Skip to content

Preserve panel order in opted-in Mihomo proxy groups - #94

Merged
limeflash merged 9 commits into
Mistgate:mainfrom
Morvex885:fix/mihomo-group-order
Dec 3, 2026
Merged

limeflash merged 9 commits into
Mistgate:mainfrom
Morvex885:fix/mihomo-group-order

Conversation

@Morvex885

@Morvex885 Morvex885 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Closes #92.

Что изменилось

  • Новый флаг mistgate-ordered-proxies: true включает порядок панели для группы в шаблоне Mihomo. В готовой группе сначала идут явно заданные участники, затем серверы пользователя в порядке панели и после них — прокси из шаблона. Сам флаг не попадает в YAML превью и подписки.
  • Нативное поведение include-all-proxies, include-all и use не меняется; внешние провайдеры по-прежнему загружает Mihomo. В одной группе нельзя одновременно включить два способа автоматического добавления локальных прокси. Заготовки новых шаблонов используют новый флаг, сохранённые шаблоны не мигрируют.
  • В группах с новым флагом Mistgate разрешает имена настроек и преобразует скалярные значения так же, как Mihomo. Наследование через YAML merge сохраняется, одноимённые провайдеры не удаляются, а при превышении лимита времени на фильтрацию редактор показывает ошибку в превью черновика.
  • Версия regexp2 зафиксирована на v1.12.0. В локальной копии исправлен контроль времени в однопоточном WebAssembly: срок выполнения проверяется и во время сопоставления.

Проверки

  • Целевые Go-тесты Mihomo, превью, порядка подписки, ProfileOrder и работы с шаблонами через MCP и ассистента.
  • Mihomo v1.19.34: состав и порядок .all с новым флагом и без него, выбор первого доступного прокси в fallback, порядок внешних провайдеров, приоритет KZ, исключения, числовые параметры и совместимость с существующими шаблонами.
  • Проверка истечения срока выполнения и тесты порядка групп в реальном js/wasm.
  • Проверка типов TypeScript, 100 тестов редактора, проверка новой заготовки в браузере, сборка и тесты документации.
  • scripts/check-edge-sizes.sh: все шесть сборок проходят. Admin Worker занимает 49,4 MiB при бюджете 50 MiB; лимиты остальных Worker не менялись.

Expand automatic local members in the rendered template so Mihomo keeps the panel order. Leave external providers and cross-source filter priority to the core.
Refs Mistgate#92.
Keep native Mihomo auto-inclusion unchanged. Use x-mistgate-ordered-proxies in new templates and strip it from the emitted YAML.
Refs Mistgate#92.
Keep directive removal within groups and their defaults. Match the core’s option lookup and scalar types, and reject provider-name conflicts.
Validate boolean opt-in and source locations; bound regexp polling and surface preview timeouts without exposing filter or node text.
Pin the upstream regexp2 v1.12.0 source with its MIT license. Poll monotonic time on wasm, where background goroutines cannot preempt the interpreter.
Test deadline expiry without yielding under the Go js/wasm runner.
The admin Worker validates and previews unsaved templates using the same regexp2 matching as subscription rendering. Moving it to the public Worker would require a cross-Worker RPC for an owner-only operation.
The release-style admin build is 49.4 MiB. Raise only its budget from 49 to 50 MiB, below the 64 MiB Cloudflare ceiling.
@limeflash

Copy link
Copy Markdown
Collaborator

Thanks for this — the ordering work is careful, and the test against a real Mihomo core is great. I checked the group composition against Mihomo's own parser and found no ordering, dedupe, filter, use or YAML-merge problems. A few things before we can merge:

Must change

  1. Please drop the vendored regexp2 fork (third_party/regexp2 and the replace in go.mod) and depend on upstream github.com/dlclark/regexp2 v1.12.0 directly.

    • On deployed Cloudflare Workers, performance.now()/Date.now() don't advance while code runs (Spectre mitigation), so the patched clock can't expire there either. It only works under Node, which is where the wasm test runs. Our mihomoGroupFilters budget has the same limit on the edge.
    • Polling the time on every opcode makes wasm matching about 3.3x slower (Node, 1000 names, lookahead filter: 7.0 ms → 23.2 ms).
    • The copy drops upstream's ATTRIB file, which carries the MIT notice for the code ported from dotnet/corefx and the BSD notice for the Go-derived parts. It also drops all upstream tests and has no MISTGATE.md/internal/vendorcheck entry like our other third_party copies.

    Keeping MatchTimeout is fine: it works on the VPS build. On the edge, the Worker CPU limit is the backstop; please mention that in the docs.

Should change

  1. Don't switch a person to the built-in profile when the filter budget runs out while serving a subscription. The budget is wall-clock, so CPU contention can trip it: in a local run with 40 concurrent renders on one CPU, 1 of 40 hit it with a harmless filter. The person then silently gets different rules. Please return an error instead (clients keep their cached profile) and log a distinct code for it, e.g. mihomo_template_filter_budget. The error text has no names in it, so it's safe to log.
  2. The save check only tries the names server 1 and server 2. A filter like ^(\w+\s?)*$ saves fine and then times out for any node with a long name. Please add one long sample name to the trial build (64+ characters is enough).
  3. Docs: list the new save refusals under "What a save checks" (the flag together with include-all*, a group named like a provider, a non-boolean flag, an invalid regex, the filter time limit). Also say what happens when the limit is hit. Please update the comments in subscription.proto (around lines 140 and 393), which still point to include-all-proxies, and regenerate.
  4. Tests:
    • a real catastrophic pattern rendered natively, which should fail with ErrMihomoFilterBudget well under a second;
    • the subscription path when the budget is hit;
    • the preview returning InvalidArgument when the budget is hit;
    • keep one native include-all-proxies group in the golden fixtures, since that's what existing saved templates look like.

Nits (optional)

  • A short release note: after a downgrade, groups that use the flag render with no members, and Mihomo rejects the file.
  • Maybe refuse the flag on type: relay.
  • Mention in the docs that with a multi-part filter plus providers, the core reorders explicit members too, so Auto may stop being first in a select group.

Size: by my build, admin goes 48.8 → 49.4 MiB and public 29.2 → 29.8 MiB (233 KiB left under its limit). We'll take the admin bump on our side, but please mention the public number in the script comment.

Happy to re-review once the fork is gone. Thanks again!

- Use upstream regexp2 and document the Cloudflare Worker CPU limit.
- Fail subscription refresh and draft preview when matching times out; validate a long sample name on save.
- Cover the failure paths and keep a native group in the golden fixture.
@Morvex885

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @limeflash. I pushed the fixes in b9529ac781:

  • Removed the vendored fork and switched to upstream regexp2 v1.12.0. The docs now explain that the Worker CPU limit is the backstop on Cloudflare.
  • Filter timeouts now fail the subscription refresh instead of serving the built-in profile, with a distinct mihomo_template_filter_budget log code. Draft preview returns InvalidArgument, and save validation now tries a long server name.
  • Added timeout regression tests, restored a native include-all-proxies group in the golden fixture, and updated the docs and regenerated protobuf bindings.

The native render stopped the pathological filter in about 240 ms. Tests with Mihomo v1.19.34 and js/wasm passed, as did the full Go and web checks. The public Worker is 29.8 MiB with 228 KiB of headroom; the admin Worker is under its 50 MiB limit.

Ready for another look when you have time.

@limeflash

Copy link
Copy Markdown
Collaborator

Thanks, @Morvex885 — everything from the review is addressed: the fork is gone, a timeout now fails the refresh with mihomo_template_filter_budget instead of swapping the profile, the save check tries a long name, and the docs, proto comments and tests are in. I re-ran the subs and subsettings tests locally on b9529ac781 and they pass. Merging.

@limeflash
limeflash merged commit f4dcd86 into Mistgate:main Dec 3, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mihomo: порядок нод из панели теряется в группах с include-all-proxies

2 participants