Files
e48591bd82 feat: bot message policy, message lifecycle hooks, command routing and Chat rename (supersedes #2831, #2833) (#2966)
* feat(bot): support direct binding of plugin commands (LANG-240)

Co-authored-by: multica-agent <github@multica.ai>

* fix(bot): address review feedback on command routing and migration (LANG-240)

- Remove redundant cmd_mgr.is_admin call in routing layer
- Move legacy YAML command config migration to startup build_app stage with idempotency flag
- Validate that command_settings.plugins are installed in current workspace
- Cache bot command_settings in memory via platform_mgr helper
- Wrap command matching and execution inside _run_event_delivery for cloud tenant scope
- Preserve original launcher_id type in session resolution

Co-authored-by: multica-agent <github@multica.ai>

* style(bot): apply ruff format to command routing changes (LANG-240)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* wip(command): command processor instances and per-command config (LANG-238)

Work in progress handed off for completion; backend and tests are done,
web pieces are partially written and not yet type-checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(command): complete command processor configuration UI

Co-authored-by: multica-agent <github@multica.ai>

* fix(command): retain saved bot command settings when editing

Co-authored-by: multica-agent <github@multica.ai>

* test(command): exclude command instances from runner operations

Co-authored-by: multica-agent <github@multica.ai>

* test(command): verify bot prefixes and manage async test lifecycle

Co-authored-by: multica-agent <github@multica.ai>

* feat(platform): register Telegram and Discord plugin commands

Co-authored-by: multica-agent <github@multica.ai>

* fix(platform): align registration metadata and selected command diagnostics

Co-authored-by: multica-agent <github@multica.ai>

* fix(plugin): keep platform command refresh best-effort after runner refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(web): simplify bot event routing card with tabs

Split routes, plugin commands and plugin processors into tabs, collapse
the supported events panel into a dialog, keep rule rows on a stable
two-line grid, and show bound commands as compact chips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(web): move command prefixes behind a small popover button

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(web): show commands, routes and plugin processors as separate routing layers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(command): record command processor runs and support debugging

Bot command executions and debug runs are written to the run ledger as
command_processor runs, so processors get run history and traces. Debug
runs a command line once with admin privilege without platform delivery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): command processor logs, debug and plugin marketplace select

Group plugin processors and command processors under a From plugin option
on the processor creation page, redraw the processor type diagrams, add
logs and debugging to the command processor detail page, list installed
and marketplace command plugins with one-click install, and use a Remix
icon for command processors in the sidebar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(web): count new command processor locale keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): illustrate processor types with animated scenes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* revert(web): restore original processor line diagrams and add a command one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(web): count command diagram locale keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): progressive plugin options and a code-bearing plugin processor diagram

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): command plugin wording in the plugin selector

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(web): count command plugin selector locale keys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(pipeline): pin outer-stage behaviour before moving it to the message policy

Baseline cases state a legacy pipeline config and the behaviour it must
produce (group respond rules, access control, ignore rules, content filter,
rate limit, long text, sending, user notices, aggregation). They reach the
stages only through outer_stage_harness, so the same cases keep guarding
behaviour once the configuration moves to the bot.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(message-policy): add the bot message policy schema, runtime and manager

A message policy says which messages a bot answers (trigger), what is checked
on the way in and out (safety) and how replies are sent (output). It keeps the
key names these settings had inside a Messaging (pipeline) config.

- schema: neutral and default policies, bot + route merge, validation, and the
  single legacy conversion (split_legacy_config / restore_legacy_config).
- runtime: the logic of the outer stages, compiled per effective policy
  (admission, group rules, rate limit, content filter, long text, sending).
- manager: resolves the policy of a bot route and caches the compiled runtime
  per bot and route; the debug chat and unknown bots get the neutral policy.

Group respond rules and the rate limit gain an explicit enabled switch so a
policy can express "do nothing"; converted legacy settings state it as on.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(message-policy): store policies on bots and migrate them out of Messaging

- bots.message_policy (JSON) and an optional policy override on each route in
  event_bindings; BotService validates both. A route resubmitted without the
  policy key keeps its stored override, so older clients cannot drop it.
- Migration 0049: existing bots get the neutral policy and every route to a
  Messaging processor receives that processor's former settings as its
  override; the moved keys are kept verbatim in
  legacy_pipelines.message_policy_backup and restored on downgrade.
- Messaging writes accept and ignore trigger / safety / general output keys;
  its template and form metadata keep only AI, speech and AI-specific output.
- New bots start with the defaults new Messaging processors used to get.
- GET /api/v1/platform/bots/_/message-policy/metadata serves the form metadata;
  MCP bot tools describe message_policy and route overrides.
- The group-filter migration helper reads and updates the route policy.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(pipeline): run the outer stages through the message policy runtime

Stage order and position are unchanged. The group rule, access control,
content filter, rate limit, long text and send stages become thin shells over
the policy runtime of the route a message matched; user notices and the
scheduler's steering gate use it too. The effective policy is laid over
query.pipeline_config under the legacy key names, so plugins reading those
keys keep working. Message aggregation reads the policy as well.

The matched route id travels from routing through the aggregator to the query
(_message_route_id, host-reserved). Messages that reach Messaging without one
(web page widget, form callbacks) use the bot's first route to that processor.

The baseline cases now run on legacy configs converted the way the migration
converts them.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* chore(persistence): renumber message policy migrations after master (0054-0056)

Master added 0047-0053, so the bot command settings, platform command sync
and bot message policy migrations now follow 0053_knowledge_artifact_sources.
Also bind a message policy in the agent run recovery test, whose replayed
output stages now read output and safety settings from the bot route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(sdk): expose command processor configuration in execution contexts

Co-authored-by: multica-agent <github@multica.ai>

* feat(bot): dispatch plugin lifecycle hooks with route-scoped query and policy

Co-authored-by: multica-agent <github@multica.ai>

* fix(messaging): dispatch received hooks for direct pipeline queries

Co-authored-by: multica-agent <github@multica.ai>

* fix(messaging): tolerate queries without bound plugins in the received-hook fallback

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(messaging): apply bot policies to agent delivery

Co-authored-by: multica-agent <github@multica.ai>

* feat(web): bot plugins and message policy tabs, Chat rename

- Bot event routing becomes three tabs: Routes, Plugins, Message policy.
- Plugins tab: message lifecycle strip (received → command → admission →
  before reply → process → after reply → send) with the enabled plugins
  acting at each step; one row per plugin with its switch, command tags and
  hook tags. Hooks a route cannot use are struck through with the reason
  (prompt hooks on Agent routes, observe-only after-reply hook when
  streaming). Enable-all switch plus manual selection, as on Chat. Command
  settings and plugin processors live in the same tab.
- Message policy tab: entry / safety / reply forms from the policy metadata,
  bot default or per-route override (use default / custom), route overview,
  "make bot default" which also clears routes left identical to it.
- New routes show a hint that they inherit the bot policy.
- Chat editor drops Trigger and Safety; Output keeps AI-only options with a
  pointer to the bot policy; the plugin list is "Tools the AI can call".
- Installing a plugin with commands or listeners reports on how many bots it
  is enabled, or offers to go enable it.
- User-visible "Pipeline/流水线" renamed to "Chat/聊天" in all eight WebUI
  locales (identifiers, paths and keys unchanged).
- plugin-registrations (HTTP and MCP) accepts include_disabled to list every
  installed plugin for the editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(i18n): call the pipeline Chat in backend user-facing text

Default name, runner authorization notice, operation catalog labels and
summaries, alert email rule label, adapter streaming descriptions and
MCP tool descriptions say Chat (pipeline). Identifiers keep pipeline.
The group filter migration tools describe the message-policy at-bot rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): finish the Chat rename in locales and the migration dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* chore(sdk): regenerate workspace proxy for monitoring.sessions launcher_id

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* docs: message lifecycle events, bot message policy and the Chat rename

- Plugin docs: 'Pipeline events' become message lifecycle events with
  the lifecycle order, where plugins are enabled, which processors each
  hook applies to, known limits and platform notifications.
- Command docs: matching before routes, route policy, *CommandSent.
- Bots page: event routing tabs, plugin enablement, message policy.
- Chat page and the rest of docs/ (zh/en/ja, regenerated recipes) use
  Chat instead of Pipeline; URLs and identifiers are unchanged.
- langbot-mcp-ops skill, ARCHITECTURE.md and dev-docs/architecture/
  message-policy.md describe the new contracts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(bot): keep the platform command clear in update_bot after the master merge

The merge carried the branch's platform-command check into master's new
_apply_bot_configuration, where update_data does not exist, so every
runtime-affecting bot update returned 500. Run the check in update_bot
before applying. Command admin checks now pass the sender ID.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* test(persistence): register all entities in the startup command migration test

The test created bots without the tables its foreign keys reference and
only passed when other tests had imported those entities first. Also
apply prettier to AgentCreateContent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(messaging): use one listener list per query when no bot policy applies

Queries entering a Chat without a bot (debug chat, pipeline.run) bound
the neutral policy, so later hooks went to every plugin while the
fallback *MessageReceived used the Chat's plugin list. Use the Chat's
list for all hooks there. The contract test now carries the plugin
selection the way migration 0060 stores it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): move plugin command settings into the plugin list

Drop the separate plugin command binding section from the bot's Plugins tab.
The command switch and prefixes now sit in the plugin list header, per-bot
command settings open from a plugin's row (only when its commands declare
spec.config), and platform command registration follows the enabled plugins.

Duplicate command names now resolve in the order of the bot's effective plugin
list, the same order lifecycle hooks run in; the WebUI keeps that list in
display order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): mark plugin hook badges with the event listener icon

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): explain AI routes versus plugin handling on the bot tabs

Routes now say they send events to configurable LangBot processors that use
AI, and that a plugin-only bot can delete or disable its routes. The Plugins
tab explains that plugins handle their lifecycle steps as each plugin defines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): optional route notes and auto-described routes

Routes get an optional note, edited in the route's expanded panel and shown
under the route. Wherever routes are listed (scope picker, policy route list)
a second line now says when the route applies, derived from its conditions,
plus its target when the name is a note, so routes stay distinguishable
without any user input.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): compact route cards and labelled message template routes

Saved routes collapse to a two-line summary (note or processor, then event,
conditions and target); event, conditions, processor and note are edited in
the expanded card. Unsaved routes open expanded. The "Reply to messages"
template and the setup wizard now label their routes as private messages and
group messages that mention the bot.

Also move the plugin processor compatibility e2e onto the Plugins tab, where
plugin processors live since the message policy refactor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): keep bot-wide command settings read-only on route scope

The plugin command switch, prefixes and per-plugin command settings apply to
the whole bot, so they are read-only (with a hint) while a route is selected.
Turning commands off crosses out every command badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* style(bots): make the crossed-out command badges easier to see

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(agents): stop offering command processors on the create page

Command settings are created from a plugin's row on the bot's Plugins tab.
The "From plugin" card now selects plugin processors directly; existing
command processors keep their detail page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): install plugin processors from the marketplace in place

The add-plugin-processor dialog's new-configuration tab keeps the installed
processor list (with event compatibility) and adds a marketplace picker for
plugins that declare processor support; installing one selects it. Bound and
existing processors show their plugin icon, and the empty state points to the
marketplace. Plugin-subscription e2e now opens the Plugins tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(plugins): point command and listener plugins to bots after install

Commands and event listeners are enabled on a bot's Plugins tab now, so the
post-install next step for them links to bots; tools still lead to a Chat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(bots): pick plugin processors from a single picker

The new-configuration tab drops the separate installed-processor list: one
picker lists installed processors and marketplace plugins (installable in
place), and the chosen processor's events and compatibility show below it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(plugins): show next steps on first visit and reload after confirming permissions

- The plugin detail page opens a next-steps dialog the first time a ready
  plugin is visited (remembered per plugin).
- After permissions are confirmed, the page polls until the plugin is mounted
  and remounts its settings, readme and log panels, so no manual refresh is
  needed.
- The install dialog shows next steps under the permission-review link
  instead of hiding them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(plugins): say why plugin settings and docs are unavailable

While a plugin waits for permission confirmation its settings and docs cannot
load; show a dedicated notice pointing to Plugin permissions (or a starting
indicator while it boots) instead of the generic load error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(plugins): confirm permissions inside the install dialog

A plugin awaiting permission review now shows the permission card in the
install dialog; granting there opens the usual confirmation, and the dialog
then switches to the success banner with its next steps. The first-visit
next-steps popup on the plugin page is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(plugins): show next steps right after granting in the install dialog

The plugin restarts after a grant, so re-reading it could fail or still report
pending, leaving the dialog on the review banner. Trust the successful grant,
keep the already loaded manifest, and retry loading it if it was missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(plugins): treat initialized plugins as running on the detail page

The runtime moves plugins unmounted -> mounted -> initialized; initialized is
the ready state. The detail page only accepted mounted, so running plugins
showed "starting" forever. Also fix the misspelled status in the type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(plugins): re-read the plugin until it lists components before showing install next steps

A plugin awaiting permissions is not started and reports no components, so
the post-grant guide stayed empty.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): add bot plugins from a list and the Marketplace; rename event listeners to chat event hooks

The bot Plugins tab now lists added plugins as cards (all of them when
'enable all' is on) instead of per-plugin switches, with an Add plugin
dialog for installed plugins and Marketplace plugins that provide commands
or chat event hooks. EventListener is shown as 'Chat event hook' in the UI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): with all plugins enabled, the bot plugin list offers installing new plugins only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): bot plugin Marketplace tab lists only uninstalled or updatable plugins

Installed plugins with a newer Marketplace version get an inline Update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): no 'not enabled on any bot' toast for plugins installed from a bot's plugin list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): move plugin dev docs link from the routing help popover to the Plugins tab

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): open a plugin's settings page from its card in the bot plugin list

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): describe commands, chat event hooks and plugin processors by how each handles events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): drop the route overview list from the bot message policy tab

The scope selector already marks which routes are customised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): regroup bot message policy settings by what the owner decides

The policy tab now groups settings into who gets replies, how messages are
read, safety and rate limits, how the bot replies, and what happens on
errors. Each setting shows a plain-language summary and expands to purpose-
built controls; stored trigger/safety/output keys are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* refactor(web): use shadcn Button and Label for this branch's new UI

Replace raw button, link and label elements added on this branch with
shadcn Button (ghost / link / asChild) and Label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(commands): add bot system commands and sender permissions

Co-authored-by: multica-agent <github@multica.ai>

* fix(commands): honor session model, replay text turns and gate denial replies

Co-authored-by: multica-agent <github@multica.ai>

* feat(web): one-page Chat settings with prompt, tools and knowledge up front

Replace the Chat editor's section tabs with a single page: the runner,
then primary blocks for model, prompt, tools (summary + side sheet) and
knowledge, then folded rows with one-line summaries for context, run
limits, sandbox, speech, reply content, notices, advanced and manage.
Runner fields are placed by type and name, so any runner works; values and
stored keys are unchanged. Folded rows stay mounted so invalid drafts still
block saving. SettingRow/SettingGroup are shared with the bot policy tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): keep folded setting rows mounted but hidden

Radix forceMount forces content open; render the row body ourselves with
the hidden attribute so folded rows stay collapsed while their fields keep
validating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): system commands and command permissions in the bot Plugins tab

A small 'System commands · n/m' entry in the command bar opens a sheet with
the admin list (person_ IDs, /whoami hint), the no-permission reply, every
built-in command's switch and permission grouped by session/info/admin,
and per-command permissions for enabled plugins' commands. Admin-only plugin
commands show a lock on their chips; the lifecycle Command step marks the
system commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): one-page Agent settings matching the Chat layout

Replace the Agent editor's Runner / Events & tools tabs with one page: the
runner, then model and prompt, the events the Agent handles, a tool access
summary (editing in a side sheet), knowledge and runner settings, then
folded rows for context, run limits, sandbox and advanced fields. The
runner field layout is shared with Chat (runner-layout/RunnerConfigLayout).
Loading fills the active runner's schema defaults before the clean snapshot,
so required-field status and revert-to-clean keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): 'Plugins & commands' tab with its own Commands section

Rename the bot tab to Plugins & commands. Commands get their own section
above plugins: one global switch, the shared prefixes (with an example, as
they apply to system and plugin commands alike), the system commands entry
and the plugin command list. Admins are no longer edited in the system
commands sheet; it shows the bot admin count and links to the session
monitor where admins are managed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): give system and plugin commands their own sheets

The System commands sheet now lists only built-in commands; plugin command
access moves to a 'Set access' sheet on the plugin commands row. Admins and
the no-permission reply apply to both kinds, so they become rows of the
Commands section instead of living in the system sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): keep dividers between command access rows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): link plugin processor dev docs from the processors section

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(commands): use session monitoring admins for command permissions

Co-authored-by: multica-agent <github@multica.ai>

* chore(web): drop retired command_settings.admins from the bot command type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* Record message policy decisions and add workspace upgrade checks

Co-authored-by: multica-agent <github@multica.ai>

* fix(message-policy): queue EssentialCommands uninstall through plugin.delete task

The upgrade-check action called the plugin connector directly, skipping the
tenant-scoped fence and task tracking used by the regular uninstall path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): message policy monitoring badges, timeline, route counts and upgrade checks

- Monitoring: handling badges (system/plugin command, denied, policy drop,
  plugin interception), a handling filter (AI / command / plugin / policy)
  and a message policy timeline in the execution detail.
- Backend: executions accept handling= (HTTP + MCP, not plugin-visible) and
  rows carry handling, policy_layer/item, command and hook facts.
- Bot routes show last-24h handling counts.
- Upgrade check banner + Sheet on bot and Chat pages with one-click
  actions, per-item and acknowledge-all; eight locales.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(monitoring): name layer and rule for policy drops recorded before structured fields

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): name command/policy/plugin ingress rows and dedupe output actions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(message-policy): preserve drop notices, Windows fallback, 0060 enabled filter, and ignore-rules hint

Co-authored-by: multica-agent <github@multica.ai>

* docs(message-policy): update trilingual user, upgrade, telemetry and command docs

Co-authored-by: multica-agent <github@multica.ai>

* Document bot command permissions and Chat event hooks in skills

Co-authored-by: multica-agent <github@multica.ai>

* Distinguish Chat debugging from bot admission tests

Co-authored-by: multica-agent <github@multica.ai>

* Navigate to Chats from Processors in skills and QA flows

Co-authored-by: multica-agent <github@multica.ai>

* Restore bot ingress tracing and align CI with route-owned message policies

Co-authored-by: multica-agent <github@multica.ai>

* fix(web): stop the bot plugins tab crashing without runtime registrations; align e2e with the Chat UI

pluginCommandList read descriptorMap before its declaration, so the Plugins &
commands tab threw a TDZ error whenever an enabled plugin had no Runtime
registration (older Runtimes). Compute it after the map.

Update stale Playwright specs to the current UI: Chat migration labels,
one-page Chat editor (no AI tab, Runner field), 'Create processor' heading,
and the in-dialog permission review after plugin installation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(telemetry): count builtin_disabled_bots only for built-ins turned off from their default

/model is off by default, so counting any disabled built-in counted every
bot and the heartbeat field carried no signal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(migration): preserve empty legacy chat settings on downgrade

Co-authored-by: multica-agent <github@multica.ai>

* fix(migration): initialize bot policies when resuming 0059

Co-authored-by: multica-agent <github@multica.ai>

* test(commands): exercise LocalAgent over signed HTTP ingress

Co-authored-by: multica-agent <github@multica.ai>

* fix(api): report ignored legacy settings in chat copy requests

Co-authored-by: multica-agent <github@multica.ai>

* test(commands): cover alternate prefixes and unrouted group commands

Co-authored-by: multica-agent <github@multica.ai>

* fix(web): policy timeline says MessageReceived already ran when admission blocks

MessageReceived fires at the bot entry before admission, so a policy drop
still ran it. The hooks step now says so instead of 'not run'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(commands): consume silently denied commands before primary routing

Co-authored-by: multica-agent <github@multica.ai>

* Test upgrade assistant actions and command telemetry against a local Core

Co-authored-by: multica-agent <github@multica.ai>

* Verify lifecycle hooks and command bypass during message aggregation

Co-authored-by: multica-agent <github@multica.ai>

* Verify native Agent reply chunks and proactive delivery through signed callbacks

Co-authored-by: multica-agent <github@multica.ai>

* Cover subscriber replies on denied ingress and concurrent command rate limits

Co-authored-by: multica-agent <github@multica.ai>

* Verify LocalAgent records missing model failures for signed messages

Co-authored-by: multica-agent <github@multica.ai>

* Skip runtime synchronization for empty event selections after validating workspace scope

Co-authored-by: multica-agent <github@multica.ai>

* Verify route access overrides, removal and telemetry using signed bot messages

Co-authored-by: multica-agent <github@multica.ai>

* Exercise signed command admission and reply policies in a running Core

Co-authored-by: multica-agent <github@multica.ai>

* Compare dashboard debug chat with signed messages on the same Chat

Co-authored-by: multica-agent <github@multica.ai>

* Validate unavailable Agent runners and verify native quotes and Agent policy traces

Co-authored-by: multica-agent <github@multica.ai>

* Correlate successful Agent output with telemetry and exercise command hook order

Co-authored-by: multica-agent <github@multica.ai>

* Honor Chat exception policy for Runner failures and verify streaming observers

Co-authored-by: multica-agent <github@multica.ai>

* Verify OneBot membership events bypass message admission and reply policies

Co-authored-by: multica-agent <github@multica.ai>

* Exercise command name precedence and processor instance isolation in runtime

Co-authored-by: multica-agent <github@multica.ai>

* Accept ISO source times in runner events and verify long-text boundaries

Co-authored-by: multica-agent <github@multica.ai>

* Compare Chat output filtering on OneBot and HTTP Bot

Co-authored-by: multica-agent <github@multica.ai>

* Trace matched deliveries intercepted by message listeners

Co-authored-by: multica-agent <github@multica.ai>

* Record Chat execution owner with the first success update

Co-authored-by: multica-agent <github@multica.ai>

* Admit matched commands before recording listener interception

Co-authored-by: multica-agent <github@multica.ai>

* Handle stop on a Chat without a Runner and verify built-in command permissions

Co-authored-by: multica-agent <github@multica.ai>

* Link command processor runs to ingress routes and identify denied plugin commands

Co-authored-by: multica-agent <github@multica.ai>

* Report ignored legacy operation keys and limit Runner error replies to a redacted summary

Co-authored-by: multica-agent <github@multica.ai>

* style(web): wrap long monitoring timeline strings for prettier

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* Dispatch QA Runner by envelope type and verify remaining command conflicts after uninstall

Co-authored-by: multica-agent <github@multica.ai>

* fix(persistence): chain bot command settings after master's 0057 migration

master added 0057_agent_event_index on top of 0056, which left two Alembic
heads. Run 0057_bot_command_settings after it; revision ids are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: multica-agent <github@multica.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 08:20:44 +08:00

2289 lines
74 KiB
Python

from __future__ import annotations
import asyncio
import io
import os
import zipfile
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock
import pytest
from langbot_plugin.api.definition.components.base import NoneComponent
from langbot_plugin.api.definition.components.manifest import ComponentManifest
from langbot_plugin.api.definition.plugin import NonePlugin
from langbot_plugin.api.entities.builtin.runner.result import RunnerResult
from langbot_plugin.api.entities.builtin.command.context import CommandReturn
from langbot_plugin.api.entities.builtin.provider.message import Message
from langbot_plugin.api.entities.context import EventContext
from langbot_plugin.api.entities.builtin.platform import message as platform_message
from langbot_plugin.api.entities.events import (
PersonCommandSent,
PersonNormalMessageReceived,
)
from langbot_plugin.runtime.helper import marketplace as marketplace_helper
from langbot_plugin.runtime.plugin.container import (
ComponentContainer,
PluginContainer,
RuntimeContainerStatus,
)
from langbot_plugin.runtime.plugin import mgr as manager_module
from langbot_plugin.runtime.plugin.mgr import PluginInstallSource, PluginManager
from langbot_plugin.entities.io.actions.enums import RuntimeToLangBotAction
from langbot_plugin.entities.io.errors import (
DependencyInstallError,
DependencyVerificationError,
)
from langbot_plugin.entities.io.context import ActionContext, InstallationBinding
from langbot_plugin.runtime.context import RuntimeContext
from langbot_plugin.runtime.security import PLUGIN_REGISTRATION_CAPABILITY_ENV
def _manifest(
kind: str = "Plugin",
name: str = "demo",
author: str = "tester",
spec: dict[str, Any] | None = None,
) -> ComponentManifest:
return ComponentManifest(
owner=author,
rel_path=f"{name}.yaml",
manifest={
"apiVersion": "v1",
"kind": kind,
"metadata": {
"name": name,
"label": {"en_US": name.title()},
"author": author,
"version": "1.0.0",
},
"spec": spec or {},
},
)
def _component(kind: str, name: str, spec: dict[str, Any] | None = None):
return ComponentContainer(
manifest=_manifest(kind=kind, name=name, spec=spec),
component_instance=NoneComponent(),
component_config={},
)
def _plugin(
name: str = "demo",
author: str = "tester",
*,
components: list[ComponentContainer] | None = None,
status: RuntimeContainerStatus = RuntimeContainerStatus.INITIALIZED,
enabled: bool = True,
debug: bool = False,
) -> PluginContainer:
return PluginContainer(
debug=debug,
install_source="local",
install_info={},
manifest=_manifest(name=name, author=author),
plugin_instance=NonePlugin(),
enabled=enabled,
priority=0,
plugin_config={},
status=status,
components=components or [],
)
def _manager() -> PluginManager:
manager = PluginManager(SimpleNamespace(ws_debug_port=18080))
manager.plugins = []
manager.plugin_handlers = []
manager.plugin_run_tasks = []
return manager
def _registration_capability(
manager: PluginManager,
plugin: PluginContainer,
) -> str:
return manager._issue_registration_capability(
plugin_author=str(plugin.manifest.metadata.author),
plugin_name=plugin.manifest.metadata.name,
plugin_path=f"/tmp/{plugin.manifest.metadata.author}__{plugin.manifest.metadata.name}",
)
def _write_installed_plugin(
root,
*,
author: str = "tester",
name: str = "demo",
):
plugin_path = root / f"{author}__{name}"
plugin_path.mkdir()
(plugin_path / "manifest.yaml").write_text(
f"""
apiVersion: v1
kind: Plugin
metadata:
author: {author}
name: {name}
spec: {{}}
""",
encoding="utf-8",
)
return plugin_path
def _bound_runtime_context(
control_handler: FakeControlHandler | None = None,
) -> RuntimeContext:
context = RuntimeContext()
context.ws_debug_port = 18080
if control_handler is not None:
context.control_handler = control_handler
context.bind_workspace(
ActionContext(
instance_uuid="instance-1",
workspace_uuid="workspace-a",
placement_generation=9,
)
)
return context
def _plugin_zip(author: str = "tester", name: str = "demo", version: str = "1.0.0"):
manifest = f"""
apiVersion: v1
kind: Plugin
metadata:
name: {name}
label:
en_US: Demo
author: {author}
version: {version}
spec: {{}}
"""
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("manifest.yaml", manifest)
archive.writestr("main.py", "")
return buffer.getvalue()
@pytest.mark.asyncio
async def test_launch_plugin_uses_sanitized_environment(monkeypatch, tmp_path):
from langbot_plugin.runtime.plugin import mgr as mgr_module
captured: dict[str, Any] = {}
class FakeStdioClientController:
process = None
def __init__(self, command, args, env, working_dir, *, capture_stderr=False):
captured["capture_stderr"] = capture_stderr
captured["command"] = command
captured["args"] = args
captured["env"] = env
captured["working_dir"] = working_dir
async def run(self, new_connection_callback):
raise asyncio.CancelledError()
monkeypatch.setenv("PYTHONPATH", "/tmp/langbot-plugin-sdk/src")
monkeypatch.setattr(mgr_module, "get_platform", lambda: "linux")
monkeypatch.setattr(
mgr_module.pkgmgr_helper,
"get_plugin_site_packages",
lambda _plugin_path: "/tmp/plugin-dependencies",
)
monkeypatch.setattr(
mgr_module.stdio_client_controller,
"StdioClientController",
FakeStdioClientController,
)
plugin_path = _write_installed_plugin(tmp_path)
manager = _manager()
await manager.launch_plugin(str(plugin_path))
assert captured["working_dir"] == str(plugin_path)
# Plugin logs page reads the captured stderr stream.
assert captured["capture_stderr"] is True
assert captured["env"] is not os.environ
assert captured["env"]["PYTHONPATH"] == os.pathsep.join(
(
str(manager.worker_launcher.runtime_import_root),
"/tmp/plugin-dependencies",
)
)
assert "/tmp/langbot-plugin-sdk/src" not in captured["env"]["PYTHONPATH"]
assert captured["env"][PLUGIN_REGISTRATION_CAPABILITY_ENV]
class FakeControlHandler:
def __init__(self):
self.calls: list[tuple[Any, dict[str, Any]]] = []
self.contexts: list[ActionContext | None] = []
async def call_action(self, action, payload, *, action_context=None):
self.calls.append((action, payload))
self.contexts.append(action_context)
return {
"enabled": True,
"priority": 7,
"plugin_config": {"api_key": "secret"},
"install_source": PluginInstallSource.MARKETPLACE.value,
"install_info": {"plugin_version": "1.0.0"},
"installation_uuid": "installation-1",
}
class FakeConnection:
closed = False
async def close(self):
self.closed = True
class FakeLogBuffer:
has_active_reader = False
def __init__(self):
self.entries = []
def add_entry(self, level, text):
self.entries.append((level, text))
def get_logs(self, limit=200, level=None):
return [{"limit": limit, "level": level, "text": "ready"}]
class FakeHandler:
def __init__(self, plugin: PluginContainer):
self.plugin = plugin
self.debug_plugin = False
self.conn = FakeConnection()
self.stdio_process = None
self.initialized_with = None
self.shutdown_calls = 0
self.diagnostics = []
self.log_buffer = FakeLogBuffer()
self.agent_run_calls: list[tuple[Any, dict[str, Any], float]] = []
self.bound_action_context = None
self.files = {
"icon-key": b"<svg/>",
"readme-key": b"# Demo",
"asset-key": b"asset-bytes",
}
def bind_action_context(self, action_context):
self.bound_action_context = action_context
return action_context
async def initialize_plugin(self, plugin_settings):
self.initialized_with = plugin_settings
async def get_plugin_container(self):
refreshed = self.plugin.model_dump()
refreshed["status"] = RuntimeContainerStatus.INITIALIZED.value
return refreshed
async def shutdown_plugin(self):
self.shutdown_calls += 1
async def notify_plugin_diagnostic(self, diagnostic):
self.diagnostics.append(diagnostic)
return {"ok": True}
async def emit_event(self, event_context):
return {"emitted": True, "event_context": event_context}
async def call_tool(
self,
tool_name,
tool_parameters,
session,
query_id,
query_uuid=None,
):
query_ref = {"query_id": query_id}
if query_uuid is not None:
query_ref["query_uuid"] = query_uuid
return {
"tool_response": {
"tool_name": tool_name,
"params": tool_parameters,
**query_ref,
}
}
async def execute_command(self, command_context):
yield {"command_response": {"text": command_context["command"]}}
async def call_action_generator(self, action, data, timeout=300):
self.agent_run_calls.append((action, data, timeout))
run_id = data["context"]["run_id"]
yield RunnerResult.message_completed(
run_id=run_id,
message=Message(role="assistant", content="toy runner ok"),
).model_dump(mode="json")
yield RunnerResult.run_completed(
run_id=run_id,
finish_reason="stop",
).model_dump(mode="json")
async def get_plugin_icon(self):
return {"plugin_icon_file_key": "icon-key", "mime_type": "image/svg+xml"}
async def get_plugin_readme(self, language="en"):
return {"plugin_readme_file_key": "readme-key", "language": language}
async def get_plugin_assets_file(self, file_key):
if file_key == "missing":
return {"file_file_key": "", "mime_type": ""}
return {"file_file_key": "asset-key", "mime_type": "text/plain"}
async def read_local_file(self, file_key):
return self.files[file_key]
async def delete_local_file(self, file_key):
del self.files[file_key]
async def call_page_api(self, page_id, endpoint, method, body):
return {
"data": {
"page_id": page_id,
"endpoint": endpoint,
"method": method,
"body": body,
},
"error": None,
}
async def get_rag_capabilities(self):
return {"capabilities": ["ingest", "retrieve"]}
async def retrieve_knowledge(self, retriever_name, retrieval_context):
return {
"retriever_name": retriever_name,
"retrieval_context": retrieval_context,
}
async def rag_ingest_document(self, context_data):
return {"ingested": context_data["document_id"]}
async def rag_delete_document(self, kb_id, document_id):
return {"deleted": [kb_id, document_id]}
async def rag_on_kb_create(self, kb_id, config):
return {"created": kb_id, "config": config}
async def rag_on_kb_delete(self, kb_id):
return {"deleted_kb": kb_id}
async def parse_document(self, context_data, file_bytes):
return {"context": context_data, "text": file_bytes.decode()}
class ReplyChangingFakeHandler(FakeHandler):
async def emit_event(self, event_context):
event_context["event"]["reply_message_chain"] = [
{"type": "Plain", "text": "plugin reply"}
]
return {"emitted": True, "event_context": event_context}
class DefaultPreventingFakeHandler(FakeHandler):
async def emit_event(self, event_context):
event_context["is_prevent_default"] = True
return {"emitted": True, "event_context": event_context}
class QueryUuidChangingFakeHandler(FakeHandler):
async def emit_event(self, event_context):
event_context["query_uuid"] = "query-forged"
event_context["event"]["query_uuid"] = "query-forged"
return {"emitted": True, "event_context": event_context}
class QueryUuidDroppingFakeHandler(FakeHandler):
async def emit_event(self, event_context):
event_context.pop("query_uuid", None)
event_context["event"].pop("query_uuid", None)
return {"emitted": True, "event_context": event_context}
def test_plugin_manager_instances_should_not_share_plugin_state():
PluginManager.plugins = []
first = PluginManager(SimpleNamespace())
second = PluginManager(SimpleNamespace())
first.plugins.append(_plugin())
assert second.plugins == []
@pytest.mark.asyncio
async def test_launch_plugin_passes_registration_capability_not_debug_key(
monkeypatch, tmp_path
):
captured: dict[str, Any] = {}
class FakeStdioController:
process = None
def __init__(self, command, args, env, working_dir, **_kwargs):
captured.update(
command=command,
args=args,
env=env,
working_dir=working_dir,
)
async def run(self, _callback):
return None
monkeypatch.setattr(manager_module, "get_platform", lambda: "linux")
monkeypatch.setattr(
manager_module.stdio_client_controller,
"StdioClientController",
FakeStdioController,
)
plugin_path = _write_installed_plugin(tmp_path)
await _manager().launch_plugin(str(plugin_path))
assert "--plugin-debug-key" not in captured["args"]
assert "PLUGIN_DEBUG_KEY" not in captured["env"]
capability = captured["env"]["LANGBOT_PLUGIN_REGISTRATION_CAPABILITY"]
assert len(capability) >= 32
@pytest.mark.asyncio
async def test_windows_launch_uses_minimal_env_and_fences_runtime_url(
monkeypatch, tmp_path
):
captured: dict[str, Any] = {}
class FakeProcess:
async def wait(self):
return 0
async def fake_create_subprocess_exec(*args, **kwargs):
captured.update(args=args, kwargs=kwargs)
return FakeProcess()
monkeypatch.setattr(manager_module, "get_platform", lambda: "win32")
monkeypatch.setattr(
manager_module.asyncio,
"create_subprocess_exec",
fake_create_subprocess_exec,
)
monkeypatch.setenv("RUNTIME_WS_URL", "ws://untrusted.example/plugin/ws")
monkeypatch.setenv("LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN", "runtime-secret")
monkeypatch.setenv("LANGBOT_BOX_CONTROL_TOKEN", "box-secret")
monkeypatch.setenv("UNRELATED_SECRET", "also-secret")
plugin_path = _write_installed_plugin(tmp_path)
await _manager().launch_plugin(str(plugin_path))
assert "--plugin-debug-key" not in captured["args"]
child_env = captured["kwargs"]["env"]
assert "PLUGIN_DEBUG_KEY" not in child_env
assert "LANGBOT_PLUGIN_RUNTIME_CONTROL_TOKEN" not in child_env
assert "LANGBOT_BOX_CONTROL_TOKEN" not in child_env
assert "UNRELATED_SECRET" not in child_env
assert len(child_env["LANGBOT_PLUGIN_REGISTRATION_CAPABILITY"]) >= 32
assert child_env["RUNTIME_WS_URL"] == "ws://localhost:18080/plugin/ws"
assert child_env["PYTHONUTF8"] == "1"
assert child_env["PYTHONIOENCODING"] == "utf-8"
assert captured["kwargs"]["stdout"] is manager_module.sys.stderr
@pytest.mark.asyncio
async def test_windows_launch_cancellation_reaps_worker(monkeypatch, tmp_path):
class HangingProcess:
def __init__(self):
self.returncode = None
self.wait_started = asyncio.Event()
self.release = asyncio.Event()
async def wait(self):
self.wait_started.set()
await self.release.wait()
process = HangingProcess()
async def fake_create_subprocess_exec(*_args, **_kwargs):
return process
async def stop_process(stopped_process):
assert stopped_process is process
process.returncode = -9
process.release.set()
return True
monkeypatch.setattr(manager_module, "get_platform", lambda: "win32")
monkeypatch.setattr(
manager_module.asyncio,
"create_subprocess_exec",
fake_create_subprocess_exec,
)
monkeypatch.setattr(
manager_module.stdio_client_controller,
"stop_process",
AsyncMock(side_effect=stop_process),
)
plugin_path = _write_installed_plugin(tmp_path)
launch_task = asyncio.create_task(_manager().launch_plugin(str(plugin_path)))
await process.wait_started.wait()
launch_task.cancel()
with pytest.raises(asyncio.CancelledError):
await launch_task
manager_module.stdio_client_controller.stop_process.assert_awaited_once_with(
process
)
@pytest.mark.asyncio
async def test_launch_all_plugins_waits_for_trusted_workspace_binding(monkeypatch):
context = RuntimeContext()
context.ws_debug_port = 18080
manager = PluginManager(context)
context.plugin_mgr = manager
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.glob.glob",
lambda _pattern: [],
)
launch_task = asyncio.create_task(manager.launch_all_plugins())
await asyncio.sleep(0)
assert not launch_task.done()
context.bind_workspace(
ActionContext(
instance_uuid="instance-1",
workspace_uuid="workspace-a",
placement_generation=9,
)
)
await launch_task
def test_find_plugin_and_component_lists_respect_include_filters():
manager = _manager()
tool = _component("Tool", "lookup")
command = _component("Command", "admin")
parser = _component("Parser", "pdf", {"supported_mime_types": ["application/pdf"]})
manager.plugins = [
_plugin(name="demo", components=[tool, command, parser]),
_plugin(name="other", components=[_component("Tool", "skip")]),
]
assert manager.find_plugin("tester", "demo") is manager.plugins[0]
assert manager.find_plugin("tester", "missing") is None
tools = asyncio.run(manager.list_tools(include_plugins=["tester/demo"]))
commands = asyncio.run(manager.list_commands(include_plugins=["tester/demo"]))
parsers = asyncio.run(manager.list_parsers())
assert [tool.metadata.name for tool in tools] == ["lookup"]
assert [command.metadata.name for command in commands] == ["admin"]
assert parsers[0]["plugin_id"] == "tester/demo"
assert parsers[0]["supported_mime_types"] == ["application/pdf"]
@pytest.mark.asyncio
async def test_notify_plugin_diagnostic_routes_to_target_and_log_buffer():
manager = _manager()
plugin = _plugin()
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
diagnostic = {
"level": "ERROR",
"code": "deferred_response_delivery_failed",
"message": "Deferred response delivery failed",
"plugin": {"author": "tester", "name": "demo"},
"query": {
"query_id": 123,
"event_name": "GroupNormalMessageReceived",
"stage": "SendResponseBackStage",
},
"delivery": {
"error_type": "ActionFailed",
"error_message": "retcode=1200",
},
"message_chain": {
"component_types": ["Plain", "Image"],
"component_count": 2,
},
}
await manager.notify_plugin_diagnostic(diagnostic)
assert handler.diagnostics == [
{
"level": "ERROR",
"code": "deferred_response_delivery_failed",
"message": "Deferred response delivery failed",
"details": {
"query_id": 123,
"event_name": "GroupNormalMessageReceived",
"stage": "SendResponseBackStage",
"delivery_error": "ActionFailed: retcode=1200",
"message_chain": {
"component_types": ["Plain", "Image"],
"component_count": 2,
},
},
}
]
assert handler.log_buffer.entries == [
(
"ERROR",
"[deferred_response_delivery_failed] Deferred response delivery failed"
" | query_id=123 | event=GroupNormalMessageReceived"
" | stage=SendResponseBackStage"
" | delivery_error=ActionFailed: retcode=1200",
)
]
@pytest.mark.asyncio
async def test_notify_plugin_diagnostic_missing_target_only_warns(caplog):
manager = _manager()
manager.plugins = []
caplog.set_level("WARNING")
await manager.notify_plugin_diagnostic(
{
"level": "ERROR",
"code": "deferred_response_delivery_failed",
"message": "Deferred response delivery failed",
"plugin": {"author": "tester", "name": "missing"},
}
)
assert "Plugin diagnostic target not found (tester/missing)" in caplog.text
@pytest.mark.asyncio
async def test_notify_plugin_diagnostic_skips_synthetic_log_with_active_reader():
manager = _manager()
plugin = _plugin()
handler = FakeHandler(plugin)
handler.log_buffer.has_active_reader = True
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
await manager.notify_plugin_diagnostic(
{
"level": "ERROR",
"code": "deferred_response_delivery_failed",
"message": "Deferred response delivery failed",
"plugin": {"author": "tester", "name": "demo"},
}
)
assert handler.diagnostics
assert handler.log_buffer.entries == []
@pytest.mark.asyncio
async def test_install_plugin_from_file_extracts_manifest_to_staging(
tmp_path,
monkeypatch,
):
monkeypatch.chdir(tmp_path)
manager = _manager()
old_plugin = _plugin(name="demo")
old_plugin._runtime_plugin_handler = FakeHandler(old_plugin)
manager.plugins = [old_plugin]
old_path = tmp_path / "data/plugins/tester__demo"
old_path.mkdir(parents=True)
(old_path / "old.py").write_text("", encoding="utf-8")
new_path, author, name, version = await manager.install_plugin_from_file(
_plugin_zip(version="2.0.0")
)
staged = tmp_path / new_path
assert (staged / "manifest.yaml").exists()
assert new_path.startswith("data/.plugin-staging/tester__demo-")
assert (author, name, version) == ("tester", "demo", "2.0.0")
assert manager.plugins == [old_plugin]
assert (old_path / "old.py").exists()
@pytest.mark.asyncio
async def test_install_plugin_from_file_rejects_same_version_duplicate(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
manager.plugins = [_plugin(name="demo")]
with pytest.raises(ValueError, match="already exists"):
await manager.install_plugin_from_file(_plugin_zip(version="1.0.0"))
@pytest.mark.asyncio
async def test_install_plugin_from_file_reuses_verified_extractor(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
with zipfile.ZipFile(io.BytesIO(_plugin_zip()), "r") as source:
manifest = source.read("manifest.yaml")
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("manifest.yaml", manifest)
archive.writestr("../escaped.py", "unsafe")
with pytest.raises(ValueError, match="unsafe path"):
await manager.install_plugin_from_file(buffer.getvalue())
assert not (tmp_path / "escaped.py").exists()
def test_idle_plugin_operation_locks_are_not_retained():
manager = _manager()
lock = manager._get_plugin_operation_lock("tester", "transient")
manager._forget_plugin_operation_lock("tester", "transient", lock)
assert manager._plugin_operation_locks == {}
@pytest.mark.asyncio
async def test_dependency_reconciliation_isolates_plugin_failures(monkeypatch):
manager = _manager()
async def fake_install(plugin_path):
if plugin_path.endswith("bad"):
raise OSError("venv unavailable")
return 0, ""
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.glob.glob",
lambda pattern: ["data/plugins/bad", "data/plugins/good"],
)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.os.path.isdir",
lambda path: True,
)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.pkgmgr_helper.install_requirements_isolated",
fake_install,
)
await manager.ensure_all_plugins_dependencies_installed()
assert manager._dependency_errors == {
"data/plugins/bad": "OSError: venv unavailable"
}
@pytest.mark.asyncio
async def test_activation_stops_supervisor_without_registered_container(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
target_path = tmp_path / "data/plugins/tester__demo"
target_path.mkdir(parents=True)
(target_path / "old.py").write_text("old", encoding="utf-8")
staging_path = tmp_path / "data/.plugin-staging/tester__demo-new"
staging_path.mkdir(parents=True)
(staging_path / "new.py").write_text("new", encoding="utf-8")
manager.stop_plugin_supervisor = AsyncMock()
await manager._activate_staged_plugin(str(staging_path), "tester", "demo")
manager.stop_plugin_supervisor.assert_awaited_once_with("data/plugins/tester__demo")
assert (target_path / "new.py").is_file()
@pytest.mark.asyncio
async def test_activation_failure_restores_and_restarts_previous_generation(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
target_path = tmp_path / "data/plugins/tester__demo"
target_path.mkdir(parents=True)
(target_path / "old.py").write_text("old", encoding="utf-8")
staging_path = tmp_path / "data/.plugin-staging/tester__demo-new"
staging_path.mkdir(parents=True)
(staging_path / "new.py").write_text("new", encoding="utf-8")
manager.stop_plugin_supervisor = AsyncMock()
restarted = []
manager.start_plugin_supervisor = lambda path: restarted.append(path)
real_replace = os.replace
def fail_new_generation(source, destination):
if str(source) == str(staging_path):
raise OSError("swap failed")
return real_replace(source, destination)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.os.replace",
fail_new_generation,
)
with pytest.raises(OSError, match="swap failed"):
await manager._activate_staged_plugin(str(staging_path), "tester", "demo")
assert (target_path / "old.py").read_text(encoding="utf-8") == "old"
assert restarted == ["data/plugins/tester__demo"]
@pytest.mark.asyncio
async def test_install_plugin_raises_when_dependency_install_fails(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
plugin_path = tmp_path / "data/plugins/tester__demo"
plugin_path.mkdir(parents=True)
(plugin_path / "requirements.txt").write_text("missing-package\n", encoding="utf-8")
manager = _manager()
async def fake_install_from_file(plugin_file):
return "data/plugins/tester__demo", "tester", "demo", "1.0.0"
call_count = {"n": 0}
async def fake_install_single_async(
dep, extra_params=None, *, python_executable=None, timeout_sec=300
):
call_count["n"] += 1
return 1, 0, "pip could not find package"
# No real sleeping between retries.
async def fake_sleep(delay):
return None
async def fake_ensure_plugin_environment(plugin_path):
return "plugin-python"
monkeypatch.setattr(manager, "install_plugin_from_file", fake_install_from_file)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.pkgmgr_helper.ensure_plugin_environment",
fake_ensure_plugin_environment,
)
monkeypatch.setattr(
"langbot_plugin.runtime.helper.pkgmgr.install_single_async",
fake_install_single_async,
)
monkeypatch.setattr(
"langbot_plugin.runtime.helper.pkgmgr.asyncio.sleep",
fake_sleep,
)
progress = []
with pytest.raises(DependencyInstallError) as exc_info:
async for item in manager.install_plugin(
PluginInstallSource.LOCAL,
{"plugin_file": b"zip"},
):
progress.append(item["current_action"])
err = exc_info.value
assert err.plugin == "tester/demo"
assert err.failed == ["missing-package"]
# pip stderr preserved in structured details for debugging.
assert "pip could not find package" in err.details["missing-package"]
# install_with_retry must have retried up to max_retries (3) before giving up.
assert call_count["n"] == 3
assert progress[0] == "downloading plugin package"
assert "installing dependencies" in progress
assert "initializing plugin settings" not in progress
assert "launching plugin" not in progress
@pytest.mark.asyncio
async def test_install_plugin_raises_verification_error_when_pip_lies(
tmp_path, monkeypatch
):
"""pip reports success but the dependency is still unsatisfiable."""
monkeypatch.chdir(tmp_path)
plugin_path = tmp_path / "data/plugins/tester__demo"
plugin_path.mkdir(parents=True)
(plugin_path / "requirements.txt").write_text(
"langbot-absent-after-install\n", encoding="utf-8"
)
manager = _manager()
async def fake_install_from_file(plugin_file):
return "data/plugins/tester__demo", "tester", "demo", "1.0.0"
# pip exits 0 (success) but nothing actually got installed.
async def fake_install_single_async(
dep, extra_params=None, *, python_executable=None, timeout_sec=300
):
return 0, 0, "Successfully installed langbot-absent-after-install"
monkeypatch.setattr(manager, "install_plugin_from_file", fake_install_from_file)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.pkgmgr_helper.ensure_plugin_environment",
lambda plugin_path: asyncio.sleep(0, result="plugin-python"),
)
monkeypatch.setattr(
"langbot_plugin.runtime.helper.pkgmgr.install_single_async",
fake_install_single_async,
)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr.pkgmgr_helper.classify_requirements_in_environment",
lambda python, deps: asyncio.sleep(
0, result=(["langbot-absent-after-install"], [])
),
)
with pytest.raises(DependencyVerificationError) as exc_info:
async for _ in manager.install_plugin(
PluginInstallSource.LOCAL,
{"plugin_file": b"zip"},
):
pass
err = exc_info.value
assert err.plugin == "tester/demo"
assert "langbot-absent-after-install" in err.missing
assert err.version_mismatch == []
@pytest.mark.asyncio
async def test_register_plugin_initializes_settings_and_refreshes_container():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
plugin = _plugin(
name="demo",
components=[_component("Tool", "lookup")],
status=RuntimeContainerStatus.MOUNTED,
)
handler = FakeHandler(plugin)
capability = _registration_capability(manager, plugin)
await manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=capability,
)
registered = manager.plugins[0]
assert registered._runtime_plugin_handler is handler
assert registered.install_source == PluginInstallSource.MARKETPLACE.value
assert registered.install_info == {"plugin_version": "1.0.0"}
assert registered.status is RuntimeContainerStatus.INITIALIZED
assert [
component.manifest.metadata.name for component in registered.components
] == ["lookup"]
assert handler.initialized_with["plugin_config"] == {"api_key": "secret"}
@pytest.mark.asyncio
async def test_register_plugin_binds_installation_from_trusted_host_settings():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
workspace_binding = manager.context.workspace_binding
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
handler = FakeHandler(plugin)
capability = _registration_capability(manager, plugin)
await manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=capability,
)
assert handler.bound_action_context == workspace_binding.for_installation(
"installation-1"
)
@pytest.mark.asyncio
async def test_registration_capability_is_one_use_and_manifest_bound():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
expected = _plugin(status=RuntimeContainerStatus.MOUNTED)
forged = _plugin(
author="attacker",
name="forged",
status=RuntimeContainerStatus.MOUNTED,
)
capability = _registration_capability(manager, expected)
with pytest.raises(ValueError, match="manifest identity"):
await manager.register_plugin(
FakeHandler(forged),
forged.model_dump(),
registration_capability=capability,
)
assert control_handler.calls == []
assert not manager.is_registration_capability_pending(capability)
with pytest.raises(ValueError, match="invalid or already used"):
await manager.register_plugin(
FakeHandler(expected),
expected.model_dump(),
registration_capability=capability,
)
@pytest.mark.asyncio
async def test_registered_plugin_cannot_change_manifest_identity_on_refresh():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
handler = FakeHandler(plugin)
capability = _registration_capability(manager, plugin)
async def forged_container():
payload = plugin.model_dump()
payload["manifest"]["manifest"]["metadata"]["name"] = "forged"
return payload
handler.get_plugin_container = forged_container
with pytest.raises(ValueError, match="changed its manifest identity"):
await manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=capability,
)
assert manager.plugins == []
@pytest.mark.asyncio
async def test_register_plugin_waits_for_binding_before_host_settings_request():
manager = _manager()
control_handler = FakeControlHandler()
context = RuntimeContext()
context.control_handler = control_handler
context.ws_debug_port = 18080
manager.context = context
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
handler = FakeHandler(plugin)
capability = _registration_capability(manager, plugin)
register_task = asyncio.create_task(
manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=capability,
)
)
await asyncio.sleep(0)
assert not register_task.done()
assert control_handler.calls == []
context.bind_workspace(
ActionContext(
instance_uuid="instance-1",
workspace_uuid="workspace-a",
placement_generation=9,
)
)
await register_task
assert [call[0] for call in control_handler.calls] == [
RuntimeToLangBotAction.GET_PLUGIN_SETTINGS
]
assert handler.bound_action_context == context.workspace_binding.for_installation(
"installation-1"
)
@pytest.mark.asyncio
async def test_register_plugin_rejects_missing_installation_capability():
manager = _manager()
control_handler = FakeControlHandler()
async def settings_without_installation(action, payload, *, action_context=None):
result = await FakeControlHandler.call_action(
control_handler, action, payload, action_context=action_context
)
result.pop("installation_uuid")
return result
control_handler.call_action = settings_without_installation
manager.context = _bound_runtime_context(control_handler)
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
capability = _registration_capability(manager, plugin)
with pytest.raises(ValueError, match="installation capability"):
await manager.register_plugin(
FakeHandler(plugin),
plugin.model_dump(),
registration_capability=capability,
)
assert manager.plugins == []
@pytest.mark.asyncio
async def test_register_debug_plugin_initializes_settings_first():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
plugin = _plugin(name="debug", status=RuntimeContainerStatus.MOUNTED)
handler = FakeHandler(plugin)
handler.debug_plugin = True
handler.bound_action_context = manager.context.workspace_binding
await manager.register_plugin(handler, plugin.model_dump(), debug_plugin=True)
assert control_handler.contexts[:2] == [
manager.context.workspace_binding,
manager.context.workspace_binding,
]
assert [call[0] for call in control_handler.calls] == [
RuntimeToLangBotAction.INITIALIZE_PLUGIN_SETTINGS,
RuntimeToLangBotAction.GET_PLUGIN_SETTINGS,
]
assert (
control_handler.calls[0][1]["install_source"] == PluginInstallSource.DEBUG.value
)
assert manager.plugins[0].debug is True
@pytest.mark.asyncio
async def test_register_plugin_requires_control_handler():
manager = _manager()
manager.context = _bound_runtime_context()
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
capability = _registration_capability(manager, plugin)
with pytest.raises(ValueError, match="Failed to get plugin settings"):
await manager.register_plugin(
FakeHandler(plugin),
plugin.model_dump(),
registration_capability=capability,
)
@pytest.mark.asyncio
async def test_minimal_toy_plugin_registers_and_dispatches_core_surfaces():
manager = _manager()
control_handler = FakeControlHandler()
manager.context = _bound_runtime_context(control_handler)
components = [
_component("Tool", "lookup"),
_component("Command", "admin"),
_component("Page", "settings"),
_component(
"Runner",
"default",
{
"usages": ["agent"],
"capabilities": {"streaming": True},
"permissions": {},
"config": [],
},
),
]
plugin = _plugin(
name="toy",
components=components,
status=RuntimeContainerStatus.MOUNTED,
)
handler = FakeHandler(plugin)
capability = _registration_capability(manager, plugin)
await manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=capability,
)
assert [tool.metadata.name for tool in await manager.list_tools()] == ["lookup"]
assert [tool.owner for tool in await manager.list_tools()] == ["tester/toy"]
assert [command.metadata.name for command in await manager.list_commands()] == [
"admin"
]
assert await manager.call_tool(
"lookup",
{"city": "Shanghai"},
{"launcher_type": "person"},
query_id=7,
) == {
"tool_name": "lookup",
"params": {"city": "Shanghai"},
"query_id": 7,
}
command_responses = [
response
async for response in manager.execute_command(
SimpleNamespace(
command="admin",
model_dump=lambda mode="json": {"command": "admin"},
)
)
]
assert command_responses == [CommandReturn(text="admin")]
page_response = await manager.handle_page_api(
"tester",
"toy",
page_id="settings",
endpoint="/save",
method="POST",
body={"enabled": True},
)
assert page_response["data"]["body"] == {"enabled": True}
runners = await manager.list_runners()
assert runners[0]["manifest"]["id"] == "plugin:tester/toy/default"
results = [
item
async for item in manager.run_runner(
"tester",
"toy",
"default",
{
"run_id": "run_toy",
"trigger": {"type": "message.received"},
"event": {
"event_id": "event_toy",
"event_type": "message.received",
"source": "test",
},
"input": {"text": "hello"},
"delivery": {"surface": "platform"},
"resources": {},
"runtime": {},
"config": {},
},
)
]
assert [item["type"] for item in results] == [
"message.completed",
"run.completed",
]
assert [item["sequence"] for item in results] == [1, 2]
assert handler.agent_run_calls[0][1]["runner_name"] == "default"
@pytest.mark.asyncio
async def test_call_tool_and_execute_command_delegate_to_connected_plugin():
manager = _manager()
plugin = _plugin(
components=[
_component("Tool", "lookup"),
_component("Command", "admin"),
]
)
plugin._runtime_plugin_handler = FakeHandler(plugin)
manager.plugins = [plugin]
tool_response = await manager.call_tool(
"lookup",
{"city": "Paris"},
{"launcher_type": "person"},
query_id=99,
query_uuid="query-opaque-99",
)
command_responses = [
response
async for response in manager.execute_command(
SimpleNamespace(
command="admin",
model_dump=lambda mode="json": {"command": "admin"},
)
)
]
assert tool_response == {
"tool_name": "lookup",
"params": {"city": "Paris"},
"query_id": 99,
"query_uuid": "query-opaque-99",
}
assert command_responses == [CommandReturn(text="admin")]
@pytest.mark.asyncio
async def test_call_tool_and_execute_command_return_empty_when_filtered_or_disconnected():
manager = _manager()
plugin = _plugin(
components=[
_component("Tool", "lookup"),
_component("Command", "admin"),
]
)
manager.plugins = [plugin]
assert (
await manager.call_tool(
"lookup",
{},
{},
query_id=1,
include_plugins=["tester/other"],
)
== {}
)
assert await manager.call_tool("lookup", {}, {}, query_id=1) == {}
assert [
response
async for response in manager.execute_command(
SimpleNamespace(
command="admin",
model_dump=lambda mode="json": {"command": "admin"},
)
)
] == []
@pytest.mark.asyncio
async def test_shutdown_plugin_closes_connection_and_removes_container():
manager = _manager()
plugin = _plugin()
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
manager.plugin_handlers = [handler]
await manager.shutdown_plugin(plugin)
assert manager.plugins == []
assert manager.plugin_handlers == []
assert handler.shutdown_calls == 1
assert handler.conn.closed is True
@pytest.mark.asyncio
async def test_shutdown_all_plugins_uses_snapshot_and_closes_every_plugin():
manager = _manager()
plugins = [_plugin(name="one"), _plugin(name="two")]
handlers = [FakeHandler(plugin) for plugin in plugins]
for plugin, handler in zip(plugins, handlers, strict=True):
plugin._runtime_plugin_handler = handler
manager.plugins = list(plugins)
manager.plugin_handlers = list(handlers)
await manager.shutdown_all_plugins()
assert manager.plugins == []
assert manager.plugin_handlers == []
assert [handler.shutdown_calls for handler in handlers] == [1, 1]
@pytest.mark.asyncio
async def test_add_plugin_handler_cleans_up_after_unexpected_run_failure():
manager = _manager()
plugin = _plugin()
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
handler.run = AsyncMock(side_effect=RuntimeError("protocol failure"))
with pytest.raises(RuntimeError, match="protocol failure"):
await manager.add_plugin_handler(handler)
assert manager.plugin_handlers == []
assert manager.plugins == []
@pytest.mark.asyncio
async def test_plugin_supervisor_restarts_after_crash(monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
plugin_path = tmp_path / "data/plugins/tester__demo"
plugin_path.mkdir(parents=True)
manager = _manager()
second_generation_started = asyncio.Event()
calls = 0
async def fake_launch(path):
nonlocal calls
calls += 1
if calls == 1:
raise RuntimeError("crash")
second_generation_started.set()
await asyncio.Event().wait()
monkeypatch.setattr(manager, "launch_plugin", fake_launch)
monkeypatch.setattr(
"langbot_plugin.runtime.plugin.mgr._PLUGIN_RESTART_INITIAL_DELAY_SEC",
0,
)
manager.start_plugin_supervisor(str(plugin_path))
await asyncio.wait_for(second_generation_started.wait(), timeout=1)
assert calls == 2
await manager.stop_plugin_supervisor(str(plugin_path))
assert str(plugin_path) not in manager._desired_plugin_paths
def test_restart_backoff_extends_cap_after_persistent_failures():
from langbot_plugin.runtime.plugin import mgr as manager_module
delay = manager_module._PLUGIN_RESTART_INITIAL_DELAY_SEC
delays = []
for failures in range(1, 16):
delays.append(delay)
delay = manager_module._next_restart_delay(delay, failures)
threshold = manager_module._PLUGIN_PERSISTENT_FAILURE_THRESHOLD
# Transient crashes keep the short 60s cap so recovery stays fast.
assert max(delays[:threshold]) == manager_module._PLUGIN_RESTART_MAX_DELAY_SEC
# A worker that never stabilises backs off up to the long cap.
assert delays[-1] == manager_module._PLUGIN_PERSISTENT_FAILURE_MAX_DELAY_SEC
assert delays == sorted(delays)
@pytest.mark.asyncio
async def test_plugin_supervisor_backs_off_for_persistently_failing_plugin(
monkeypatch, tmp_path
):
from langbot_plugin.runtime.plugin import mgr as manager_module
monkeypatch.chdir(tmp_path)
plugin_path = tmp_path / "data/plugins/tester__broken"
plugin_path.mkdir(parents=True)
manager = _manager()
calls = 0
sleeps: list[float] = []
async def failing_launch(path):
# Mirrors a plugin whose initialize() raises on every start (e.g. it
# writes next to its read-only code): the worker exits immediately.
nonlocal calls
calls += 1
async def record_sleep(delay):
sleeps.append(delay)
if len(sleeps) >= 14:
manager._desired_plugin_paths.discard(str(plugin_path))
monkeypatch.setattr(manager, "launch_plugin", failing_launch)
monkeypatch.setattr(manager_module.random, "uniform", lambda a, b: 1.0)
monkeypatch.setattr(manager_module.asyncio, "sleep", record_sleep)
manager._desired_plugin_paths.add(str(plugin_path))
await manager._supervise_plugin(str(plugin_path))
assert calls == 14
assert sleeps[:7] == [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 60.0]
assert sleeps[9] == 60.0
assert sleeps[10:] == [120.0, 240.0, 480.0, 900.0]
@pytest.mark.asyncio
async def test_register_plugin_rolls_back_container_when_initialize_fails():
manager = _manager()
manager.context = _bound_runtime_context(FakeControlHandler())
plugin = _plugin(status=RuntimeContainerStatus.MOUNTED)
handler = FakeHandler(plugin)
handler.initialize_plugin = AsyncMock(side_effect=RuntimeError("init failed"))
registration_capability = _registration_capability(manager, plugin)
with pytest.raises(RuntimeError, match="init failed"):
await manager.register_plugin(
handler,
plugin.model_dump(),
registration_capability=registration_capability,
)
assert manager.plugins == []
assert manager.plugin_handlers == []
@pytest.mark.asyncio
async def test_restart_plugin_debug_skips_relaunch_and_missing_plugin_errors():
manager = _manager()
plugin = _plugin(debug=True)
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
manager.plugin_handlers = [handler]
actions = [
item["current_action"]
async for item in manager.restart_plugin("tester", "demo")
]
assert actions == [
"shutting down plugin",
"removing plugin container",
"plugin restarted",
]
assert manager.plugin_run_tasks == []
assert manager.plugins == []
with pytest.raises(ValueError, match="Plugin tester/missing not found"):
async for _ in manager.restart_plugin("tester", "missing"):
pass
@pytest.mark.asyncio
async def test_delete_plugin_removes_files_and_rejects_debug_plugins(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
plugin_path = tmp_path / "data/plugins/tester__demo"
plugin_path.mkdir(parents=True)
(plugin_path / "manifest.yaml").write_text("kind: Plugin\n", encoding="utf-8")
plugin = _plugin()
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
manager.plugin_handlers = [handler]
actions = [
item["current_action"] async for item in manager.delete_plugin("tester", "demo")
]
assert actions == [
"shutting down plugin",
"removing plugin container",
"deleting plugin files",
"plugin deleted",
]
assert not plugin_path.exists()
debug = _plugin(debug=True)
manager.plugins = [debug]
with pytest.raises(ValueError, match="is a debugging plugin"):
async for _ in manager.delete_plugin("tester", "demo"):
pass
@pytest.mark.asyncio
async def test_delete_plugin_removes_installed_files_when_plugin_is_not_running(
tmp_path, monkeypatch
):
monkeypatch.chdir(tmp_path)
manager = _manager()
plugin_path = tmp_path / "data/plugins/tester__demo"
plugin_path.mkdir(parents=True)
(plugin_path / "manifest.yaml").write_text(
"kind: Plugin\nmetadata:\n author: tester\n name: demo\n",
encoding="utf-8",
)
actions = [
item["current_action"] async for item in manager.delete_plugin("tester", "demo")
]
assert actions == [
"stopping plugin supervisor",
"deleting plugin files",
"plugin deleted",
]
assert not plugin_path.exists()
@pytest.mark.asyncio
async def test_upgrade_plugin_validates_source_and_reports_up_to_date(monkeypatch):
manager = _manager()
debug = _plugin(debug=True)
manager.plugins = [debug]
with pytest.raises(ValueError, match="is a debugging plugin"):
async for _ in manager.upgrade_plugin("tester", "demo"):
pass
local = _plugin()
manager.plugins = [local]
with pytest.raises(ValueError, match="not installed from marketplace"):
async for _ in manager.upgrade_plugin("tester", "demo"):
pass
marketplace = _plugin()
marketplace.install_source = PluginInstallSource.MARKETPLACE.value
manager.plugins = [marketplace]
async def fake_get_plugin_info(author, name):
return SimpleNamespace(latest_version="1.0.0")
monkeypatch.setattr(marketplace_helper, "get_plugin_info", fake_get_plugin_info)
actions = [
item["current_action"]
async for item in manager.upgrade_plugin("tester", "demo")
]
assert actions == ["checking for latest version", "plugin is up to date"]
@pytest.mark.asyncio
async def test_plugin_resource_and_page_methods_delegate_to_connected_handler():
manager = _manager()
plugin = _plugin()
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
assert await manager.get_plugin_icon("tester", "missing") == (b"", "")
assert await manager.get_plugin_icon("tester", "demo") == (
b"<svg/>",
"image/svg+xml",
)
assert "icon-key" not in handler.files
assert await manager.get_plugin_readme("tester", "demo", language="zh") == b"# Demo"
assert "readme-key" not in handler.files
assert await manager.get_plugin_assets_file("tester", "demo", "missing") == (
b"",
"",
)
assert await manager.get_plugin_assets_file("tester", "demo", "asset.txt") == (
b"asset-bytes",
"text/plain",
)
assert "asset-key" not in handler.files
page_response = await manager.handle_page_api(
"tester",
"demo",
page_id="settings",
endpoint="/save",
method="POST",
body={"enabled": True},
)
assert page_response["data"]["page_id"] == "settings"
assert page_response["data"]["body"] == {"enabled": True}
assert await manager.handle_page_api(
"tester",
"missing",
page_id="settings",
endpoint="/save",
method="POST",
) == {"data": None, "error": "Plugin not found"}
@pytest.mark.asyncio
async def test_shared_plugin_resource_transfers_use_exact_installation_binding():
manager = _manager()
plugin = _plugin()
digest = "a" * 64
binding = InstallationBinding(
instance_uuid="instance-1",
workspace_uuid="workspace-a",
placement_generation=1,
installation_uuid="installation-a",
runtime_revision=1,
artifact_digest=digest,
)
sibling = binding.model_copy(
update={
"workspace_uuid": "workspace-b",
"installation_uuid": "installation-b",
}
)
class SharedHandler(FakeHandler):
def __init__(self, container):
super().__init__(container)
self.files = {
(binding, "icon-key"): b"<svg/>",
(binding, "readme-key"): b"# Demo",
(binding, "asset-key"): b"asset-bytes",
(sibling, "icon-key"): b"sibling icon",
}
self.file_calls = []
async def read_local_file(self, file_key, *, action_context):
self.file_calls.append(("read", action_context, file_key))
return self.files[(action_context, file_key)]
async def delete_local_file(self, file_key, *, action_context):
self.file_calls.append(("delete", action_context, file_key))
self.files.pop((action_context, file_key), None)
handler = SharedHandler(plugin)
plugin._runtime_plugin_handler = handler
manager.plugins = [plugin]
manager._binding_by_container_id[id(plugin)] = binding
assert await manager.get_plugin_icon("tester", "demo") == (
b"<svg/>",
"image/svg+xml",
)
assert await manager.get_plugin_readme("tester", "demo") == b"# Demo"
assert await manager.get_plugin_assets_file("tester", "demo", "asset.txt") == (
b"asset-bytes",
"text/plain",
)
assert {call[1] for call in handler.file_calls} == {binding}
assert handler.files[(sibling, "icon-key")] == b"sibling icon"
assert not any(key[0] == binding for key in handler.files)
@pytest.mark.asyncio
async def test_plugin_logs_and_resource_methods_handle_missing_connections():
manager = _manager()
assert await manager.get_plugin_logs("tester", "missing") == []
assert await manager.get_plugin_readme("tester", "missing") == b""
assert await manager.get_plugin_assets_file("tester", "missing", "asset.txt") == (
b"",
"",
)
plugin = _plugin()
manager.plugins = [plugin]
assert await manager.get_plugin_logs("tester", "demo") == []
assert await manager.handle_page_api(
"tester",
"demo",
page_id="settings",
endpoint="/save",
method="POST",
) == {"data": None, "error": "Plugin is not connected"}
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
assert await manager.get_plugin_logs("tester", "demo", limit=3, level="INFO") == [
{"limit": 3, "level": "INFO", "text": "ready"}
]
@pytest.mark.asyncio
async def test_knowledge_engine_methods_validate_components_and_delegate_to_handler():
manager = _manager()
rag = _component(
"KnowledgeEngine",
"kb",
{
"creation_schema": [{"name": "api_key"}],
"retrieval_schema": [{"name": "top_k"}],
},
)
plugin = _plugin(components=[rag])
plugin._runtime_plugin_handler = FakeHandler(plugin)
manager.plugins = [plugin]
engines = await manager.list_knowledge_engines()
assert engines[0]["plugin_id"] == "tester/demo"
assert engines[0]["capabilities"] == ["ingest", "retrieve"]
assert engines[0]["creation_schema"] == {"schema": [{"name": "api_key"}]}
assert await manager.get_rag_creation_schema("tester", "demo") == {
"schema": [{"name": "api_key"}]
}
assert await manager.get_rag_retrieval_schema("tester", "demo") == {
"schema": [{"name": "top_k"}]
}
assert await manager.rag_ingest_document(
"tester",
"demo",
{"document_id": "doc-1"},
) == {"ingested": "doc-1"}
assert await manager.rag_delete_document("tester", "demo", "kb-1", "doc-1") == {
"deleted": ["kb-1", "doc-1"]
}
assert await manager.rag_on_kb_create(
"tester",
"demo",
"kb-1",
{"api_key": "secret"},
) == {"created": "kb-1", "config": {"api_key": "secret"}}
assert await manager.rag_on_kb_delete("tester", "demo", "kb-1") == {
"deleted_kb": "kb-1"
}
with pytest.raises(ValueError, match="has no KnowledgeEngine component"):
manager.plugins = [_plugin(components=[])]
await manager.rag_ingest_document("tester", "demo", {})
@pytest.mark.asyncio
async def test_knowledge_engine_errors_and_retrieve_knowledge_delegate():
manager = _manager()
with pytest.raises(ValueError, match="Plugin tester/missing not found"):
await manager.retrieve_knowledge("tester", "missing", "kb", {"query": "hi"})
plugin = _plugin(components=[_component("KnowledgeEngine", "kb")])
manager.plugins = [plugin]
with pytest.raises(ValueError, match="is not connected"):
await manager.retrieve_knowledge("tester", "demo", "kb", {"query": "hi"})
handler = FakeHandler(plugin)
plugin._runtime_plugin_handler = handler
assert await manager.retrieve_knowledge(
"tester", "demo", "kb", {"query": "hi"}
) == {
"retriever_name": "kb",
"retrieval_context": {"query": "hi"},
}
assert await manager.get_rag_creation_schema("tester", "missing") == {"schema": []}
assert await manager.get_rag_retrieval_schema("tester", "missing") == {"schema": []}
manager.plugins = [_plugin(components=[])]
with pytest.raises(ValueError, match="has no KnowledgeEngine component"):
await manager.rag_delete_document("tester", "demo", "kb-1", "doc-1")
plugin_without_handler = _plugin(components=[_component("KnowledgeEngine", "kb")])
manager.plugins = [plugin_without_handler]
with pytest.raises(ValueError, match="is not connected"):
await manager.rag_on_kb_create("tester", "demo", "kb-1", {})
@pytest.mark.asyncio
async def test_parser_methods_validate_components_and_delegate_to_handler():
manager = _manager()
parser = _component(
"Parser",
"pdf",
{"supported_mime_types": ["application/pdf"]},
)
plugin = _plugin(components=[parser])
plugin._runtime_plugin_handler = FakeHandler(plugin)
manager.plugins = [plugin]
parsers = await manager.list_parsers()
assert parsers[0]["plugin_id"] == "tester/demo"
assert parsers[0]["supported_mime_types"] == ["application/pdf"]
assert await manager.parse_document(
"tester",
"demo",
{"filename": "a.txt"},
b"hello",
) == {"context": {"filename": "a.txt"}, "text": "hello"}
plugin._runtime_plugin_handler = None
with pytest.raises(ValueError, match="is not connected"):
await manager.parse_document("tester", "demo", {}, b"")
@pytest.mark.asyncio
async def test_parser_errors_for_missing_plugin_and_component():
manager = _manager()
with pytest.raises(ValueError, match="Plugin tester/missing not found"):
await manager.parse_document("tester", "missing", {}, b"")
manager.plugins = [_plugin(components=[])]
with pytest.raises(ValueError, match="has no Parser component"):
await manager.parse_document("tester", "demo", {}, b"")
@pytest.mark.asyncio
async def test_emit_event_should_report_each_emitting_plugin_once():
manager = _manager()
plugin = _plugin(components=[_component("EventListener", "events")])
plugin._runtime_plugin_handler = FakeHandler(plugin)
manager.plugins = [plugin]
event_context = EventContext(
query_id=1,
event_name="PersonCommandSent",
event=PersonCommandSent(
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
command="demo",
params=[],
text_message="/demo",
is_admin=False,
),
)
emitted_plugins, _, _ = await manager.emit_event(event_context)
assert emitted_plugins == [plugin]
@pytest.mark.asyncio
async def test_emit_event_rejects_plugin_query_uuid_forgery():
manager = _manager()
plugin = _plugin(components=[_component("EventListener", "events")])
plugin._runtime_plugin_handler = QueryUuidChangingFakeHandler(plugin)
manager.plugins = [plugin]
event_context = EventContext(
query_id=1,
query_uuid="query-trusted",
event_name="PersonCommandSent",
event=PersonCommandSent(
query_uuid="query-trusted",
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
command="demo",
params=[],
text_message="/demo",
is_admin=False,
),
)
with pytest.raises(ValueError, match="changed EventContext query_uuid"):
await manager.emit_event(event_context)
@pytest.mark.asyncio
async def test_emit_event_restores_query_uuid_dropped_by_legacy_plugin():
manager = _manager()
plugin = _plugin(components=[_component("EventListener", "events")])
plugin._runtime_plugin_handler = QueryUuidDroppingFakeHandler(plugin)
manager.plugins = [plugin]
event_context = EventContext(
query_id=1,
query_uuid="query-trusted",
event_name="PersonCommandSent",
event=PersonCommandSent(
query_uuid="query-trusted",
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
command="demo",
params=[],
text_message="/demo",
is_admin=False,
),
)
_, returned_context, _ = await manager.emit_event(event_context)
assert returned_context.query_uuid == "query-trusted"
assert returned_context.event.query_uuid == "query-trusted"
@pytest.mark.asyncio
async def test_emit_event_reports_only_plugins_that_changed_reply_message_chain():
manager = _manager()
observer = _plugin(
name="observer", components=[_component("EventListener", "events")]
)
responder = _plugin(
name="responder", components=[_component("EventListener", "events")]
)
observer._runtime_plugin_handler = FakeHandler(observer)
responder._runtime_plugin_handler = ReplyChangingFakeHandler(responder)
manager.plugins = [observer, responder]
event_context = EventContext(
query_id=1,
event_name="PersonNormalMessageReceived",
event=PersonNormalMessageReceived(
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
text_message="hello",
message_event={
"time": 0.0,
"self_id": "bot",
"sender": {"id": "sender", "nickname": "Sender", "remark": ""},
"message_chain": [{"type": "Plain", "text": "hello"}],
},
message_chain=platform_message.MessageChain(
[platform_message.Plain(text="hello")]
),
),
)
emitted_plugins, event_context, response_sources = await manager.emit_event(
event_context
)
assert emitted_plugins == [observer, responder]
assert response_sources == [
{
"kind": "reply_message_chain",
"plugin": {"author": "tester", "name": "responder"},
}
]
assert str(event_context.event.reply_message_chain) == "plugin reply"
@pytest.mark.asyncio
async def test_install_plugin_marketplace_streams_progress_and_launches(monkeypatch):
manager = _manager()
control_handler = FakeControlHandler()
manager.context = SimpleNamespace(control_handler=control_handler)
async def fake_download_plugin_streaming(author, name, version):
yield {
"done": False,
"downloaded": 5,
"total": 10,
"speed": 2,
}
yield {"done": True, "data": b"zip"}
async def fake_install_plugin_from_file(plugin_file):
assert plugin_file == b"zip"
return "data/.plugin-staging/tester__demo-stage", "tester", "demo", "1.0.0"
launched = []
def fake_start_plugin_supervisor(plugin_path):
launched.append(plugin_path)
async def fake_wait_for_plugin_ready(author, name, timeout):
return None
monkeypatch.setattr(
marketplace_helper,
"download_plugin_streaming",
fake_download_plugin_streaming,
)
monkeypatch.setattr(
manager, "install_plugin_from_file", fake_install_plugin_from_file
)
monkeypatch.setattr(
manager, "start_plugin_supervisor", fake_start_plugin_supervisor
)
monkeypatch.setattr(manager, "_wait_for_plugin_ready", fake_wait_for_plugin_ready)
monkeypatch.setattr(
manager,
"_activate_staged_plugin",
lambda path, author, name: asyncio.sleep(0, result=None),
)
progress = [
item
async for item in manager.install_plugin(
PluginInstallSource.MARKETPLACE,
{
"plugin_author": "tester",
"plugin_name": "demo",
"plugin_version": "1.0.0",
},
)
]
assert [item["current_action"] for item in progress] == [
"downloading plugin package",
"downloading plugin package",
"installing dependencies",
"initializing plugin settings",
"launching plugin",
]
assert progress[1]["metadata"] == {
"download_current": 5,
"download_total": 10,
"download_speed": 2,
}
assert control_handler.calls[-1][1]["install_info"] == {
"plugin_author": "tester",
"plugin_name": "demo",
"plugin_version": "1.0.0",
}
assert launched == ["data/plugins/tester__demo"]
@pytest.mark.asyncio
async def test_reinstall_cancellation_does_not_cancel_runtime_launch(monkeypatch):
context = SimpleNamespace(wait_for_workspace_binding=AsyncMock())
manager = PluginManager(context)
monkeypatch.setattr(manager_module.glob, "glob", lambda pattern: [])
ready = asyncio.Event()
async def worker():
ready.set()
await asyncio.Future()
child = asyncio.create_task(worker())
manager.plugin_run_tasks = [child]
launch = asyncio.create_task(manager.launch_all_plugins())
await ready.wait()
child.cancel()
await launch
assert child.cancelled()
assert not launch.cancelled()
def _command_event():
return EventContext(
query_id=1,
event_name="PersonCommandSent",
event=PersonCommandSent(
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
command="demo",
params=[],
text_message="/demo",
is_admin=False,
),
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"kind", [None, "Runner", "Tool", "Command", "Parser", "Page", "KnowledgeEngine"]
)
async def test_emit_event_skips_plugins_without_listener(kind):
manager = _manager()
plugin = _plugin(
components=[
_component(
kind, "component", {"usages": ["agent"]} if kind == "Runner" else {}
)
]
if kind
else []
)
handler = FakeHandler(plugin)
handler.emit_event = AsyncMock(side_effect=RuntimeError("must not contact worker"))
plugin._runtime_plugin_handler = handler
listener = _plugin(
name="listener", components=[_component("EventListener", "events")]
)
listener._runtime_plugin_handler = FakeHandler(listener)
manager.plugins = [plugin, listener]
emitted, _, _ = await manager.emit_event(_command_event())
assert emitted == [listener]
handler.emit_event.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize("prevent", [False, True])
async def test_listener_dispatch_preserves_order_mutation_and_prevention(prevent):
manager = _manager()
calls = []
for name in ["first", "second", "third"]:
plugin = _plugin(name=name, components=[_component("EventListener", "events")])
handler = FakeHandler(plugin)
async def emit(context, name=name):
calls.append((name, context["event"]["text_message"]))
await asyncio.sleep(0)
context["event"]["text_message"] += ":" + name
context["is_prevent_postorder"] = prevent and name == "second"
return {"emitted": True, "event_context": context}
handler.emit_event = emit
plugin._runtime_plugin_handler = handler
manager.plugins.append(plugin)
emitted, context, _ = await manager.emit_event(_command_event())
expected = ["first", "second"] if prevent else ["first", "second", "third"]
assert [p.manifest.metadata.name for p in emitted] == expected
assert [c[0] for c in calls] == expected
assert calls[1][1] == "/demo:first"
assert context.event.text_message == "/demo:" + ":".join(expected)
@pytest.mark.asyncio
async def test_registered_event_dispatch_uses_host_order():
manager = _manager()
for name, registered in [
("first", ["PersonCommandSent"]),
("idle", []),
("last", ["PersonCommandSent"]),
]:
plugin = _plugin(
name=name,
components=[
_component("EventListener", "events"),
_component("Command", name),
],
)
plugin.registered_events = registered
plugin._runtime_plugin_handler = FakeHandler(plugin)
manager.plugins.append(plugin)
manager.plugins[1]._runtime_plugin_handler.emit_event = AsyncMock(
side_effect=AssertionError("unregistered event")
)
order = ["tester/last", "tester/idle", "tester/first"]
emitted, _, _ = await manager.emit_event(_command_event(), order)
assert [plugin.manifest.metadata.name for plugin in emitted] == ["last", "first"]
assert manager.plugin_registrations(order)["tester/idle"] == {
"events": [],
"commands": ["idle"],
}
@pytest.mark.asyncio
@pytest.mark.parametrize("error", [RuntimeError, TimeoutError, ConnectionError])
async def test_subscriber_failures_preserve_existing_propagation(error):
manager = _manager()
first = _plugin(components=[_component("EventListener", "events")])
first._runtime_plugin_handler = FakeHandler(first)
first._runtime_plugin_handler.emit_event = AsyncMock(
side_effect=error("listener fault")
)
second = _plugin(name="second", components=[_component("EventListener", "events")])
second._runtime_plugin_handler = FakeHandler(second)
second._runtime_plugin_handler.emit_event = AsyncMock()
manager.plugins = [first, second]
with pytest.raises(error):
await manager.emit_event(_command_event())
second._runtime_plugin_handler.emit_event.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"excluded", ["disabled", "uninitialized", "disconnected", "binding"]
)
async def test_listener_dispatch_retains_admission_filters(excluded):
manager = _manager()
plugin = _plugin(
components=[
_component("Runner", "run", {"usages": ["agent"]}),
_component("EventListener", "events"),
]
)
handler = FakeHandler(plugin)
handler.emit_event = AsyncMock(
side_effect=AssertionError("filtered listener contacted")
)
plugin._runtime_plugin_handler = handler
if excluded == "disabled":
plugin.enabled = False
elif excluded == "uninitialized":
plugin.status = RuntimeContainerStatus.MOUNTED
elif excluded == "disconnected":
plugin._runtime_plugin_handler = None
manager.plugins = [plugin]
emitted, _, _ = await manager.emit_event(
_command_event(), include_plugins=[] if excluded == "binding" else None
)
assert emitted == []
handler.emit_event.assert_not_awaited()
@pytest.mark.asyncio
async def test_emit_event_reports_only_the_plugin_that_prevented_default():
manager = _manager()
observer = _plugin(
name="observer", components=[_component("EventListener", "events")]
)
taker = _plugin(name="taker", components=[_component("EventListener", "events")])
later = _plugin(name="later", components=[_component("EventListener", "events")])
observer._runtime_plugin_handler = FakeHandler(observer)
taker._runtime_plugin_handler = DefaultPreventingFakeHandler(taker)
# A later plugin that sets the flag again must not take the attribution.
later._runtime_plugin_handler = DefaultPreventingFakeHandler(later)
manager.plugins = [observer, taker, later]
event_context = EventContext(
query_id=1,
event_name="PersonNormalMessageReceived",
event=PersonNormalMessageReceived(
launcher_type="person",
launcher_id="launcher",
sender_id="sender",
text_message="hello",
message_event={
"time": 0.0,
"self_id": "bot",
"sender": {"id": "sender", "nickname": "Sender", "remark": ""},
"message_chain": [{"type": "Plain", "text": "hello"}],
},
message_chain=platform_message.MessageChain(
[platform_message.Plain(text="hello")]
),
),
)
_, returned_context, response_sources = await manager.emit_event(event_context)
assert returned_context.is_prevented_default()
assert response_sources == [
{
"kind": "prevent_default",
"plugin": {"author": "tester", "name": "taker"},
}
]