diff --git a/changes/plugin-runtime-compatibility.json b/changes/plugin-runtime-compatibility.json new file mode 100644 index 0000000..d2ef969 --- /dev/null +++ b/changes/plugin-runtime-compatibility.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["cosimawei"], + "zh": "在插件列表和设置中提示当前运行时不支持的插件设置。", + "en": "Show which settings the active runtime does not support in the plugin list and settings dialog." +} diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index a3e520f..9226a51 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -46,6 +46,8 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V 启动前钩子在单插件 2 秒、整条链路 10 秒的时限内返回启动意图(白名单内的参数片段、带命名空间前缀的环境变量、警告或阻塞理由、受控启动后动作)。宿主与所属驱动合并意图后一次性写入配置,并在虚拟机目录记录参数归属账本:插件停用或卸载时精确剥离其名下参数,用户手工填写的高级参数永不被自动剥离。连续超时或报错的外部插件自动降级并在插件页提示原因,不阻塞虚拟机启停。 +声明式 `vm.beforeStart` 规则的 `set_env` 动作可用 `envFromSettings` 将本插件命名空间内的环境变量映射到设置键。宿主按设置的应用或虚拟机作用域读取值,仅导出未标记为敏感的字符串和布尔值。两种作用域都可配置时,虚拟机值优先于应用值。规则可以用 `runtime.capabilities` 限定支持该设置的运行时。 + 未启用外部插件时,插件内核保持零额外开销:无订阅者时不构造日志等高频事件对象,不轮询插件状态,外部子进程、沙箱面板与远程市场索引一律在首次使用时惰性拉起或请求,使用内置默认主题时不注入额外样式表、不加载交互脚本接口。 ## 主题、面板桥接与契约演进 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ed836b..0d7834a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1445,6 +1445,7 @@ export const App: React.FC = () => { locale={locale} appearance={theme} safeMode={state.safe_mode} + runtimeCommit={state.active_runtime?.commit} onRefresh={refresh} onError={fail} onThemeChanged={() => setThemeRevision((r) => r + 1)} diff --git a/frontend/src/components/PluginsPage.tsx b/frontend/src/components/PluginsPage.tsx index 6b3f9cb..173d2ff 100644 --- a/frontend/src/components/PluginsPage.tsx +++ b/frontend/src/components/PluginsPage.tsx @@ -27,6 +27,7 @@ interface Props { locale: Locale appearance: 'light' | 'dark' safeMode?: boolean + runtimeCommit?: string onRefresh: () => void onError: (title: string, e: unknown) => void onThemeChanged?: () => void @@ -48,7 +49,7 @@ function hasAppSettings(p: PluginInfo): boolean { /** Top-level Plugins & Themes management page. */ export const PluginsPage: React.FC = ({ - locale, appearance, safeMode, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate, + locale, appearance, safeMode, runtimeCommit, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed') @@ -63,6 +64,7 @@ export const PluginsPage: React.FC = ({ const [approveChecked, setApproveChecked] = useState(false) const approveTargetIDRef = useRef('') const [settingsTarget, setSettingsTarget] = useState(null) + const settingsRuntimeWarning = plugins.find((p) => p.id === settingsTarget?.id)?.runtime_warning const [settingsValues, setSettingsValues] = useState>({}) const settingsSaveQueuesRef = useRef(new Map>()) const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null) @@ -154,7 +156,7 @@ export const PluginsPage: React.FC = ({ onThemeChanged?.() } - useEffect(() => { void reload() }, [safeMode]) + useEffect(() => { void reload() }, [safeMode, runtimeCommit, locale]) useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab]) @@ -442,6 +444,12 @@ export const PluginsPage: React.FC = ({ {alert} )} + {p.runtime_warning && ( +
+
+ )}
{!isBuiltin && ( @@ -883,6 +891,12 @@ export const PluginsPage: React.FC = ({ onClose={() => setSettingsTarget(null)} >
+ {settingsRuntimeWarning && ( +
+
+ )} 0 { + info.RuntimeWarning = i18n.M(locale, "plugin.runtime_settings_skipped", i18n.Vars{ + "settings": strings.Join(settings, ", "), + }) + } + } + return infos } func (a *App) InstallPluginArchive(archivePath string) (*plugin.PluginInfo, error) { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 8374445..7991197 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -528,6 +528,7 @@ var catalog = map[Locale]map[string]string{ "plugin.not_found": "未找到插件 \"{id}\"", "plugin.packed": "已打包插件 {id}@{ver} -> {path}", "plugin.removed": "已卸载 {id}(purge={purge})", + "plugin.runtime_settings_skipped": "当前运行时无法应用以下设置:{settings}。切换到支持这些功能的运行时即可使用。", "plugin.target_not_found": "未找到插件或目录 \"{target}\"", "pluginSafeModeShort": "安全模式", "quitFailed": "已取消退出", @@ -1233,6 +1234,7 @@ var catalog = map[Locale]map[string]string{ "plugin.not_found": "plugin \"{id}\" not found", "plugin.packed": "Packed {id}@{ver} -> {path}", "plugin.removed": "Removed {id} (purge={purge})", + "plugin.runtime_settings_skipped": "The current runtime cannot apply these settings: {settings}. Switch to a runtime that supports them.", "plugin.target_not_found": "plugin or directory \"{target}\" not found", "pluginSafeModeShort": "Safe mode", "quitFailed": "Quit canceled", @@ -1549,6 +1551,7 @@ var paramOrder = map[string][]string{ "plugin.not_found": {"id"}, "plugin.packed": {"id", "ver", "path"}, "plugin.removed": {"id", "purge"}, + "plugin.runtime_settings_skipped": {"settings"}, "plugin.target_not_found": {"target"}, "resLooksLike": {"h", "w"}, "runtime.activated": {"commit"}, diff --git a/internal/lifecycle/lifecycle.go b/internal/lifecycle/lifecycle.go index 1ffec38..dd99f6d 100644 --- a/internal/lifecycle/lifecycle.go +++ b/internal/lifecycle/lifecycle.go @@ -40,7 +40,7 @@ func (s *Service) ResolveForDelete(ctx context.Context, driverID, name string) ( } func defaultPayload(d driver.Driver, vm driver.VMInfo) plugin.BeforeStartPayload { - p := plugin.BeforeStartPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID(), + p := plugin.BeforeStartPayload{VMName: vm.Name, VMSettingsKey: vm.Ref().Key(), VMDir: vm.Directory, DriverID: d.ID(), RuntimeKind: d.RuntimeKind(), VMCaps: d.Capabilities(), State: vm.State} if vm.DriverData != nil { p.ExtraArgs, _ = vm.DriverData["extra_args"].(string) diff --git a/internal/plugin/hooks.go b/internal/plugin/hooks.go index 7899963..07bb30c 100644 --- a/internal/plugin/hooks.go +++ b/internal/plugin/hooks.go @@ -64,6 +64,7 @@ type BeforeCreateResult struct { // BeforeStartPayload is passed to vm.beforeStart handlers. type BeforeStartPayload struct { VMName string `json:"vm_name"` + VMSettingsKey string `json:"-"` // driver-qualified key for declarative rules VMDir string `json:"vm_dir"` DriverID string `json:"driver_id"` ExtraArgs string `json:"extra_args"` @@ -442,14 +443,15 @@ func (b *HookBus) runLogBatcher(ch <-chan LogLineEvent) { // keys before handing a BeforeStartPayload to any external plugin. func redactBeforeStartPayload(p BeforeStartPayload) BeforeStartPayload { return BeforeStartPayload{ - VMName: p.VMName, - DriverID: p.DriverID, - HasInstaller: p.HasInstaller, - RuntimeKind: p.RuntimeKind, - RuntimeCaps: append([]string(nil), p.RuntimeCaps...), - HostFacts: StripSensitiveFields(p.HostFacts), - VMCaps: append([]string(nil), p.VMCaps...), - State: p.State, + VMName: p.VMName, + VMSettingsKey: p.VMSettingsKey, + DriverID: p.DriverID, + HasInstaller: p.HasInstaller, + RuntimeKind: p.RuntimeKind, + RuntimeCaps: append([]string(nil), p.RuntimeCaps...), + HostFacts: StripSensitiveFields(p.HostFacts), + VMCaps: append([]string(nil), p.VMCaps...), + State: p.State, } } diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index ade6d7a..ebac491 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -97,6 +97,7 @@ func NewManager(opts ManagerOptions) (*Manager, error) { supervisors: make(map[string]*SidecarSupervisor), l10nCache: make(map[string]map[string]string), } + reg.ruleSettings = m.GetSettings reg.OnChange(func() { m.mu.Lock() clear(m.l10nCache) diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index abfa6e9..d4f9b9f 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -98,6 +98,7 @@ type Registry struct { onChange []func() logger func(source, line string) localeFn func() i18n.Locale + ruleSettings func(pluginID, vmName string, maskSecrets bool) map[string]any // Extension point tables. themes map[string]ThemeContribution @@ -631,7 +632,7 @@ func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) { // Register L1 declarative rule hooks on the hook bus. if len(m.Contributes.RuleHooks) > 0 { rules := append([]RuleHook(nil), m.Contributes.RuleHooks...) - r.registerRuleHooks(sc, pid, rules) + r.registerRuleHooks(sc, pid, rules, m.Settings) } // Register declarative services declared in external Manifest.Provides. for _, pr := range m.Provides { diff --git a/internal/plugin/rule_settings_test.go b/internal/plugin/rule_settings_test.go new file mode 100644 index 0000000..1f592fc --- /dev/null +++ b/internal/plugin/rule_settings_test.go @@ -0,0 +1,110 @@ +package plugin + +import ( + "context" + "reflect" + "testing" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +func TestRuleEnvironmentUsesVisiblePluginSettings(t *testing.T) { + const pluginID = "local.capture-shortcut" + const vmKey = "builtin.guest.macos:test-vm" + reg := NewRegistry(nil) + reg.ruleSettings = func(id, key string, maskSecrets bool) map[string]any { + if id != pluginID || !maskSecrets { + t.Errorf("unexpected settings lookup: %q %q %v", id, key, maskSecrets) + return nil + } + switch key { + case vmKey: + return map[string]any{"shortcut": "Ctrl+F12", "autoRelease": false, "token": "private"} + case "": + return map[string]any{"shortcut": "Ctrl+F11", "label": "app"} + default: + t.Errorf("unexpected VM settings lookup: %q", key) + return nil + } + } + schema := &SettingsSchema{Scope: "vm", Properties: map[string]SettingProperty{ + "shortcut": {Scope: "both"}, "autoRelease": {}, "label": {Scope: "app"}, "token": {Secret: true}, + }} + rule := RuleHook{Event: EventVMBeforeStart, Actions: []RuleAction{ + {Kind: "set_env", EnvFromSettings: map[string]string{ + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS": "shortcut", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE": "autoRelease", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_LABEL": "label", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_TOKEN": "token", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_OVERRIDE": "shortcut", + "PATH": "shortcut", + }}, + {Kind: "set_env", Env: map[string]string{"REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_OVERRIDE": "fixed"}}, + }} + if err := reg.Register(PluginDef{ + Manifest: Manifest{ + ID: pluginID, + Version: "1.0.0", + Permissions: []string{"vm:intent"}, + Settings: schema, + Contributes: Contributes{RuleHooks: []RuleHook{rule}}, + }, + Source: SourceLocal, + Desired: true, + }); err != nil { + t.Fatal(err) + } + reg.Reconcile(context.Background()) + intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), BeforeStartPayload{ + VMName: "test-vm", VMSettingsKey: vmKey, + }) + if err != nil || len(intents) != 1 { + t.Fatalf("unexpected startup intents: %#v, %v", intents, err) + } + want := map[string]string{ + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS": "Ctrl+F12", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE": "false", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_LABEL": "app", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_OVERRIDE": "fixed", + } + if !reflect.DeepEqual(intents[0].Env, want) { + t.Fatalf("unexpected environment: %#v", intents[0].Env) + } +} + +func TestRuntimeUnavailableSettings(t *testing.T) { + const capability = "window-release-shortcut" + manifest := Manifest{ + ID: "local.capture-shortcut", + Settings: &SettingsSchema{Properties: map[string]SettingProperty{ + "releaseKeys": {Title: LocalizedText{ZhCN: "释放快捷键"}}, + "releaseOnLeave": {Title: LocalizedText{ZhCN: "鼠标移出时释放"}}, + "private": {Secret: true}, + }}, + Contributes: Contributes{RuleHooks: []RuleHook{{ + Event: EventVMBeforeStart, + Conditions: []RuleCondition{{Fact: "runtime.capabilities", Operator: "contains", Value: capability}}, + Actions: []RuleAction{{Kind: "set_env", EnvFromSettings: map[string]string{ + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS": "releaseKeys", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE": "releaseOnLeave", + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_PRIVATE": "private", + }}}, + }}}, + } + locale := i18n.Locale("zh-CN") + if got := RuntimeUnavailableSettings(manifest, nil, locale); !reflect.DeepEqual(got, []string{"释放快捷键", "鼠标移出时释放"}) { + t.Fatalf("unexpected settings for incompatible runtime: %v", got) + } + if got := RuntimeUnavailableSettings(manifest, []string{capability}, locale); len(got) != 0 { + t.Fatalf("compatible runtime should have no warning: %v", got) + } + manifest.Contributes.RuleHooks = append(manifest.Contributes.RuleHooks, RuleHook{ + Event: EventVMBeforeStart, + Actions: []RuleAction{{Kind: "set_env", EnvFromSettings: map[string]string{ + "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS": "releaseKeys", + }}}, + }) + if got := RuntimeUnavailableSettings(manifest, nil, locale); !reflect.DeepEqual(got, []string{"鼠标移出时释放"}) { + t.Fatalf("settings covered by a fallback should have no warning: %v", got) + } +} diff --git a/internal/plugin/rules.go b/internal/plugin/rules.go index 032a4f4..2a5f5b9 100644 --- a/internal/plugin/rules.go +++ b/internal/plugin/rules.go @@ -3,7 +3,10 @@ package plugin import ( "context" "fmt" + "slices" "strings" + + "github.com/Nwflower/reims-go/internal/i18n" ) // RuleCondition is a declarative, non-Turing-complete predicate over host, VM, @@ -16,13 +19,14 @@ type RuleCondition struct { // RuleAction is a constrained action emitted when all conditions match (§5.4). type RuleAction struct { - Kind string `json:"kind"` // "append_args" | "set_env" | "warn" | "post_start" - Key string `json:"key,omitempty"` // fragment key for append_args - Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens - Env map[string]string `json:"env,omitempty"` // env overrides - Message LocalizedText `json:"message,omitempty"` // localized warning text (accepts string or {"zh-CN":..., "en-US":...}) - Action string `json:"action,omitempty"` // post_start kind - Params map[string]any `json:"params,omitempty"` + Kind string `json:"kind"` // "append_args" | "set_env" | "warn" | "post_start" + Key string `json:"key,omitempty"` // fragment key for append_args + Tokens []string `json:"tokens,omitempty"` // QEMU arg tokens + Env map[string]string `json:"env,omitempty"` // env overrides + EnvFromSettings map[string]string `json:"envFromSettings,omitempty"` // environment key to plugin setting + Message LocalizedText `json:"message,omitempty"` // localized warning text (accepts string or {"zh-CN":..., "en-US":...}) + Action string `json:"action,omitempty"` // post_start kind + Params map[string]any `json:"params,omitempty"` } // RuleHook is an L1 declarative hook rule contributed via plugin.json (§5.4). @@ -92,7 +96,7 @@ func factContains(actual, needle any) bool { } } -func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHook) { +func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHook, schema *SettingsSchema) { for _, rule := range rules { rl := rule switch rl.Event { @@ -110,7 +114,7 @@ func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHoo if !EvaluateRuleConditions(rl.Conditions, facts) { return nil, nil } - return buildRuleStartIntent(pluginID, rl, string(r.currentLocale())), nil + return r.buildRuleStartIntent(pluginID, rl, string(r.currentLocale()), schema, p.VMSettingsKey), nil }, }) case EventHostPreflight: @@ -142,6 +146,82 @@ func (r *Registry) registerRuleHooks(sc *Scope, pluginID string, rules []RuleHoo } } +// RuntimeUnavailableSettings reports settings guarded by rules that depend only +// on runtime capabilities. VM-specific rules cannot be assessed on the plugin page. +func RuntimeUnavailableSettings(m Manifest, caps []string, loc i18n.Locale) []string { + if m.Settings == nil { + return nil + } + facts := map[string]any{"runtime.capabilities": caps} + unavailable := make(map[string]bool) + available := make(map[string]bool) + for _, rule := range m.Contributes.RuleHooks { + if rule.Event != EventVMBeforeStart || slices.ContainsFunc(rule.Conditions, func(c RuleCondition) bool { + return c.Fact != "runtime.capabilities" + }) { + continue + } + matches := EvaluateRuleConditions(rule.Conditions, facts) + for _, action := range rule.Actions { + if action.Kind != "set_env" { + continue + } + for envKey, settingKey := range action.EnvFromSettings { + prop, ok := m.Settings.Properties[settingKey] + if !ok || prop.Secret || !ValidateEnvKey(m.ID, envKey) { + continue + } + if matches { + available[settingKey] = true + } else { + unavailable[settingKey] = true + } + } + } + } + var labels []string + for key := range unavailable { + if available[key] { + continue + } + label := m.Settings.Properties[key].Title.Get(string(loc)) + if label == "" { + label = key + } + labels = append(labels, label) + } + slices.Sort(labels) + return slices.Compact(labels) +} + +func (r *Registry) applyRuleEnvSettings(intent *StartIntent, action RuleAction, schema *SettingsSchema, vmKey string) { + if schema == nil || r.ruleSettings == nil { + return + } + for envKey, settingKey := range action.EnvFromSettings { + prop, ok := schema.Properties[settingKey] + if !ok || prop.Secret || !ValidateEnvKey(intent.PluginID, envKey) { + continue + } + scope := prop.Scope + if scope == "" { + scope = schema.Scope + } + settingsVM := "" + if scope == "vm" || scope == "both" { + settingsVM = vmKey + } + value := r.ruleSettings(intent.PluginID, settingsVM, true)[settingKey] + switch value := value.(type) { + case string, bool: + if intent.Env == nil { + intent.Env = make(map[string]string) + } + intent.Env[envKey] = fmt.Sprint(value) + } + } +} + func buildStartFacts(p BeforeStartPayload) map[string]any { facts := make(map[string]any, len(p.HostFacts)+8) for k, v := range p.HostFacts { @@ -157,7 +237,7 @@ func buildStartFacts(p BeforeStartPayload) map[string]any { return facts } -func buildRuleStartIntent(pluginID string, rule RuleHook, loc string) StartIntent { +func (r *Registry) buildRuleStartIntent(pluginID string, rule RuleHook, loc string, schema *SettingsSchema, vmKey string) StartIntent { intent := StartIntent{PluginID: pluginID} for i, act := range rule.Actions { switch act.Kind { @@ -184,6 +264,7 @@ func buildRuleStartIntent(pluginID string, rule RuleHook, loc string) StartInten intent.Env[k] = v } } + r.applyRuleEnvSettings(&intent, act, schema, vmKey) case "warn": if msg := act.Message.Get(loc); msg != "" { intent.Warnings = append(intent.Warnings, msg) diff --git a/internal/plugin/types.go b/internal/plugin/types.go index 4ab1ae1..f1c7ec4 100644 --- a/internal/plugin/types.go +++ b/internal/plugin/types.go @@ -818,6 +818,7 @@ type PluginInfo struct { InUse bool `json:"in_use"` Error string `json:"error,omitempty"` DegradedReason string `json:"degraded_reason,omitempty"` + RuntimeWarning string `json:"runtime_warning,omitempty"` Permissions []PermissionSpec `json:"permissions,omitempty"` ApprovedPermissions []string `json:"approved_permissions,omitempty"` NeedsApproval bool `json:"needs_approval"` diff --git a/locales/en-US/native.json b/locales/en-US/native.json index a0100fb..f1fd1e0 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -1,4 +1,5 @@ { + "plugin.runtime_settings_skipped": "The current runtime cannot apply these settings: {settings}. Switch to a runtime that supports them.", "network.log.create_network_prepare": "Preparing network dependencies and checking the uplink", "network.log.mode_applied": "Network mode applied: {mode}", "network.log.uplink_switched": "Bridged uplink changed. The main adapter was notified to reconnect and renew DHCP", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 6132c64..8d2d738 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -1,4 +1,5 @@ { + "plugin.runtime_settings_skipped": "当前运行时无法应用以下设置:{settings}。切换到支持这些功能的运行时即可使用。", "network.log.create_network_prepare": "正在准备网络依赖并检查出口", "network.log.mode_applied": "网络模式已应用:{mode}", "network.log.uplink_switched": "桥接出口已更换,已通知主网卡重新连接并续租 DHCP",