Introducing a new way to review your PRs.

Read the announcement

2dust / v2rayn

A GUI client for Windows, Linux and macOS, support Xray and sing-box and others

View on GitHub

13 documents · Updated Nov 16, 2026

docs / service-lib-viewmodels-app-orchestration

ServiceLib MVVM Application Orchestration

Overview

This area is the UI-agnostic application layer for v2rayN. v2rayN/…/MainWindowViewModel.cs is the main orchestrator: it owns the child view models for profiles, messages, Clash UI, updates, backup/restore, and the shared StatusBarViewModel, wires their EventChannel<T> notifications, opens dialogs through AppManager.Instance.WindowDialog, and turns user actions into persisted config/database changes plus core reloads. View models inherit v2rayN/…/MyReactiveObject.cs, which gives ReactiveUI activation and the shared ConfigTextHandler.Config reference; UI shells provide platform-specific operations through Interaction<,> properties and close dialogs by listening for ICloseable.RequestClose from v2rayN/…/ICloseable.cs.

Startup is split between v2rayN/…/AppManager.cs and MainWindowViewModel.cs. AppManager.InitApp() prepares logging, loads text config, sets culture, and creates SQLite tables for subscriptions, profiles, routing, profile extras, DNS, and templates. AppManager.InitComponents() calculates API ports and runs profile-extra migration. When the main view model is created, MainWindowViewModel.Init() initializes builtin DNS/templates, loads ProfileExManager, starts CoreManager, initializes certificate storage, registers TaskManager, optionally starts statistics, refreshes profile/status-bar lists, then calls Reload().

MainWindowViewModel.Reload() is the central runtime transition. It serializes reload requests with _reloadSemaphore and _hasNextReloadJob, gets the default server via ConfigTextHandler.GetDefaultServer(), builds core contexts with CoreConfigContextBuilder.BuildAll(), displays validator warnings through NoticeManager.NotifyValidatorResult(), calls CoreManager.Instance.LoadCore(), updates system proxy via SysProxyHandler.UpdateSysProxy(), schedules an availability check through StatusBarViewModel.TestServerAvailability(), and enables the Clash tabs only when AppManager.Instance.IsRunningCore(ECoreType.sing_box) is true. Reloads are requested by profile activation, routing changes, TUN toggles, option/DNS/template dialogs, update completion, and status-bar actions.

Profile and subscription work is concentrated in v2rayN/…/ProfilesViewModel.cs. It renders profiles from ConfigDbQuery.ProfileModels() joined with StatisticsManager.Instance.ServerStat and ProfileExManager.Instance.GetProfileExs(), writes active server changes through ConfigTextHandler.SetDefaultServerIndex(), and publishes ReloadRequested so MainWindowViewModel can reload the core. Add/edit flows open AddServerViewModel, AddServer2ViewModel, or AddGroupServerViewModel depending on EConfigType; saves use ConfigDbHandler.AddServer(), EditCustomServer(), AddServerCommon(), or related group/custom helpers. Clipboard and QR imports are initiated either by MainWindowViewModel menu commands or StatusBarViewModel tray commands, then end in ConfigDbHandler.AddBatchServers() and list/subscription refreshes. Subscription add/edit/delete is handled by SubSettingViewModel and SubEditViewModel, and update execution is delegated to SubscriptionHandler from MainWindowViewModel.UpdateSubscriptionProcess() or TaskManager.

The status bar and tray state live in v2rayN/…/StatusBarViewModel.cs, a singleton used by the main window. It owns routing-menu selection, system-proxy mode selection, TUN enablement, running-server display, inbound port display, real-time speed display, and tray-triggered server/subscription actions. It reads profiles/routings from ConfigDbQuery, writes default routing through ConfigDbHandler.SetDefaultRouting(), writes proxy/TUN choices to ConfigTextHandler.SaveConfig(), and asks the main view model to reload through ReloadRequested. On non-admin TUN enablement it either calls AppManager.Instance.RebootAsAdmin() on Windows or asks the UI for a sudo password through PasswordInputInteraction on Linux/macOS.

Settings dialogs mutate the shared config or SQLite-backed settings directly. OptionSettingViewModel copies inbound, core, UI, system proxy, TUN, update-source, speed-test, and core-type fields from _config, validates ports and fragment ranges, saves with ConfigTextHandler.SaveConfig(), updates OS autostart through AutoStartupHandler.UpdateTask(), and resets cached app ports through AppManager.Instance.Reset(). DNSSettingViewModel edits _config.SimpleDNSItem plus Xray/sing-box DNS rows from ConfigDbQuery.GetDNSItem() and persists them through ConfigDbHandler.SaveDNSItems(). FullConfigTemplateViewModel edits full-config template rows for Xray and sing-box. GlobalHotkeySettingViewModel edits _config.GlobalHotkeys.

Routing management is split between the status-bar quick selector and dialog view models. RoutingSettingViewModel lists RoutingItem rows, auto-saves domain strategy fields into _config.RoutingBasicItem, imports builtin routing via ConfigDbHandler.InitRouting(true), and opens RoutingRuleSettingViewModel. RoutingRuleSettingViewModel owns an in-memory _rules list parsed from RoutingItem.RuleSet, imports JSON rules from file/clipboard/URL, edits individual RulesItem records through RoutingRuleDetailsViewModel, and saves the serialized rule set with ConfigDbHandler.SaveRoutingItem(). After a successful routing dialog, MainWindowViewModel.RoutingSettingAsync() reinitializes builtin routing, refreshes the status-bar routing menu, and reloads the core.

The update, backup, and Clash subflows are also UI-facing view models. CheckUpdateViewModel builds a selectable list of core types from CoreInfoManager, stores selected update choices in _config.CheckUpdateItem, uses UpdateService and DownloadService to check/update GUI, cores, and geo files, then stops the core and publishes ReloadRequested after upgrades. BackupAndRestoreViewModel writes WebDAV settings to _config.WebDavItem, zips/restores the config directory, uploads/downloads through WebDavManager, and exits/reboots through AppManager during restore. ClashProxiesViewModel and ClashConnectionsViewModel poll the local Clash-compatible API via ClashApiManager only while active, auto-refresh is enabled, the app is shown in the taskbar, and the running core is sing-box/mihomo; they expose proxy group selection, delay tests, mode changes, and connection closing.

Events and notification plumbing are deliberately minimal. v2rayN/…/EventChannel.cs wraps a synchronized Reactive signal and is used for global events in v2rayN/…/AppEvents.cs plus view-model-local events. NoticeManager publishes snack and message-panel strings onto AppEvents.SendSnackMsgRequested and SendMsgViewRequested; MsgViewModel subscribes to the message stream, applies a regex filter from _config.MsgUIItem.MainMsgFilter, and flushes queued lines to the shell through ShowMsgInteraction. AppEvents.DispatcherStatisticsRequested carries ServerSpeedItem updates from MainWindowViewModel.UpdateStatisticsHandler() into ProfilesViewModel and StatusBarViewModel on the UI scheduler.

The covered managers provide state/services used by these view models. AppManager.cs owns app lifecycle, dialog host injection, port derivation, running core type, update-result cache, restart/shutdown, and config/database startup. TaskManager.cs runs a one-minute background timer for subscription auto-update, periodic config/profile-extra saves, geo updates, and daily update checks. ProfileExManager.cs caches sortable per-profile metadata and test results in memory, queues changed profile IDs, and flushes to SQLite during scheduled saves or app exit. GroupProfileManager.cs resolves child profiles for policy/proxy-chain groups and detects cycles. PacManager.cs serves PAC content on a TCP listener using configured/custom PAC text. EndpointResolveManager.cs builds system/UDP/TCP/DoH DNS resolvers and parses DNS wire responses. WebDavManager.cs wraps WebDAV backup transport. ClashApiManager.cs talks to the local API on AppManager.Instance.StatePort2 for proxies, modes, delay checks, config patches, and connections.

Coupling

Risks

  • v2rayN/…/MainWindowViewModel.cs intentionally coalesces concurrent reloads with _reloadSemaphore and _hasNextReloadJob. If new code calls Reload() and then assumes the core has already restarted, that assumption can be false when another reload is in progress; follow-up UI state should be driven by reload completion or scheduled on the main thread.
  • v2rayN/…/OptionSettingViewModel.cs mutates the shared _config object before ConfigTextHandler.SaveConfig() succeeds. If validation is added after partial mutation or saving fails, in-memory runtime state can differ from disk until restart.
  • v2rayN/…/TaskManager.cs starts ScheduledTasks() with Task.Run() and no cancellation or duplicate-registration guard. If RegUpdateTask() is called more than once in a process, multiple timers can update subscriptions, save config, and publish update messages concurrently.
  • v2rayN/…/ProfileExManager.cs delays SQLite writes through an in-memory queue. If the process exits without ProfileExManager.SaveTo() from AppManager.AppExitAsync() or the 20-minute TaskManager save, recent delay/speed/IP/sort updates can be lost.
  • v2rayN/…/RoutingRuleSettingViewModel.cs regenerates every rule ID before saving. UI code or tests that hold a RulesItem.Id across save boundaries will lose that reference.
  • v2rayN/…/PacManager.cs serves one cached _writeContent buffer to all PAC TCP clients and swallows per-client exceptions. If PAC generation fails or _writeContent is stale after a port/config change, clients may keep receiving an old PAC script until StartAsync() rebuilds it.

Routing / Covers

This document owns: