mirror of
https://gitcode.com/JianFeeeee/ModelRouter.git
synced 2026-10-03 23:54:06 +00:00
## 现象
部署示例后打开 WebUI:侧栏有 Billing 页,但**状态页上没有任何计费组件**。
插件明明声明了 elements,/api/ui-inject 也确实返回了 mount(1570 字节)。
## 根因(不是缺功能)
七个宿主页面的渲染函数都用 `pane.innerHTML = ...` **整体替换**自己的 DOM。
`renderStatus` 在 `injectPluginUI()` 之后由 refresh() 立刻调用,于是刚挂上的
plugin-el 连同整个 pane 一起被下一次赋值销毁。
时序上它**从没有过"显示一帧"的机会**:注入 → refresh("status") → innerHTML 覆盖。
所以症状是"元素从来没出现过",而不是"刷新后消失"——这正是我先前据
/api/ui-inject 返回值判定"注入正常"而漏掉的地方:**载荷到达 ≠ DOM 存活**。
Billing 页不受影响,因为它属于 PLUGIN_PAGES,走插件自有 DOM,不经宿主重建。
于是看起来像"页面注入有效、元素注入无效",把排查引向插件声明本身。
## 修法
- mountPluginElements 改成具名可重入函数,并注册进 PLUGIN_MOUNT_HOOKS
- refresh() 在**唯一出口**统一调 remountPluginElements(),而不是给七个渲染函数
各加一次调用——后者是多一处会忘的地方,而忘记的后果是静默的
- 每个挂载点按 data-idx 幂等:宿主重绘时若该 pane 已有该元素就直接返回,
否则插件的 <script> 会每次重绘都跑一遍,计数器静默翻倍
## ★ 验证方式换了:真实浏览器,而不是 payload
静态测试和 curl 都看不出这个 bug(载荷完全正确)。用 CDP 连本机共享浏览器实测:
修复后:首屏 tile=1,页面重建后=1,连续重建 5 次仍=1,console 无错误
回退后:tile 全程=0
对照二进制(把 done 改成空函数重编译)实测首屏就是 0,
**证明"从未显示过",不是"显示后消失"**。
## 判据与变异
TestPluginElementsSurviveHostRebuild 锁住:remountPluginElements 存在、
PLUGIN_MOUNT_HOOKS 在使用之前声明(const TDZ 会让首屏直接抛错)、refresh 挂了重挂、
挂载按 data-idx 幂等。
三个变异全部被抓住:撤掉 refresh 的重挂 / 去掉幂等守卫 / 把 const 声明移到 push 之后。
★ 第一次跑第三个变异时**判据正确地没报**,因为我的替换脚本命中了注释里的同名文本,
真正的 const 没被移动——是变异无效,不是判据有洞。换按行定位后如期变红。
## 同时补上部署示例
packaging/config.example.yaml 里补 plugin_dir 说明(之前只有 online 部署路径踩过)。
实测升级路径本身是好的:给已有配置加 plugin_dir 后,首次启动会自动 seed 内置
billing 插件,无需手工放置文件。
318 lines
13 KiB
Go
318 lines
13 KiB
Go
package gateway
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// The plugin UI injection is JavaScript inside the embedded index.html, and it
|
|
// is the ONLY thing that turns a plugin's `ui` block into a visible page or
|
|
// element. These tests pin the wiring on the JS side; the server side (what the
|
|
// payload contains) is covered by TestUIInjectServesPluginUI and the lua
|
|
// package's TestBillingPluginDeclaresUI.
|
|
//
|
|
// What makes this worth pinning: a missing hook here fails SILENTLY. The page
|
|
// simply never appears, there is no error anywhere, and it looks like "the
|
|
// plugin didn't declare a page" rather than "the UI forgot to inject it".
|
|
|
|
// uiSource returns the embedded WebUI document.
|
|
func uiSourceX(t *testing.T) string {
|
|
t.Helper()
|
|
return uiSource(t)
|
|
}
|
|
|
|
// TestUIFetchesPluginInjection: the boot sequence must ask the kernel what to
|
|
// inject. Without this fetch the whole feature is inert.
|
|
func TestUIFetchesPluginInjection(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
if !strings.Contains(src, "/api/ui-inject") {
|
|
t.Error("the WebUI never calls /api/ui-inject; plugin pages and elements can never appear")
|
|
}
|
|
}
|
|
|
|
// TestUIInjectsBeforeFirstRender: injection must be awaited before the first
|
|
// refresh, otherwise the sidebar is built without the plugin entry and the
|
|
// first paint races the fetch. This is an ordering contract, so it is asserted
|
|
// on the source order rather than trusted.
|
|
func TestUIInjectsBeforeFirstRender(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
iInject := strings.Index(src, "injectPluginUI()")
|
|
iRefresh := strings.LastIndex(src, `refresh("status")`)
|
|
if iInject < 0 {
|
|
t.Fatal("injectPluginUI() is never called")
|
|
}
|
|
if iRefresh < 0 {
|
|
t.Fatal("the boot sequence no longer calls refresh(\"status\")")
|
|
}
|
|
if iInject > iRefresh {
|
|
t.Error("injectPluginUI() is called after the first refresh; the sidebar " +
|
|
"and #main would be built before the plugin page exists")
|
|
}
|
|
// And it must be awaited, not fire-and-forget.
|
|
window := src[iInject:]
|
|
if !strings.Contains(window[:200], ".finally") && !strings.Contains(window[:200], "await") {
|
|
t.Error("injectPluginUI() is not awaited before refresh; a slow response " +
|
|
"would race the first paint")
|
|
}
|
|
}
|
|
|
|
// TestUIPluginScriptsRunAfterMarkup is the subtle one. Setting innerHTML with a
|
|
// <script> tag does NOT execute it; appending via a template neither does. The
|
|
// mount therefore has to be inserted first and its scripts re-created
|
|
// afterwards, or a plugin's script runs before its own DOM exists — which is
|
|
// exactly the "document.getElementById returns null" failure mode.
|
|
func TestUIPluginScriptsRunAfterMarkup(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
// A <template> is used to parse the mount without executing scripts...
|
|
if !strings.Contains(src, "createElement(\"template\")") {
|
|
t.Error("the mount is not parsed via <template>; scripts could execute before their DOM")
|
|
}
|
|
// ...and scripts are then re-created as fresh elements so they DO run.
|
|
if !strings.Contains(src, "document.createElement(\"script\")") {
|
|
t.Error("plugin <script> blocks are never re-created, so they never execute")
|
|
}
|
|
if !strings.Contains(src, "replaceWith(s)") {
|
|
t.Error("the original inert <script> is not replaced by an executable one")
|
|
}
|
|
}
|
|
|
|
// TestUIPluginAPISurface: the documented browser API must exist with the exact
|
|
// names docs/plugins.md promises, since plugin authors code against it.
|
|
func TestUIPluginAPISurface(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
for _, member := range []string{"fetchState", "postState", "onTabShown"} {
|
|
if !strings.Contains(src, member+":") && !strings.Contains(src, member+"(") {
|
|
t.Errorf("window.pluginAPI.%s is missing; docs/plugins.md documents it", member)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestUIPluginPageBecomesRealTab: a plugin page must get a pane in #main AND a
|
|
// sidebar button wired to goTab, otherwise the page is unreachable.
|
|
func TestUIPluginPageBecomesRealTab(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
// pane in #main
|
|
if !strings.Contains(src, `pane.id = "tab-" + id`) {
|
|
t.Error("no pane is created for a plugin page")
|
|
}
|
|
if !strings.Contains(src, "main.appendChild(pane)") {
|
|
t.Error("the plugin pane is not appended to #main")
|
|
}
|
|
// sidebar button wired to the tab router
|
|
if !strings.Contains(src, "btn.dataset.tab = id") {
|
|
t.Error("the sidebar button is not given a data-tab, so goTab() will not route to it")
|
|
}
|
|
if !strings.Contains(src, "btn.onclick = () => goTab(id)") {
|
|
t.Error("the sidebar button is not wired to goTab()")
|
|
}
|
|
// and the router must know about it
|
|
if !strings.Contains(src, "PLUGIN_PAGES.has(tab)") {
|
|
t.Error("refresh() does not route plugin pages, so opening one renders nothing")
|
|
}
|
|
}
|
|
|
|
// TestUIPluginElementsHonorAnchor: elements declare top / bottom / before:sel /
|
|
// after:sel. Silently ignoring the anchor would put a "top" tile at the bottom
|
|
// of the status page, which looks like a layout bug rather than a plugin bug.
|
|
func TestUIPluginElementsHonorAnchor(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
for _, anchor := range []string{`anchor === "top"`, `anchor.startsWith("before:")`, `"after:"`} {
|
|
if !strings.Contains(src, anchor) {
|
|
t.Errorf("the anchor form %s is not handled; elements would all land at the bottom", anchor)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestUIPluginInjectionFailureIsNonFatal: plugins are optional, so a failed
|
|
// /api/ui-inject must still leave a working UI (the dashboard has to render).
|
|
// Two places have to cooperate: the function swallows the fetch error, and the
|
|
// caller catches anything that still escapes so refresh() always runs.
|
|
func TestUIPluginInjectionFailureIsNonFatal(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
// inside the function: the fetch is wrapped in try/catch
|
|
fnStart := strings.Index(src, "async function injectPluginUI()")
|
|
if fnStart < 0 {
|
|
t.Fatal("injectPluginUI() is not defined")
|
|
}
|
|
fn := src[fnStart:]
|
|
if !strings.Contains(fn, "plugins are optional; the UI must work without them") {
|
|
t.Error("injectPluginUI does not guard its own fetch failure")
|
|
}
|
|
// at the call site: the rejection cannot escape before the first render
|
|
// LastIndex, not Index: the DEFINITION of injectPluginUI also matches, and
|
|
// the definition has no .catch on it.
|
|
iCall := strings.LastIndex(src, "injectPluginUI()")
|
|
if iCall < 0 {
|
|
t.Fatal("injectPluginUI() is never called")
|
|
}
|
|
// Bound the window at len(src): the call site sits near EOF and a fixed
|
|
// slice overruns it (a panic in a test is worse than a skipped assertion).
|
|
end := iCall + 220
|
|
if end > len(src) {
|
|
end = len(src)
|
|
}
|
|
if !strings.Contains(src[iCall:end], ".catch") {
|
|
t.Error("a failed /api/ui-inject would reject before refresh(\"status\"), " +
|
|
"leaving the dashboard blank")
|
|
}
|
|
}
|
|
|
|
// ---- plugin management UI contract ---------------------------------------
|
|
//
|
|
// The management page is the operator's only way to take a broken plugin out
|
|
// of the request path. Every one of these assertions guards a link that, if it
|
|
// silently broke, would leave the gateway running with a plugin it cannot
|
|
// disable — the worst kind of gap: everything looks fine and nothing is
|
|
// reachable.
|
|
|
|
func TestUIHasPluginTabAndPane(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
if !strings.Contains(src, `data-tab="plugins"`) {
|
|
t.Error("no sidebar entry for the plugin page")
|
|
}
|
|
if !strings.Contains(src, `id="tab-plugins"`) {
|
|
t.Error("no #tab-plugins pane")
|
|
}
|
|
// The tab list is now a single constant; a new tab must be added there or
|
|
// goTab will not un-hide its pane.
|
|
if !strings.Contains(src, `const TABS = [`) {
|
|
t.Error("TABS is gone; the tab list went back to a duplicated literal")
|
|
}
|
|
for _, tn := range []string{"status", "chat", "keys", "sort", "sources", "adapters", "plugins"} {
|
|
if !strings.Contains(src, `"`+tn+`"`) {
|
|
t.Errorf("TABS is missing %q", tn)
|
|
}
|
|
}
|
|
// goTab must iterate TABS, not its own list.
|
|
if !strings.Contains(src, "TABS.forEach((tn) =>") {
|
|
t.Error("goTab does not iterate TABS")
|
|
}
|
|
if strings.Contains(src, `["status", "chat", "keys", "sort", "sources", "adapters"].forEach`) {
|
|
t.Error("a duplicated tab literal survived; it will drift from TABS")
|
|
}
|
|
}
|
|
|
|
func TestUIRendersPluginManagement(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
body, ok := jsFunctionBody(src, "renderPlugins")
|
|
if !ok {
|
|
t.Fatal("renderPlugins() not found")
|
|
}
|
|
// It must read the DISK listing, not just the loaded set: a plugin that
|
|
// failed to compile is absent from the loaded set, and showing only the
|
|
// loaded set makes a syntax error look like "the plugin is not installed".
|
|
if !strings.Contains(body, "on_disk") {
|
|
t.Error("renderPlugins reads only the loaded set; a failed plugin would " +
|
|
"be invisible instead of shown with its error")
|
|
}
|
|
if !strings.Contains(body, "/api/plugins") {
|
|
t.Error("renderPlugins does not call /api/plugins")
|
|
}
|
|
// Hook errors must be surfaced: a plugin that throws in every stage leaves
|
|
// no other trace, so without this the symptom is "the feature just doesn't
|
|
// work".
|
|
if !strings.Contains(body, "hook_errors") {
|
|
t.Error("renderPlugins ignores hook_errors; a silently broken plugin is undebuggable")
|
|
}
|
|
// Enable / disable / remove / edit.
|
|
for _, fn := range []string{"togglePlugin", "delPlugin", "installPlugin", "editPlugin"} {
|
|
if _, ok := jsFunctionBody(src, fn); !ok {
|
|
t.Errorf("%s() is missing from the WebUI", fn)
|
|
}
|
|
}
|
|
// The toggle must go through the enable/disable endpoint, not delete.
|
|
tb, ok := jsFunctionBody(src, "togglePlugin")
|
|
if !ok {
|
|
t.Fatal("togglePlugin() missing")
|
|
}
|
|
if !strings.Contains(tb, `method: "PUT"`) {
|
|
t.Error("togglePlugin does not use PUT")
|
|
}
|
|
if !strings.Contains(tb, "enabled:") {
|
|
t.Error("togglePlugin does not send an \"enabled\" field")
|
|
}
|
|
// And the admin-only tab list must include plugins, or a non-admin would
|
|
// see a page whose every action 403s.
|
|
if !strings.Contains(src, `["sort", "sources", "adapters", "plugins"]`) {
|
|
t.Error("the admin-only tab list omits \"plugins\"; a user key would see a " +
|
|
"page full of actions that all fail with 403")
|
|
}
|
|
}
|
|
|
|
// TestUIBindDropzoneIsParameterised guards the refactor: the adapter and plugin
|
|
// upload forms share one dropzone, so a hard-coded id would send a dropped
|
|
// plugin file into the adapter name field.
|
|
func TestUIBindDropzoneIsParameterised(t *testing.T) {
|
|
src := uiSourceX(t)
|
|
body, ok := jsFunctionBody(src, "bindDropzone")
|
|
if !ok {
|
|
t.Fatal("bindDropzone() not found")
|
|
}
|
|
if strings.Contains(body, `$("#dz")`) || strings.Contains(body, `$("#adp-name")`) {
|
|
t.Error("bindDropzone still hard-codes the adapter's element ids; the " +
|
|
"plugin form would write into the adapter form")
|
|
}
|
|
if !strings.Contains(body, "dzId") || !strings.Contains(body, "nameSel") {
|
|
t.Error("bindDropzone does not accept the ids to bind")
|
|
}
|
|
// Both forms must call it.
|
|
if !strings.Contains(src, `bindDropzone("pl-dz", "pl-file", "#pl-name", "#pl-code")`) {
|
|
t.Error("the plugin upload form does not use the parameterised dropzone")
|
|
}
|
|
}
|
|
|
|
// TestPluginElementsSurviveHostRebuild guards the defect that made plugin
|
|
// elements look absent no matter how the injection was configured.
|
|
//
|
|
// renderStatus (and six other pages) assign pane.innerHTML wholesale. Anything a
|
|
// plugin had mounted into that pane is destroyed by the assignment. The symptom
|
|
// is silent and misleading: the plugin really did declare an element, the
|
|
// payload really did arrive, and the element is still gone on the next repaint —
|
|
// so the natural conclusion is "my plugin declared nothing", which sends you
|
|
// looking in the wrong file.
|
|
//
|
|
// The fix is to re-mount after the rebuild. This test asserts the re-mount is
|
|
// wired at the SINGLE place every renderer passes through, rather than leaving
|
|
// it to be re-added per page.
|
|
func TestPluginElementsSurviveHostRebuild(t *testing.T) {
|
|
html := uiSource(t)
|
|
|
|
if !strings.Contains(html, "function remountPluginElements") {
|
|
t.Fatal("remountPluginElements is not defined; nothing can re-attach a plugin element after a host rebuild")
|
|
}
|
|
if !strings.Contains(html, "const PLUGIN_MOUNT_HOOKS = []") {
|
|
t.Fatal("PLUGIN_MOUNT_HOOKS is not declared")
|
|
}
|
|
// The hook array must be declared BEFORE injectPluginUI pushes to it, and
|
|
// before refresh() calls into it. A use-before-declaration in a const
|
|
// block is a hard TDZ ReferenceError at first paint.
|
|
hookDecl := strings.Index(html, "const PLUGIN_MOUNT_HOOKS = []")
|
|
push := strings.Index(html, "PLUGIN_MOUNT_HOOKS.push")
|
|
use := strings.Index(html, "PLUGIN_MOUNT_HOOKS.forEach")
|
|
if hookDecl < 0 || push < 0 || use < 0 {
|
|
t.Fatal("the hook array is declared but never both filled and drained")
|
|
}
|
|
if hookDecl > push || hookDecl > use {
|
|
t.Error("PLUGIN_MOUNT_HOOKS is used before its declaration (const TDZ: first paint would throw)")
|
|
}
|
|
|
|
// refresh() is the chokepoint every renderer passes through.
|
|
rf := strings.Index(html, "function refresh(tab)")
|
|
if rf < 0 {
|
|
t.Fatal("refresh(tab) is gone")
|
|
}
|
|
body := html[rf:]
|
|
if i := strings.Index(body, "\n }"); i > 0 {
|
|
body = body[:i]
|
|
}
|
|
if !strings.Contains(body, "remountPluginElements") {
|
|
t.Error("refresh() does not re-mount plugin elements: a page that rebuilds its DOM wipes them")
|
|
}
|
|
|
|
// A mount must be idempotent, or the widget's <script> runs again on every
|
|
// host repaint and its counters silently double.
|
|
if !strings.Contains(html, `data-idx="`) || !strings.Contains(html, "plugin-el[data-idx=") {
|
|
t.Error("element mounting is not guarded by a per-pane marker; re-mounting would re-run plugin scripts")
|
|
}
|
|
}
|