Merge pull request #112 from reims-go/feat/computer-use-review-fixes
fix: harden computer-use lifecycle and control channel
This commit is contained in:
42 files changed
+887
-311
No files matched your search
@@ -37,6 +37,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
### Microsoft go-winio
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Microsoft
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
### Unicode CLDR Windows timezone data
|
||||
|
||||
The Windows timezone fallback table uses the
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["bvzrays"],
|
||||
"zh": "修复虚拟机交互期间的启停、挂起和截图输入竞争,清理桌面重启后遗留的 MCP 临时虚拟机,并确保 MCP 控制通道在长请求、输入结束和请求失败时正确传递响应。登录密码通过键盘输入,不再经过客体剪贴板。",
|
||||
"en": "Fix races between VM lifecycle and console operations, clean up orphaned MCP temporary VMs after desktop restarts, and preserve MCP control-channel responses during long requests, input shutdown, and request failures. Login passwords are entered as keystrokes without passing through the guest clipboard."
|
||||
}
|
||||
@@ -47,7 +47,7 @@ flowchart TB
|
||||
|
||||
### 宿主控制台代理与本地控制通道
|
||||
|
||||
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。内置 `builtin.computer-use` 服务按虚拟机复用 QMP 长连接并串行处理截图、鼠标、键盘和文本输入;缩略图与打字流程共用该服务,键入期间暂停后台截图。
|
||||
便携运行时为每台运行中的虚拟机创建本地 Unix 域 QMP 套接字。内置虚拟机交互服务按虚拟机串行处理 QMP 操作,并在每次操作后关闭连接。生命周期操作与截图、鼠标和键盘输入共用同一把虚拟机锁。桌面文本输入期间暂停后台缩略图捕获。
|
||||
|
||||
L3 插件经权限核验的 Host API 请求虚拟机状态、截图和输入操作,宿主不接受插件提供的 QMP 套接字或虚拟机目录。MCP 客户端通过 `reims-go plugin connect <plugin-id> <channel>` 与桌面进程通信;Windows 命名管道按可执行文件路径和用户 SID 摘要区分,ACL 限制当前用户并拒绝远程客户端。
|
||||
|
||||
|
||||
@@ -30,11 +30,11 @@ flowchart TB
|
||||
2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。
|
||||
3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。
|
||||
|
||||
内置 `builtin.computer-use` 默认启用,通过宿主控制台代理串行处理每台虚拟机的截图、鼠标、键盘和文本输入,现有缩略图与打字入口共用该服务。它不实现 MCP 协议。
|
||||
内置虚拟机交互服务默认启用,通过宿主控制台代理串行处理每台虚拟机的 QMP 操作,每次操作后关闭连接,并与虚拟机生命周期操作共用锁。桌面文本输入期间暂停后台缩略图捕获。该服务不实现 MCP 协议。
|
||||
|
||||
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 `reims.agent` 插件实现 MCP 工具、VM 状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向插件返回明文。
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
|
||||
|
||||
## 生命周期、参数账本与资源预算
|
||||
|
||||
|
||||
@@ -112,15 +112,25 @@ export const SchemaForm: React.FC<Props> = ({
|
||||
if (prop['x-secret']) {
|
||||
const isMasked = cur === SECRET_MASK
|
||||
return (
|
||||
<input
|
||||
type="password"
|
||||
className="input rg-p-input"
|
||||
aria-label={label}
|
||||
autoComplete="new-password"
|
||||
placeholder={isMasked ? SECRET_MASK : undefined}
|
||||
value={isMasked ? '' : String(cur ?? '')}
|
||||
onChange={(e) => setKey(k, e.target.value)}
|
||||
/>
|
||||
<div className="input-group">
|
||||
<input
|
||||
type="password"
|
||||
className="input rg-p-input"
|
||||
aria-label={label}
|
||||
autoComplete="new-password"
|
||||
placeholder={isMasked ? SECRET_MASK : undefined}
|
||||
defaultValue={isMasked ? '' : String(cur ?? '')}
|
||||
onBlur={(e) => {
|
||||
const next = e.currentTarget.value
|
||||
if (next !== (isMasked ? '' : String(cur ?? ''))) setKey(k, next)
|
||||
}}
|
||||
/>
|
||||
{isMasked && (
|
||||
<button type="button" className="btn rg-p-button btn-ghost" onClick={() => setKey(k, '')}>
|
||||
{t(locale, 'pluginClearSecret')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginApproveTitle": "高危权限确认",
|
||||
"pluginApproveUIScriptWarn": "此插件包含交互界面脚本(ui:script),会在主窗口界面中运行并可访问页面内容,启用前务必核对来源与脚本 SHA-256",
|
||||
"pluginBuiltinSection": "内置插件",
|
||||
"pluginClearSecret": "清除",
|
||||
"pluginColorSchemes": "配色方案",
|
||||
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
|
||||
"pluginDeleteScheme": "删除方案",
|
||||
@@ -136,6 +137,7 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginApproveTitle": "Approve high-risk permissions",
|
||||
"pluginApproveUIScriptWarn": "This plugin runs an interactive script (ui:script) inside the main window with full access to the interface; verify its source and SHA-256 before enabling",
|
||||
"pluginBuiltinSection": "Built-in plugins",
|
||||
"pluginClearSecret": "Clear",
|
||||
"pluginColorSchemes": "Color schemes",
|
||||
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
|
||||
"pluginDeleteScheme": "Delete scheme",
|
||||
|
||||
@@ -688,6 +688,7 @@ export type I18nKey =
|
||||
| "pluginApproveTitle"
|
||||
| "pluginApproveUIScriptWarn"
|
||||
| "pluginBuiltinSection"
|
||||
| "pluginClearSecret"
|
||||
| "pluginColorSchemes"
|
||||
| "pluginColorSchemesHint"
|
||||
| "pluginDeleteScheme"
|
||||
|
||||
+9
-3
@@ -148,8 +148,7 @@ type App struct {
|
||||
keymapPIDs map[string]int
|
||||
fallbackInputSvc *host.InputService
|
||||
inputShuttingDown bool
|
||||
// computerUseOwnedVMs records temporary CoW VMs created by an MCP session.
|
||||
// Ownership is process-scoped and disappears when the desktop process exits.
|
||||
// computerUseOwnedVMs caches ownership markers for MCP-created temporary VMs.
|
||||
computerUseOwnedVMs map[string]map[string]bool
|
||||
computerUseCloneMu sync.Mutex
|
||||
}
|
||||
@@ -168,7 +167,14 @@ type Lifecycle struct {
|
||||
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
i18n.SetDetailRedactor(host.RedactText)
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
if err != nil {
|
||||
if launch.DataRoot != "" {
|
||||
cfg, err = config.Load(filepath.Join(launch.DataRoot, "reims-go.json"))
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
cfg.DataRoot = launch.DataRoot
|
||||
needsSetup = false
|
||||
} else if err != nil {
|
||||
cfg = config.Default()
|
||||
}
|
||||
a := &App{
|
||||
|
||||
@@ -13,18 +13,24 @@ func (a *App) CloneVMCoW(sourceName, cloneName string) error {
|
||||
}
|
||||
|
||||
func (a *App) CloneVMCoWWithDriver(driverID, sourceName, cloneName string) error {
|
||||
_, err := a.cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName)
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) cloneVMCoWWithDriverInfo(driverID, sourceName, cloneName string) (driver.VMInfo, error) {
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
return driver.VMInfo{}, errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
ref := driver.VMRef{DriverID: driverID, Name: sourceName}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(driverID, cloneName, line) })
|
||||
if err := svc.CloneCoW(a.baseCtx(), ref, cloneName, w, w); err != nil {
|
||||
return err
|
||||
cloned, err := svc.CloneCoWWithInfo(a.baseCtx(), ref, cloneName, w, w)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
return cloned, nil
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/console"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
@@ -18,11 +19,26 @@ func (a *App) computerUseService() (builtin.ComputerUseService, error) {
|
||||
}
|
||||
raw, ok := mgr.Registry().LookupService(builtin.ServiceComputerUse)
|
||||
if !ok {
|
||||
return nil, errors.New("virtual machine interaction is disabled")
|
||||
return nil, a.computerUseHostError("computer_use_unavailable", "err.computer_use.disabled", nil)
|
||||
}
|
||||
service, ok := raw.(builtin.ComputerUseService)
|
||||
if !ok || service == nil {
|
||||
return nil, errors.New("virtual machine interaction service is unavailable")
|
||||
return nil, a.computerUseHostError("computer_use_unavailable", "err.computer_use.unavailable", nil)
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func (a *App) computerUseInternalService() builtin.ComputerUseService {
|
||||
service, err := a.computerUseService()
|
||||
if err == nil {
|
||||
return service
|
||||
}
|
||||
return fallbackComputerUse
|
||||
}
|
||||
|
||||
func (a *App) withComputerUseVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
|
||||
if strings.TrimSpace(vmDir) == "" {
|
||||
return operation(ctx)
|
||||
}
|
||||
return a.computerUseInternalService().WithVM(ctx, vmDir, operation)
|
||||
}
|
||||
@@ -10,9 +10,11 @@ import (
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/plugin/builtin"
|
||||
"github.com/Nwflower/reims-go/internal/thumb"
|
||||
@@ -93,7 +95,11 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
|
||||
if len(secret) == 0 || utf8.RuneCountInString(secret) > computerUseMaxTextRunes {
|
||||
return nil, errors.New("secret must contain between 1 and 4000 characters")
|
||||
}
|
||||
count, err := a.injectTextIntoVMWithLogging(vm.Name, vm.Directory, secret, false, true)
|
||||
service, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
count, err := service.TypeText(ctx, vm.Directory, secret, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -224,29 +230,22 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cloneRef := driver.NewVMRef(vm.DriverID, cloneName)
|
||||
a.computerUseCloneMu.Lock()
|
||||
defer a.computerUseCloneMu.Unlock()
|
||||
if existing, listErr := a.listVMsInternal(ctx); listErr != nil {
|
||||
return nil, listErr
|
||||
} else if slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
|
||||
return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
|
||||
return strings.EqualFold(item.Name, cloneName) && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
|
||||
}) {
|
||||
return nil, fmt.Errorf("VM name %q is already taken", cloneName)
|
||||
}
|
||||
if err := a.CloneVMCoWWithDriver(vm.DriverID, vm.Name, cloneName); err != nil {
|
||||
// CloneCoW can fail after creating an overlay or VM record. The target
|
||||
// was absent during the preflight above, so clean up any partial target.
|
||||
if existing, listErr := a.listVMsInternal(ctx); listErr == nil && slices.ContainsFunc(existing, func(item driver.VMListItem) bool {
|
||||
return item.Name == cloneName && driver.CanonicalDriverID(item.DriverID) == driver.CanonicalDriverID(vm.DriverID)
|
||||
}) {
|
||||
if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("clean up failed clone %q: %w", cloneName, cleanupErr))
|
||||
}
|
||||
}
|
||||
cloned, err := a.cloneVMCoWWithDriverInfo(vm.DriverID, vm.Name, cloneName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := a.persistComputerUseOwnership(pluginID, cloneRef.Key()); err != nil {
|
||||
cloneRef := cloned.Ref()
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key())
|
||||
if err != nil {
|
||||
if cleanupErr := a.DeleteVMWithDriver(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr))
|
||||
}
|
||||
@@ -271,11 +270,13 @@ func (a *App) handleComputerUseVMDelete(ctx context.Context, raw json.RawMessage
|
||||
return nil, err
|
||||
}
|
||||
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
|
||||
return nil, fmt.Errorf("not_authorized: VM %q is not an MCP-owned temporary clone", vm.Name)
|
||||
return nil, a.computerUseHostError("not_authorized", "err.computer_use.not_owned", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
if vm.State == "running" {
|
||||
if err := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, false); err != nil {
|
||||
return nil, err
|
||||
if forceErr := a.stopVMWithDriverCtx(ctx, vm.DriverID, vm.Name, true); forceErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("force stop temporary VM %q: %w", vm.Name, forceErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(vm.DriverID, vm.Name, false); err != nil {
|
||||
@@ -335,7 +336,7 @@ func (a *App) handleComputerUseVMSnapshotRestore(_ context.Context, raw json.Raw
|
||||
return nil, err
|
||||
}
|
||||
if !a.computerUseOwned(pluginID, vm.Ref().Key()) {
|
||||
return nil, errors.New("confirmation_required: restoring a user VM requires confirmation in Reims-Go")
|
||||
return nil, a.computerUseHostError("confirmation_required", "err.computer_use.restore_confirmation", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
if err := a.RestoreSnapshotWithDriver(vm.DriverID, vm.Name, req.Name); err != nil {
|
||||
return nil, err
|
||||
@@ -371,14 +372,15 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
if driver.CanonicalDriverID(vm.DriverID) != builtin.IDDriverReimsMacOS {
|
||||
return driver.VMInfo{}, fmt.Errorf("computer_use_unavailable: driver %q does not support computer use", vm.DriverID)
|
||||
return driver.VMInfo{}, a.computerUseHostError("computer_use_unavailable", "err.computer_use.unsupported_driver", nil)
|
||||
}
|
||||
current, ok := a.polledVMForDriver(vm.DriverID, vm.Name)
|
||||
if !ok || current.State != "running" || current.PID == nil || *current.PID <= 0 {
|
||||
return driver.VMInfo{}, fmt.Errorf("vm_not_running: VM %q is not running", vm.Name)
|
||||
return driver.VMInfo{}, a.computerUseHostError("vm_not_running", "err.computer_use.vm_not_running", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
if phase := computerUseVMPhase(vm); phase != "normal" {
|
||||
return driver.VMInfo{}, fmt.Errorf("confirmation_required: VM %q is in %s phase", vm.Name, phase)
|
||||
phaseLabel := i18n.M(a.computerUseLocale(), "err.computer_use.phase."+phase, nil)
|
||||
return driver.VMInfo{}, a.computerUseHostError("confirmation_required", "err.computer_use.phase_confirmation", i18n.Vars{"name": vm.Name, "phase": phaseLabel})
|
||||
}
|
||||
if vm.Directory == "" {
|
||||
vm.Directory = current.Dir
|
||||
@@ -395,11 +397,25 @@ func (a *App) resolveAuthorizedComputerUseVMInfo(mgr *plugin.Manager, pluginID,
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
if !a.computerUseVMAccessEnabled(mgr, pluginID, vm.Ref().Key()) {
|
||||
return driver.VMInfo{}, fmt.Errorf("not_authorized: MCP access is disabled for VM %q in plugin settings", vm.Name)
|
||||
return driver.VMInfo{}, a.computerUseHostError("not_authorized", "err.computer_use.access_disabled", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
return vm, nil
|
||||
}
|
||||
|
||||
func (a *App) computerUseHostError(code, key string, params i18n.Vars) error {
|
||||
return fmt.Errorf("%s: %s", code, i18n.M(a.computerUseLocale(), key, params))
|
||||
}
|
||||
|
||||
func (a *App) computerUseLocale() i18n.Locale {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
loc := i18n.ZhCN
|
||||
if a.cfg != nil {
|
||||
loc = a.cfg.Locale
|
||||
}
|
||||
return loc
|
||||
}
|
||||
|
||||
func (a *App) computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) bool {
|
||||
return computerUseVMAccessEnabled(mgr, pluginID, vmKey) || a.computerUseOwned(pluginID, vmKey)
|
||||
}
|
||||
@@ -453,19 +469,26 @@ func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error {
|
||||
return err
|
||||
}
|
||||
path := filepath.Join(vmDir, computerUseOwnershipFile)
|
||||
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
file, err := os.CreateTemp(vmDir, computerUseOwnershipFile+".tmp-")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temporary VM ownership marker: %w", err)
|
||||
return fmt.Errorf("stage temporary VM ownership marker: %w", err)
|
||||
}
|
||||
if _, writeErr := file.Write(append(data, '\n')); writeErr != nil {
|
||||
tempPath := file.Name()
|
||||
defer os.Remove(tempPath)
|
||||
if _, err := file.Write(append(data, '\n')); err != nil {
|
||||
_ = file.Close()
|
||||
_ = os.Remove(path)
|
||||
return fmt.Errorf("write temporary VM ownership marker: %w", writeErr)
|
||||
return fmt.Errorf("write temporary VM ownership marker: %w", err)
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
_ = file.Close()
|
||||
return fmt.Errorf("sync temporary VM ownership marker: %w", err)
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
_ = os.Remove(path)
|
||||
return fmt.Errorf("close temporary VM ownership marker: %w", err)
|
||||
}
|
||||
if err := os.Link(tempPath, path); err != nil {
|
||||
return fmt.Errorf("publish temporary VM ownership marker: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -497,20 +520,54 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
a.syncComputerUseOwnership(vms)
|
||||
return nil
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
var cleanupErrors []error
|
||||
for _, item := range vms {
|
||||
vm := driver.VMInfo{Name: item.Name, DriverID: item.DriverID, Directory: item.Dir}
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if item.State == "running" {
|
||||
stopCtx, stopCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
err := a.stopVMWithDriverCtx(stopCtx, item.DriverID, item.Name, false)
|
||||
stopCancel()
|
||||
if err != nil {
|
||||
forceCtx, forceCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
forceErr := a.stopVMWithDriverCtx(forceCtx, item.DriverID, item.Name, true)
|
||||
forceCancel()
|
||||
if forceErr != nil {
|
||||
cleanupErrors = append(cleanupErrors, errors.Join(
|
||||
fmt.Errorf("stop orphaned temporary VM %q: %w", item.Name, err),
|
||||
fmt.Errorf("force stop orphaned temporary VM %q: %w", item.Name, forceErr),
|
||||
))
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := a.DeleteVMWithDriver(item.DriverID, item.Name, false); err != nil {
|
||||
cleanupErrors = append(cleanupErrors, fmt.Errorf("delete orphaned temporary VM %q: %w", item.Name, err))
|
||||
continue
|
||||
}
|
||||
a.markComputerUseOwnedVM(marker.PluginID, vm.Ref().Key(), false)
|
||||
}
|
||||
return errors.Join(cleanupErrors...)
|
||||
}
|
||||
|
||||
func (a *App) persistComputerUseOwnership(pluginID, vmKey string) (bool, error) {
|
||||
vm, err := a.resolveComputerUseVMInfo(vmKey)
|
||||
if err != nil || vm.Directory == "" {
|
||||
// Driver inventories can lag behind a successful clone. The next VM
|
||||
// inventory pass will retry persistence without discarding the clone.
|
||||
return false, nil
|
||||
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey string) error {
|
||||
if vm.Directory == "" {
|
||||
return errors.New("temporary clone directory is unavailable")
|
||||
}
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
return true, nil
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok || marker.PluginID != pluginID {
|
||||
return errors.New("temporary VM ownership marker could not be verified")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
@@ -545,6 +602,12 @@ func computerUseVMPhase(vm driver.VMInfo) string {
|
||||
if vmInfoBool(vm, "has_installer") {
|
||||
return "installer"
|
||||
}
|
||||
if driver.CanonicalDriverID(vm.DriverID) == builtin.IDDriverReimsMacOS {
|
||||
if isRecoveryMarkerActive(vm.Directory) {
|
||||
return "recovery"
|
||||
}
|
||||
return "normal"
|
||||
}
|
||||
if vmInfoBool(vm, "recovery_mode") {
|
||||
return "recovery"
|
||||
}
|
||||
@@ -555,8 +618,7 @@ func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) boo
|
||||
if mgr == nil || strings.TrimSpace(pluginID) == "" || strings.TrimSpace(vmKey) == "" {
|
||||
return false
|
||||
}
|
||||
value, _ := mgr.GetSettings(pluginID, vmKey, false)["allow_ai_access"].(bool)
|
||||
return value
|
||||
return mgr.SavedBoolSetting(pluginID, vmKey, "allow_ai_access")
|
||||
}
|
||||
|
||||
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
|
||||
|
||||
@@ -23,7 +23,11 @@ func isRecoveryModeActive(d reims.VMDetail) bool {
|
||||
if d.HasInstaller {
|
||||
return true
|
||||
}
|
||||
m := startprep.ReadRecoveryMarker(d.Directory)
|
||||
return isRecoveryMarkerActive(d.Directory)
|
||||
}
|
||||
|
||||
func isRecoveryMarkerActive(vmDir string) bool {
|
||||
m := startprep.ReadRecoveryMarker(vmDir)
|
||||
return m == "on" || m == "want"
|
||||
}
|
||||
|
||||
@@ -187,9 +191,14 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
|
||||
base := filepath.Base(path)
|
||||
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
|
||||
if svc != nil {
|
||||
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
|
||||
err = a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
||||
_, err := svc.InvokeAction(operationCtx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
|
||||
return err
|
||||
})
|
||||
} else {
|
||||
err = c.Insert(ctx, name, path, w, w)
|
||||
err = a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
||||
return c.Insert(operationCtx, name, path, w, w)
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -279,7 +288,16 @@ func (a *App) FinishInstall(name string) error {
|
||||
if svc == nil {
|
||||
return a.finishInstallLegacy(name)
|
||||
}
|
||||
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "finish_install", nil)
|
||||
vm, err := a.resolveVMInfo("", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var raw any
|
||||
err = a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
|
||||
var invokeErr error
|
||||
raw, invokeErr = svc.InvokeAction(ctx, vm.Ref(), "finish_install", nil)
|
||||
return invokeErr
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -333,7 +351,9 @@ func (a *App) finishInstallLegacy(name string) error {
|
||||
|
||||
if d.HasInstaller {
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(ctx, name, w, w); err != nil {
|
||||
if err := a.withComputerUseVM(ctx, d.Directory, func(operationCtx context.Context) error {
|
||||
return c.Eject(operationCtx, name, w, w)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ func (a *App) buildInstallGuide(ctx context.Context, g installguide.Guide, d rei
|
||||
if err := checkBoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
stopped, err := a.restartMacOSVM(name)
|
||||
stopped, err := a.restartMacOSVM(a.baseCtx(), name)
|
||||
if stopped && err != nil {
|
||||
// The guest window has closed, so report start failures via the tray.
|
||||
loc, _ := a.guidePreferences()
|
||||
|
||||
+122
-81
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
@@ -112,16 +113,33 @@ func (a *App) StartVMWithDriver(driverID, name string) error {
|
||||
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
|
||||
return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID)
|
||||
}
|
||||
return a.startVMLegacy(name)
|
||||
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error {
|
||||
return a.startVMLegacy(vm.Name)
|
||||
})
|
||||
}
|
||||
_, vm, err := svc.Resolve(context.Background(), driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
if vm.State == "suspended" {
|
||||
return a.ResumeVMWithDriver(ref.DriverID, ref.Name)
|
||||
return a.ResumeVMWithDriver(vm.DriverID, vm.Name)
|
||||
}
|
||||
return a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
|
||||
return a.startResolvedVMLocked(ctx, svc, vm)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
|
||||
Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error)
|
||||
}, vm driver.VMInfo) error {
|
||||
if svc == nil {
|
||||
return a.startVMLegacy(vm.Name)
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
detail := vm
|
||||
a.mu.Lock()
|
||||
@@ -136,7 +154,7 @@ func (a *App) StartVMWithDriver(driverID, name string) error {
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Starting "+ref.Name+"...")
|
||||
result, err := svc.Start(context.Background(), ref, w, w)
|
||||
result, err := svc.Start(ctx, ref, w, w)
|
||||
if err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
@@ -181,34 +199,35 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.transitions[key] = "stopping"
|
||||
a.mu.Unlock()
|
||||
a.emitLifecycleStateChanged()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Stop(ctx, ref, force, w, w); err != nil {
|
||||
return a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.transitions[key] = "stopping"
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
a.emitLifecycleStateChanged()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if err := svc.Stop(operationCtx, ref, force, w, w); err != nil {
|
||||
a.mu.Lock()
|
||||
delete(a.transitions, key)
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
a.mu.Unlock()
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) EjectInstaller(name string) error { return a.EjectInstallerWithDriver("", name) }
|
||||
|
||||
func (a *App) EjectInstallerWithDriver(driverID, name string) error {
|
||||
@@ -221,7 +240,14 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error {
|
||||
}
|
||||
return a.ejectInstallerLegacy(name)
|
||||
}
|
||||
_, err := svc.InvokeAction(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, "eject", nil)
|
||||
vm, err := a.resolveVMInfo(driverID, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
|
||||
_, actionErr := svc.InvokeAction(ctx, vm.Ref(), "eject", nil)
|
||||
return actionErr
|
||||
})
|
||||
if err == nil {
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
@@ -240,6 +266,11 @@ func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string,
|
||||
}
|
||||
|
||||
func (a *App) RestartVMWithDriver(driverID, name string) error {
|
||||
if err := a.beginVMStart(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer a.vmStarts.Done()
|
||||
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
@@ -257,12 +288,21 @@ func (a *App) RestartVMWithDriver(driverID, name string) error {
|
||||
ref = driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, name)
|
||||
}
|
||||
if ref.DriverID != driver.BuiltinReimsMacOSDriverID {
|
||||
if err := a.StopVMWithDriver(ref.DriverID, ref.Name, false); err != nil {
|
||||
if svc == nil {
|
||||
return errors.New("driver lifecycle is not initialized")
|
||||
}
|
||||
_, vm, err := svc.Resolve(a.baseCtx(), ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.StartVMWithDriver(ref.DriverID, ref.Name)
|
||||
return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error {
|
||||
if err := a.stopVMWithDriverCtx(ctx, ref.DriverID, ref.Name, false); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.startResolvedVMLocked(ctx, svc, vm)
|
||||
})
|
||||
}
|
||||
_, err := a.restartMacOSVM(ref.Name)
|
||||
_, err := a.restartMacOSVM(a.baseCtx(), ref.Name)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -284,55 +324,56 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
removed, delErr := a.deleteVMWithGuestTools(ref.Name, func() error {
|
||||
return svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w)
|
||||
}, func() (bool, error) {
|
||||
vms, lerr := a.listVMsInternal(context.Background())
|
||||
if lerr != nil {
|
||||
return false, lerr
|
||||
}
|
||||
for _, item := range vms {
|
||||
if item.Name == ref.Name && driver.CanonicalDriverID(item.DriverID) == ref.DriverID {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if !removed {
|
||||
return delErr
|
||||
return a.withComputerUseVM(context.Background(), vm.Directory, func(ctx context.Context) error {
|
||||
ref := vm.Ref()
|
||||
key := ref.Key()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.cancelRebootWatcher(ref.Name)
|
||||
stopVMMonitor(ref.Name)
|
||||
}
|
||||
err = delErr
|
||||
} else {
|
||||
if err := svc.DeleteResolved(context.Background(), d, vm, keepFiles, w, w); err != nil {
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
var deleteErr error
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
removed, delErr := a.deleteVMWithGuestTools(ref.Name, func() error {
|
||||
return svc.DeleteResolved(ctx, d, vm, keepFiles, w, w)
|
||||
}, func() (bool, error) {
|
||||
vms, lerr := a.listVMsInternal(ctx)
|
||||
if lerr != nil {
|
||||
return false, lerr
|
||||
}
|
||||
for _, item := range vms {
|
||||
if item.Name == ref.Name && driver.CanonicalDriverID(item.DriverID) == ref.DriverID {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
if !removed {
|
||||
return delErr
|
||||
}
|
||||
deleteErr = delErr
|
||||
} else if err := svc.DeleteResolved(ctx, d, vm, keepFiles, w, w); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
delete(a.transitions, key)
|
||||
delete(a.diskPaths, key)
|
||||
delete(a.procSamples, key)
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
releaseVMTyping(ref.Name)
|
||||
releaseVMThumbnail(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return err
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
a.stopPacketBridge(ref.Name)
|
||||
}
|
||||
a.mu.Lock()
|
||||
delete(a.pendingChanges, key)
|
||||
delete(a.transitions, key)
|
||||
delete(a.diskPaths, key)
|
||||
delete(a.procSamples, key)
|
||||
gt := a.guestTools
|
||||
a.mu.Unlock()
|
||||
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
|
||||
releaseVMTyping(ref.Name)
|
||||
releaseVMThumbnail(ref.Name)
|
||||
}
|
||||
if gt != nil {
|
||||
gt.UnregisterVM(key)
|
||||
}
|
||||
a.wakePoll()
|
||||
a.emitLifecycleStateChanged()
|
||||
return deleteErr
|
||||
})
|
||||
}
|
||||
@@ -442,6 +442,16 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(ctx, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
|
||||
return a.stopVMLegacyLocked(operationCtx, name, force, c)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) stopVMLegacyLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
a.mu.Lock()
|
||||
@@ -449,7 +459,7 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro
|
||||
a.transitions[vmKey(name)] = "stopping"
|
||||
a.mu.Unlock()
|
||||
if mgr != nil {
|
||||
mgr.Registry().Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{
|
||||
mgr.Registry().Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{
|
||||
VMName: name,
|
||||
DriverID: builtin.IDDriverReimsMacOS,
|
||||
})
|
||||
@@ -458,6 +468,7 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro
|
||||
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force))
|
||||
var err error
|
||||
if force {
|
||||
err = c.StopForce(ctx, name, w, w)
|
||||
} else {
|
||||
@@ -489,12 +500,23 @@ func (a *App) RestartVM(name string) error { return a.RestartVMWithDriver("", na
|
||||
|
||||
// restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU
|
||||
// process and its committed memory to go away before starting again.
|
||||
func (a *App) restartMacOSVM(name string) (stopped bool, err error) {
|
||||
func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) {
|
||||
vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
||||
stopped, err = a.restartMacOSVMLocked(operationCtx, name)
|
||||
return err
|
||||
})
|
||||
return stopped, err
|
||||
}
|
||||
|
||||
func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bool, err error) {
|
||||
oldPID := a.cachedVMPID(name)
|
||||
if err := a.StopVMWithDriver(driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
|
||||
if err := a.stopVMWithDriverCtx(ctx, driver.BuiltinReimsMacOSDriverID, name, false); err != nil {
|
||||
return false, err
|
||||
}
|
||||
ctx := a.baseCtx()
|
||||
a.waitForVMProcessExit(ctx, oldPID, vmExitWaitTimeout)
|
||||
if c, err := a.client(); err == nil {
|
||||
a.waitForCommitMemoryReclaim(ctx, c, name, "Restart")
|
||||
@@ -502,7 +524,21 @@ func (a *App) restartMacOSVM(name string) (stopped bool, err error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, a.StartVMWithDriver(driver.BuiltinReimsMacOSDriverID, name)
|
||||
a.mu.Lock()
|
||||
svc := a.lifecycleSvc
|
||||
a.mu.Unlock()
|
||||
if svc == nil {
|
||||
vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name)
|
||||
if resolveErr != nil {
|
||||
return true, resolveErr
|
||||
}
|
||||
return true, a.startResolvedVMLocked(ctx, nil, vm)
|
||||
}
|
||||
_, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, a.startResolvedVMLocked(ctx, svc, vm)
|
||||
}
|
||||
|
||||
func (a *App) ejectInstallerLegacy(name string) error {
|
||||
@@ -510,9 +546,15 @@ func (a *App) ejectInstallerLegacy(name string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, "Ejecting installer from "+name+"...")
|
||||
if err := c.Eject(context.Background(), name, w, w); err != nil {
|
||||
if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
||||
return c.Eject(ctx, name, w, w)
|
||||
}); err != nil {
|
||||
a.emitVMLog(name, "Eject error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
@@ -526,11 +568,21 @@ func (a *App) deleteVMLegacy(name string, keepFiles bool) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
detail, err := c.Show(context.Background(), name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
|
||||
return a.deleteVMLegacyLocked(ctx, name, keepFiles, c)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) deleteVMLegacyLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error {
|
||||
a.cancelRebootWatcher(name)
|
||||
stopVMMonitor(name)
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
|
||||
a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles))
|
||||
if err := c.Delete(context.Background(), name, keepFiles, w, w); err != nil {
|
||||
if err := c.Delete(ctx, name, keepFiles, w, w); err != nil {
|
||||
a.emitVMLog(name, "Delete error: "+err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -44,14 +44,19 @@ func (a *App) SuspendVMWithDriver(driverID, name string) error {
|
||||
|
||||
lastPct := -1
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
res, err := svc.Suspend(ctx, ref, func(p driver.SuspendProgress) {
|
||||
if pct, ok := suspendProgressPercent(p); ok {
|
||||
if pct >= lastPct+25 || p.Status == "completed" {
|
||||
lastPct = pct
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
var res driver.SuspendResult
|
||||
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
||||
var suspendErr error
|
||||
res, suspendErr = svc.Suspend(operationCtx, ref, func(p driver.SuspendProgress) {
|
||||
if pct, ok := suspendProgressPercent(p); ok {
|
||||
if pct >= lastPct+25 || p.Status == "completed" {
|
||||
lastPct = pct
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
|
||||
}
|
||||
}
|
||||
}
|
||||
}, w, w)
|
||||
}, w, w)
|
||||
return suspendErr
|
||||
})
|
||||
if err != nil {
|
||||
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Suspend error: "+err.Error())
|
||||
return err
|
||||
@@ -120,7 +125,12 @@ func (a *App) ResumeVMWithDriver(driverID, name string) error {
|
||||
|
||||
startAt := time.Now()
|
||||
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
|
||||
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
|
||||
var result driver.StartResult
|
||||
err = a.withComputerUseVM(ctx, vm.Directory, func(operationCtx context.Context) error {
|
||||
var resumeErr error
|
||||
result, resumeErr = svc.Resume(operationCtx, ref, extraEnv, w, w)
|
||||
return resumeErr
|
||||
})
|
||||
if err != nil {
|
||||
if newRegistration != nil && newRegGen > 0 {
|
||||
unlock := a.lockGuestToolsVM(ref.Name)
|
||||
|
||||
@@ -184,10 +184,7 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
service, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := a.computerUseInternalService()
|
||||
format, err := service.Screendump(ctx, vm.Dir, raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("capture screen: %w", err)
|
||||
@@ -242,10 +239,7 @@ func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail,
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
service, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
}
|
||||
service := a.computerUseInternalService()
|
||||
format, err := service.Screendump(ctx, vm.Dir, raw)
|
||||
if err != nil {
|
||||
return VMThumbnail{}, false
|
||||
|
||||
@@ -112,10 +112,7 @@ func (a *App) injectTextIntoVMWithLogging(name, knownDir, text string, fromRemot
|
||||
}
|
||||
vmDir = d.Directory
|
||||
}
|
||||
computerUse, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
computerUse := a.computerUseInternalService()
|
||||
|
||||
// Prefer Guest Tools Unicode injection for:
|
||||
// - any non-ASCII (Chinese, CJK punctuation, emoji), OR
|
||||
|
||||
@@ -109,10 +109,17 @@ func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error {
|
||||
// the caller's console and Ctrl+C, with no handles of the caller's: a pipe an
|
||||
// agent reads from must close when this command exits, not when Reims-Go does.
|
||||
func spawnWindow(args []string) error {
|
||||
return spawnWindowWithDataRoot(args, "")
|
||||
}
|
||||
|
||||
func spawnWindowWithDataRoot(args []string, dataRoot string) error {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dataRoot != "" {
|
||||
args = append(args, flagDataRoot+dataRoot)
|
||||
}
|
||||
cmd := exec.Command(exe, args...)
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP}
|
||||
if err := cmd.Start(); err != nil {
|
||||
|
||||
@@ -85,7 +85,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
|
||||
ctx := context.Background()
|
||||
switch args[0] {
|
||||
case "connect":
|
||||
return pluginConnect(args[1:])
|
||||
return pluginConnect(args[1:], cfg.DataRoot)
|
||||
case "search":
|
||||
fs := flag.NewFlagSet("plugin search", flag.ContinueOnError)
|
||||
kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)")
|
||||
|
||||
@@ -4,6 +4,6 @@ package cli
|
||||
|
||||
import "errors"
|
||||
|
||||
func pluginConnect([]string) error {
|
||||
func pluginConnect([]string, string) error {
|
||||
return errors.New("plugin connect is available on Windows desktop builds")
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -18,7 +19,7 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/control"
|
||||
)
|
||||
|
||||
func pluginConnect(args []string) error {
|
||||
func pluginConnect(args []string, dataRoot string) error {
|
||||
if len(args) != 2 || strings.TrimSpace(args[0]) == "" || strings.TrimSpace(args[1]) == "" {
|
||||
return errors.New("usage: reims-go plugin connect <plugin-id> <channel>")
|
||||
}
|
||||
@@ -27,7 +28,7 @@ func pluginConnect(args []string) error {
|
||||
defer cancel()
|
||||
conn, err := control.Dial(ctx)
|
||||
if err != nil {
|
||||
if startErr := spawnWindow([]string{"--background"}); startErr != nil {
|
||||
if startErr := spawnWindowWithDataRoot([]string{"--background"}, dataRoot); startErr != nil {
|
||||
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
|
||||
}
|
||||
conn, err = waitForPluginControl(ctx)
|
||||
@@ -35,31 +36,54 @@ func pluginConnect(args []string) error {
|
||||
return fmt.Errorf("connect to Reims-Go desktop: %w", err)
|
||||
}
|
||||
}
|
||||
return runPluginConnect(ctx, conn, os.Stdin, os.Stdout, os.Stderr, pluginID, channel)
|
||||
}
|
||||
|
||||
func runPluginConnect(ctx context.Context, conn net.Conn, input io.Reader, output, errorOutput io.Writer, pluginID, channel string) error {
|
||||
finished := make(chan struct{})
|
||||
defer close(finished)
|
||||
defer conn.Close()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = conn.Close()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = conn.Close()
|
||||
case <-finished:
|
||||
}
|
||||
}()
|
||||
|
||||
encoder := json.NewEncoder(conn)
|
||||
stdinDone := make(chan error, 1)
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
scanner := bufio.NewScanner(input)
|
||||
scanner.Buffer(make([]byte, 64*1024), control.MaxFrameBytes)
|
||||
for scanner.Scan() {
|
||||
message := append(json.RawMessage(nil), scanner.Bytes()...)
|
||||
if !json.Valid(message) {
|
||||
stdinDone <- errors.New("MCP input line is not valid JSON")
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
if err := encoder.Encode(control.Request{PluginID: pluginID, Channel: channel, Message: message}); err != nil {
|
||||
var rpcRequest struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
}
|
||||
_ = json.Unmarshal(message, &rpcRequest)
|
||||
if err := encoder.Encode(control.Request{PluginID: pluginID, Channel: channel, Message: message, RequestID: rpcRequest.ID}); err != nil {
|
||||
stdinDone <- err
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
stdinDone <- scanner.Err()
|
||||
_ = conn.Close()
|
||||
if err := scanner.Err(); err != nil {
|
||||
stdinDone <- err
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
if err := encoder.Encode(control.Request{CloseInput: true}); err != nil {
|
||||
stdinDone <- err
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
stdinDone <- nil
|
||||
}()
|
||||
|
||||
responseScanner := bufio.NewScanner(conn)
|
||||
@@ -70,41 +94,53 @@ func pluginConnect(args []string) error {
|
||||
return fmt.Errorf("decode host control response: %w", err)
|
||||
}
|
||||
if response.Error != "" {
|
||||
return errors.New(response.Error)
|
||||
}
|
||||
if len(response.Message) > 0 && string(response.Message) != "null" {
|
||||
if _, err := os.Stdout.Write(response.Message); err != nil {
|
||||
if len(response.RequestID) == 0 {
|
||||
if _, err := fmt.Fprintln(errorOutput, "plugin connect: "+response.Error); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
frame, err := json.Marshal(map[string]any{
|
||||
"jsonrpc": "2.0",
|
||||
"id": response.RequestID,
|
||||
"error": map[string]any{
|
||||
"code": -32000,
|
||||
"message": response.Error,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Stdout.Write([]byte{'\n'}); err != nil {
|
||||
if _, err := output.Write(append(frame, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(response.Message) > 0 && string(response.Message) != "null" {
|
||||
if _, err := output.Write(response.Message); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := output.Write([]byte{'\n'}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := responseScanner.Err(); err != nil {
|
||||
// Closing stdin closes the named pipe from the writer goroutine. The
|
||||
// response reader can observe that close just before stdinDone is
|
||||
// scheduled, so give the writer a short chance to report a clean EOF.
|
||||
stdinTimer := time.NewTimer(250 * time.Millisecond)
|
||||
defer stdinTimer.Stop()
|
||||
select {
|
||||
case stdinErr := <-stdinDone:
|
||||
if stdinErr != nil && !errors.Is(stdinErr, context.Canceled) {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return stdinErr
|
||||
}
|
||||
return nil
|
||||
case <-stdinTimer.C:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case stdinErr := <-stdinDone:
|
||||
if stdinErr != nil && ctx.Err() == nil {
|
||||
return stdinErr
|
||||
}
|
||||
default:
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -18,11 +18,14 @@ const (
|
||||
flagStartResult = "--start-result="
|
||||
flagCloseVM = "--close-vm="
|
||||
flagWaitPID = "--wait-pid="
|
||||
flagDataRoot = "--data-root="
|
||||
)
|
||||
|
||||
// WindowArgs is what the desktop window was asked to do at launch, or by a
|
||||
// later `reims-go` run handing work to it.
|
||||
type WindowArgs struct {
|
||||
// DataRoot selects the data folder for a background desktop launch.
|
||||
DataRoot string
|
||||
// Background keeps the window hidden; Reims-Go lives in the tray.
|
||||
Background bool
|
||||
// SafeMode skips all third-party plugins and reverts to the built-in theme (§9).
|
||||
@@ -51,6 +54,11 @@ type WindowArgs struct {
|
||||
func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
|
||||
for _, a := range args {
|
||||
switch {
|
||||
case strings.HasPrefix(a, flagDataRoot):
|
||||
w.DataRoot = strings.TrimPrefix(a, flagDataRoot)
|
||||
if w.DataRoot == "" {
|
||||
return WindowArgs{}, false
|
||||
}
|
||||
case a == flagBackground:
|
||||
w.Background = true
|
||||
case a == flagSafeMode:
|
||||
@@ -87,6 +95,9 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
|
||||
// Args is the inverse of ParseWindowArgs.
|
||||
func (w WindowArgs) Args() []string {
|
||||
var out []string
|
||||
if w.DataRoot != "" {
|
||||
out = append(out, flagDataRoot+w.DataRoot)
|
||||
}
|
||||
if w.Background {
|
||||
out = append(out, flagBackground)
|
||||
}
|
||||
|
||||
+61
-40
@@ -9,11 +9,15 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
"github.com/Nwflower/reims-go/internal/qmp"
|
||||
)
|
||||
|
||||
const vmLifecycleLockFile = ".reims-go-vm-operation.lock"
|
||||
|
||||
// Manager arbitrates screen and input operations so concurrent host features
|
||||
// never open competing QMP clients for the same VM.
|
||||
type Manager struct {
|
||||
@@ -25,7 +29,14 @@ type Manager struct {
|
||||
type vmLock struct {
|
||||
semaphore chan struct{}
|
||||
users int
|
||||
conn qmpSession
|
||||
}
|
||||
|
||||
type lockScopeKey struct{}
|
||||
|
||||
type lockScope struct {
|
||||
manager *Manager
|
||||
key string
|
||||
active atomic.Bool
|
||||
}
|
||||
|
||||
type qmpSession interface {
|
||||
@@ -44,39 +55,21 @@ func NewManager() *Manager {
|
||||
}
|
||||
}
|
||||
|
||||
// Forget closes the cached QMP session for a VM. Lifecycle code calls this
|
||||
// before stopping or deleting the VM so QEMU can release its single-client
|
||||
// console socket.
|
||||
func (m *Manager) Forget(ctx context.Context, vmDir string) error {
|
||||
lock, release, err := m.acquire(ctx, vmDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
if lock.conn != nil {
|
||||
err := lock.conn.Close()
|
||||
lock.conn = nil
|
||||
return err
|
||||
}
|
||||
// WithVM serializes a lifecycle operation with computer-use requests for the
|
||||
// same VM. Nested operations inherit the lock scope through their context.
|
||||
func (m *Manager) WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
|
||||
return m.withVM(ctx, vmDir, operation)
|
||||
}
|
||||
|
||||
// Forget is retained for lifecycle hooks. Each QMP operation closes its
|
||||
// connection before returning, so no session remains to release.
|
||||
func (m *Manager) Forget(_ context.Context, _ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close releases every cached QMP session when the owning plugin is disposed.
|
||||
// Close is retained for the service lifecycle. The manager owns no persistent
|
||||
// QMP connections.
|
||||
func (m *Manager) Close() {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
dirs := make([]string, 0, len(m.locks))
|
||||
for dir := range m.locks {
|
||||
dirs = append(dirs, dir)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
for _, dir := range dirs {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
_ = m.Forget(ctx, dir)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// Screendump writes one PPM frame while holding the VM's console lock.
|
||||
@@ -252,18 +245,25 @@ func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmp
|
||||
if operation == nil {
|
||||
return errors.New("console operation is unavailable")
|
||||
}
|
||||
lock, release, err := m.acquire(ctx, vmDir)
|
||||
key, err := lockKey(vmDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nested := m.hasLockScope(ctx, key)
|
||||
_, release, err := m.acquire(ctx, vmDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
// QEMU's QMP Unix socket only serves one client at a time. Hold the per-VM
|
||||
// semaphore across the operation, then close the socket immediately so
|
||||
// suspend/migrate, blockstats, and external reims-ctl calls are never blocked.
|
||||
if lock.conn != nil {
|
||||
_ = lock.conn.Close()
|
||||
lock.conn = nil
|
||||
if !nested {
|
||||
unlockFile, err := filelock.Acquire(ctx, filepath.Join(vmDir, vmLifecycleLockFile), 25*time.Millisecond)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer unlockFile()
|
||||
}
|
||||
// QEMU serves one QMP client at a time. Keep both locks through this
|
||||
// short-lived connection and close it before releasing them.
|
||||
dial := m.dial
|
||||
if dial == nil {
|
||||
dial = func(ctx context.Context, vmDir string) (qmpSession, error) {
|
||||
@@ -280,16 +280,26 @@ func (m *Manager) withConn(ctx context.Context, vmDir string, operation func(qmp
|
||||
return operation(conn)
|
||||
}
|
||||
|
||||
func (m *Manager) withVM(ctx context.Context, vmDir string, operation func() error) error {
|
||||
func (m *Manager) withVM(ctx context.Context, vmDir string, operation func(context.Context) error) error {
|
||||
if operation == nil {
|
||||
return errors.New("console operation is unavailable")
|
||||
}
|
||||
key, err := lockKey(vmDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.hasLockScope(ctx, key) {
|
||||
return operation(ctx)
|
||||
}
|
||||
_, release, err := m.acquire(ctx, vmDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer release()
|
||||
return operation()
|
||||
scope := &lockScope{manager: m, key: key}
|
||||
scope.active.Store(true)
|
||||
defer scope.active.Store(false)
|
||||
return operation(context.WithValue(ctx, lockScopeKey{}, scope))
|
||||
}
|
||||
|
||||
func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), error) {
|
||||
@@ -303,6 +313,9 @@ func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), e
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if m.hasLockScope(ctx, key) {
|
||||
return &vmLock{}, func() {}, nil
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
if m.locks == nil {
|
||||
@@ -331,11 +344,19 @@ func (m *Manager) acquire(ctx context.Context, vmDir string) (*vmLock, func(), e
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) hasLockScope(ctx context.Context, key string) bool {
|
||||
if ctx == nil {
|
||||
return false
|
||||
}
|
||||
scope, ok := ctx.Value(lockScopeKey{}).(*lockScope)
|
||||
return ok && scope.manager == m && scope.key == key && scope.active.Load()
|
||||
}
|
||||
|
||||
func (m *Manager) release(key string, lock *vmLock) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
lock.users--
|
||||
if lock.users == 0 && lock.conn == nil && m.locks[key] == lock {
|
||||
if lock.users == 0 && m.locks[key] == lock {
|
||||
delete(m.locks, key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,14 @@ package console
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
)
|
||||
|
||||
type fakeQMPSession struct {
|
||||
@@ -101,3 +105,57 @@ func TestManagerSerializesSameVMOperations(t *testing.T) {
|
||||
t.Fatalf("expected max 1 concurrent QMP operation per VM, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerQMPOperationHoldsLifecycleFileLock(t *testing.T) {
|
||||
m := NewManager()
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
m.dial = func(context.Context, string) (qmpSession, error) {
|
||||
return &fakeQMPSession{onExec: func(string) {
|
||||
close(entered)
|
||||
<-release
|
||||
}}, nil
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := m.Screendump(context.Background(), dir, "frame.ppm")
|
||||
done <- err
|
||||
}()
|
||||
<-entered
|
||||
|
||||
lockFile, err := os.OpenFile(filepath.Join(dir, vmLifecycleLockFile), os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
close(release)
|
||||
t.Fatal(err)
|
||||
}
|
||||
locked, err := filelock.TryLock(lockFile)
|
||||
if err != nil {
|
||||
close(release)
|
||||
lockFile.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if locked {
|
||||
filelock.Unlock(lockFile)
|
||||
close(release)
|
||||
lockFile.Close()
|
||||
t.Fatal("QMP operation did not hold the VM lifecycle file lock")
|
||||
}
|
||||
close(release)
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Screendump: %v", err)
|
||||
}
|
||||
lockFile.Close()
|
||||
|
||||
lockFile, err = os.OpenFile(filepath.Join(dir, vmLifecycleLockFile), os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lockFile.Close()
|
||||
locked, err = filelock.TryLock(lockFile)
|
||||
if err != nil || !locked {
|
||||
t.Fatalf("QMP operation did not release the VM lifecycle lock: locked=%v err=%v", locked, err)
|
||||
}
|
||||
filelock.Unlock(lockFile)
|
||||
}
|
||||
@@ -14,14 +14,17 @@ import (
|
||||
const MaxFrameBytes = 8 << 20
|
||||
|
||||
type Request struct {
|
||||
PluginID string `json:"plugin_id"`
|
||||
Channel string `json:"channel"`
|
||||
Message json.RawMessage `json:"message"`
|
||||
PluginID string `json:"plugin_id,omitempty"`
|
||||
Channel string `json:"channel,omitempty"`
|
||||
Message json.RawMessage `json:"message,omitempty"`
|
||||
RequestID json.RawMessage `json:"request_id,omitempty"`
|
||||
CloseInput bool `json:"close_input,omitempty"`
|
||||
}
|
||||
|
||||
type Response struct {
|
||||
Message json.RawMessage `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
RequestID json.RawMessage `json:"request_id,omitempty"`
|
||||
Message json.RawMessage `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Handler func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error)
|
||||
|
||||
@@ -99,37 +99,63 @@ func (s *Server) serveConn(serverCtx context.Context, conn net.Conn) {
|
||||
_ = conn.Close()
|
||||
}()
|
||||
|
||||
connCtx, cancel := context.WithCancel(serverCtx)
|
||||
defer cancel()
|
||||
var handlers sync.WaitGroup
|
||||
var writeMu sync.Mutex
|
||||
writer := bufio.NewWriter(conn)
|
||||
write := func(response Response) error {
|
||||
writeMu.Lock()
|
||||
defer writeMu.Unlock()
|
||||
return writeResponse(writer, response)
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(conn)
|
||||
scanner.Buffer(make([]byte, 64*1024), MaxFrameBytes)
|
||||
writer := bufio.NewWriter(conn)
|
||||
inputClosed := false
|
||||
for scanner.Scan() {
|
||||
var req Request
|
||||
if err := json.Unmarshal(scanner.Bytes(), &req); err != nil {
|
||||
if writeErr := writeResponse(writer, Response{Error: "invalid control request"}); writeErr != nil {
|
||||
return
|
||||
if writeErr := write(Response{Error: "invalid control request"}); writeErr != nil {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
if req.CloseInput {
|
||||
if req.PluginID != "" || req.Channel != "" || len(req.Message) != 0 {
|
||||
if err := write(Response{RequestID: req.RequestID, Error: "close-input control request must not include a plugin message"}); err != nil {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
inputClosed = true
|
||||
break
|
||||
}
|
||||
if req.PluginID == "" || req.Channel == "" || len(req.Message) == 0 || !json.Valid(req.Message) {
|
||||
if err := writeResponse(writer, Response{Error: "plugin, channel and valid JSON message are required"}); err != nil {
|
||||
return
|
||||
if err := write(Response{RequestID: req.RequestID, Error: "plugin, channel and valid JSON message are required"}); err != nil {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
result, err := s.handler(serverCtx, req.PluginID, req.Channel, req.Message)
|
||||
response := Response{Message: result}
|
||||
if err != nil {
|
||||
response = Response{Error: err.Error()}
|
||||
}
|
||||
if err := writeResponse(writer, response); err != nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-serverCtx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
handlers.Add(1)
|
||||
go func(req Request) {
|
||||
defer handlers.Done()
|
||||
result, err := s.handler(connCtx, req.PluginID, req.Channel, req.Message)
|
||||
response := Response{RequestID: req.RequestID, Message: result}
|
||||
if err != nil {
|
||||
response = Response{RequestID: req.RequestID, Error: err.Error()}
|
||||
}
|
||||
if err := write(response); err != nil {
|
||||
cancel()
|
||||
}
|
||||
}(req)
|
||||
}
|
||||
if !inputClosed {
|
||||
// EOF or a read failure without an explicit drain frame means the
|
||||
// client abandoned the session. Cancel its outstanding channel calls.
|
||||
cancel()
|
||||
}
|
||||
handlers.Wait()
|
||||
}
|
||||
|
||||
func writeResponse(writer *bufio.Writer, response Response) error {
|
||||
|
||||
@@ -60,6 +60,12 @@ type CloneDriver interface {
|
||||
CloneCoW(context.Context, string, string, io.Writer, io.Writer) error
|
||||
}
|
||||
|
||||
// CloneResultDriver returns the VM metadata produced by a clone so callers can
|
||||
// persist ownership before reporting success, even when inventories lag.
|
||||
type CloneResultDriver interface {
|
||||
CloneCoWWithInfo(context.Context, string, string, io.Writer, io.Writer) (VMInfo, error)
|
||||
}
|
||||
|
||||
// DiskDriver exposes online-safe orchestration around driver-owned disk images.
|
||||
type DiskDriver interface {
|
||||
ResizeDisk(context.Context, string, string, io.Writer, io.Writer) (DiskResizeResult, error)
|
||||
|
||||
@@ -135,6 +135,16 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.clone.same_name": "新虚拟机名称不能与原虚拟机相同",
|
||||
"err.clone.source_running": "请先关闭「{name}」再派生副本,以保证母盘数据一致",
|
||||
"err.commit_memory": "内存不够启动:这台虚拟机需要 {need, number, .0} GB(客体内存 {mem, number, .0} GB 加运行开销),Windows 现在最多还能分配 {avail, number, .1} GB(已算上页面文件可自动扩展的部分)。关掉一些程序再试,或在设置里把内存改为 {rec, number, .0} GB",
|
||||
"err.computer_use.access_disabled": "MCP 插件在设置中无权访问虚拟机 {name}",
|
||||
"err.computer_use.disabled": "虚拟机交互服务已停用,请在插件页启用后重试",
|
||||
"err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆",
|
||||
"err.computer_use.phase.installer": "安装器",
|
||||
"err.computer_use.phase.recovery": "恢复模式",
|
||||
"err.computer_use.phase_confirmation": "虚拟机 {name} 处于 {phase} 阶段,操作需要先在 Reims-Go 中确认",
|
||||
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
|
||||
"err.computer_use.unavailable": "虚拟机交互服务当前不可用",
|
||||
"err.computer_use.unsupported_driver": "当前虚拟机驱动不支持虚拟机交互",
|
||||
"err.computer_use.vm_not_running": "虚拟机 {name} 未运行",
|
||||
"err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录",
|
||||
"err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录",
|
||||
"err.dataroot.damaged": "数据目录 {dir} 的数据版本记录已损坏,已以只读方式打开,没有做任何修改。确认目录来自当前或更早的版本后,可在界面中修复版本记录",
|
||||
@@ -795,6 +805,16 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.clone.same_name": "Choose a different name from the source VM",
|
||||
"err.clone.source_running": "Stop “{name}” before deriving a CoW clone so the backing disk is clean",
|
||||
"err.commit_memory": "Not enough memory to start: this VM needs {need, number, .0} GB ({mem, number, .0} GB guest memory plus overhead) and Windows can commit at most {avail, number, .1} GB more, counting how far the page file can grow. Close some programs, or set its memory to {rec, number, .0} GB",
|
||||
"err.computer_use.access_disabled": "MCP access to VM {name} is disabled in plugin settings",
|
||||
"err.computer_use.disabled": "Virtual machine interaction is disabled. Enable it on the Plugins page and try again",
|
||||
"err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone",
|
||||
"err.computer_use.phase.installer": "installer",
|
||||
"err.computer_use.phase.recovery": "Recovery mode",
|
||||
"err.computer_use.phase_confirmation": "VM {name} is in the {phase} phase and requires confirmation in Reims-Go",
|
||||
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
|
||||
"err.computer_use.unavailable": "The virtual machine interaction service is currently unavailable",
|
||||
"err.computer_use.unsupported_driver": "The selected VM driver does not support computer use",
|
||||
"err.computer_use.vm_not_running": "VM {name} is not running",
|
||||
"err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder",
|
||||
"err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder",
|
||||
"err.dataroot.damaged": "The data version record in {dir} is damaged. The folder was opened read-only and nothing was changed. If it comes from this or an older version, you can repair the record in the app",
|
||||
@@ -1370,6 +1390,10 @@ var paramOrder = map[string][]string{
|
||||
"err.clone.overlay_exists": {"path"},
|
||||
"err.clone.source_running": {"name"},
|
||||
"err.commit_memory": {"need", "mem", "avail", "rec"},
|
||||
"err.computer_use.access_disabled": {"name"},
|
||||
"err.computer_use.not_owned": {"name"},
|
||||
"err.computer_use.phase_confirmation": {"name", "phase"},
|
||||
"err.computer_use.restore_confirmation": {"name"},
|
||||
"err.dataroot.damaged": {"dir"},
|
||||
"err.dataroot.locked": {"dir"},
|
||||
"err.dataroot.migration_failed": {"dir"},
|
||||
|
||||
@@ -154,7 +154,7 @@ func (s *Service) Stop(ctx context.Context, ref driver.VMRef, force bool, stdout
|
||||
return err
|
||||
}
|
||||
if s.reg != nil {
|
||||
s.reg.Hooks().DispatchObserve(plugin.EventVMBeforeStop, plugin.VMEventPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID()})
|
||||
s.reg.Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{VMName: vm.Name, VMDir: vm.Directory, DriverID: d.ID()})
|
||||
}
|
||||
if err := d.Stop(ctx, ref.Name, force, stdout, stderr); err != nil {
|
||||
return err
|
||||
@@ -177,7 +177,7 @@ func (s *Service) Suspend(ctx context.Context, ref driver.VMRef, progress func(d
|
||||
ref = vm.Ref()
|
||||
ev := plugin.VMEventPayload{VMName: ref.Name, VMDir: vm.Directory, DriverID: ref.DriverID}
|
||||
if s.reg != nil {
|
||||
s.reg.Hooks().DispatchObserve(plugin.EventVMBeforeStop, ev)
|
||||
s.reg.Hooks().DispatchBeforeStop(ctx, ev)
|
||||
}
|
||||
res, err := sd.Suspend(ctx, driver.SuspendRequest{Ref: ref, Progress: progress, Stdout: stdout, Stderr: stderr})
|
||||
if err != nil {
|
||||
|
||||
@@ -44,6 +44,28 @@ func (s *Service) CloneCoW(ctx context.Context, ref driver.VMRef, cloneName stri
|
||||
return clones.CloneCoW(ctx, vm.Name, cloneName, stdout, stderr)
|
||||
}
|
||||
|
||||
func (s *Service) CloneCoWWithInfo(ctx context.Context, ref driver.VMRef, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) {
|
||||
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
if _, ok := d.(driver.CloneDriver); !ok {
|
||||
return driver.VMInfo{}, fmt.Errorf("driver %q does not support CoW clones", d.ID())
|
||||
}
|
||||
var cloned driver.VMInfo
|
||||
if resultDriver, ok := d.(driver.CloneResultDriver); ok {
|
||||
cloned, err = resultDriver.CloneCoWWithInfo(ctx, vm.Name, cloneName, stdout, stderr)
|
||||
} else {
|
||||
err = s.CloneCoW(ctx, vm.Ref(), cloneName, stdout, stderr)
|
||||
cloned = driver.VMInfo{Name: cloneName, DriverID: d.ID()}
|
||||
}
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
cloned.DriverID = d.ID()
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (s *Service) ResizeDisk(ctx context.Context, ref driver.VMRef, newSize string, stdout, stderr io.Writer) (driver.DiskResizeResult, error) {
|
||||
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,11 +2,13 @@ package macosdriver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
)
|
||||
|
||||
var _ driver.CloneDriver = (*ReimsMacOSDriver)(nil)
|
||||
var _ driver.CloneResultDriver = (*ReimsMacOSDriver)(nil)
|
||||
|
||||
func readVMMacOS(dir string) string {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, ".reims-go-macos"))
|
||||
@@ -35,7 +38,28 @@ func writeVMMacOS(dir, release string) error {
|
||||
return os.WriteFile(filepath.Join(dir, ".reims-go-macos"), []byte(release+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) error {
|
||||
func (d *ReimsMacOSDriver) CloneCoWWithInfo(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) {
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if err := d.CloneCoW(ctx, sourceName, cloneName, stdout, stderr); err != nil {
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
cloned, err := d.Show(ctx, cloneName)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, d.cleanupFailedClone(ctx, cloneName, err, stdout, stderr)
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) cleanupFailedClone(ctx context.Context, cloneName string, cause error, stdout, stderr io.Writer) error {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
if cleanupErr := d.Delete(cleanupCtx, cloneName, false, stdout, stderr); cleanupErr != nil {
|
||||
return errors.Join(cause, fmt.Errorf("clean up incomplete clone %q: %w", cloneName, cleanupErr))
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (resultErr error) {
|
||||
c, active, err := d.startClient()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -80,7 +104,13 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer releaseDisks()
|
||||
cloneRegistered := false
|
||||
defer func() {
|
||||
releaseDisks()
|
||||
if resultErr != nil && cloneRegistered {
|
||||
resultErr = d.cleanupFailedClone(ctx, cloneName, resultErr, stdout, stderr)
|
||||
}
|
||||
}()
|
||||
if err := c.CheckCoWCloneSource(ctx, sourceName, srcDisk, cloneName); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -103,6 +133,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
cloneRegistered = true
|
||||
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
|
||||
if err := c.Set(ctx, postSet, stdout, stderr); err != nil {
|
||||
_, _ = fmt.Fprintf(stdout, "Warning: could not apply clone settings: %v\n", err)
|
||||
|
||||
@@ -142,6 +142,8 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo
|
||||
return driver.VMInfo{}, err
|
||||
}
|
||||
enrichSuspendDetail(&det)
|
||||
marker := startprep.ReadRecoveryMarker(det.Directory)
|
||||
det.RecoveryMode = marker == "on" || marker == "want"
|
||||
rawBytes, _ := json.Marshal(det)
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal(rawBytes, &data)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
// ComputerUseService is the host-owned console surface exposed to in-process
|
||||
// features and permission-checked Sidecar Host API handlers.
|
||||
type ComputerUseService interface {
|
||||
WithVM(ctx context.Context, vmDir string, operation func(context.Context) error) error
|
||||
Screendump(ctx context.Context, vmDir, path string) (string, error)
|
||||
TypeText(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error)
|
||||
Forget(ctx context.Context, vmDir string) error
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
// Lifecycle hook event names (§4.3).
|
||||
const (
|
||||
EventHostPreflight = "host.preflight"
|
||||
EventHostPreflight = "host.preflight"
|
||||
EventVMBeforeCreate = "vm.beforeCreate"
|
||||
EventVMAfterCreate = "vm.afterCreate"
|
||||
EventVMBeforeStart = "vm.beforeStart"
|
||||
@@ -341,8 +341,23 @@ func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPa
|
||||
return intents, nil
|
||||
}
|
||||
|
||||
// DispatchBeforeStop waits for built-in cleanup hooks before a VM stops. External
|
||||
// observation hooks remain asynchronous so they cannot delay VM shutdown.
|
||||
func (b *HookBus) DispatchBeforeStop(ctx context.Context, payload VMEventPayload) {
|
||||
subs := b.snapshot(EventVMBeforeStop)
|
||||
for _, hr := range subs {
|
||||
if hr.Builtin {
|
||||
_, _ = b.invokeBuiltin(ctx, hr, payload)
|
||||
continue
|
||||
}
|
||||
go func(hr *HookRegistration) {
|
||||
_, _ = b.invokeWithTimeout(context.Background(), hr, payload, 10*time.Second)
|
||||
}(hr)
|
||||
}
|
||||
}
|
||||
|
||||
// DispatchObserve asynchronously fires observation events (vm.afterCreate,
|
||||
// vm.afterStart, vm.beforeStop, vm.afterStop, vm.deleted), logging errors only.
|
||||
// vm.afterStart, vm.afterStop, vm.deleted), logging errors only.
|
||||
func (b *HookBus) DispatchObserve(event string, payload VMEventPayload) {
|
||||
subs := b.snapshot(event)
|
||||
if len(subs) == 0 {
|
||||
|
||||
+54
-19
@@ -506,8 +506,8 @@ func (m *Manager) buildSidecarActivator(man Manifest, exePath string, blockingAl
|
||||
if d.Priority == 0 {
|
||||
d.Priority = 100 // external L3 downloaders override builtin (50) by default
|
||||
}
|
||||
m.registry.RegisterDownloader(sc, d, newSidecarDownloader(d, sup, dlHub, func() map[string]any {
|
||||
return m.GetSettings(pid, "", false)
|
||||
m.registry.RegisterDownloader(sc, d, newSidecarDownloader(d, sup, dlHub, func() (map[string]any, error) {
|
||||
return m.DownloaderSettings(pid)
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -949,6 +949,54 @@ func (m *Manager) GetSettings(pluginID, vmName string, maskSecrets bool) map[str
|
||||
return out
|
||||
}
|
||||
|
||||
// DownloaderSettings returns a plugin's app settings to its own downloader
|
||||
// sidecar, decrypting x-secret values only for that download request.
|
||||
func (m *Manager) DownloaderSettings(pluginID string) (map[string]any, error) {
|
||||
info, ok := m.registry.Info(pluginID)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("plugin %q is unavailable", pluginID)
|
||||
}
|
||||
settings := m.GetSettings(pluginID, "", false)
|
||||
if info.Settings == nil {
|
||||
return settings, nil
|
||||
}
|
||||
for key, property := range info.Settings.Properties {
|
||||
if !property.Secret {
|
||||
continue
|
||||
}
|
||||
text, ok := settings[key].(string)
|
||||
if !ok || !strings.HasPrefix(text, protectedSecretPrefix) {
|
||||
continue
|
||||
}
|
||||
plain, err := unprotectSettingSecret(text)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decrypt downloader setting %q: %w", key, err)
|
||||
}
|
||||
settings[key] = plain
|
||||
}
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
// SavedBoolSetting reads an explicitly stored boolean without applying schema
|
||||
// defaults. Security decisions must not be authorized by plugin metadata.
|
||||
func (m *Manager) SavedBoolSetting(pluginID, vmName, key string) bool {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if m.state == nil {
|
||||
return false
|
||||
}
|
||||
record := m.state.Plugins[pluginID]
|
||||
if record == nil {
|
||||
return false
|
||||
}
|
||||
values := record.AppSettings
|
||||
if vmName != "" {
|
||||
values = record.VMSettings[vmName]
|
||||
}
|
||||
enabled, _ := values[key].(bool)
|
||||
return enabled
|
||||
}
|
||||
|
||||
func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) error {
|
||||
info, hasInfo := m.registry.Info(pluginID)
|
||||
prepared := make(map[string]any, len(values))
|
||||
@@ -962,6 +1010,10 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
||||
if !ok {
|
||||
return fmt.Errorf("secret setting %q must be a string", key)
|
||||
}
|
||||
if text == "" {
|
||||
prepared[key] = ""
|
||||
continue
|
||||
}
|
||||
protected, err := protectSettingSecret(text)
|
||||
if err != nil {
|
||||
return fmt.Errorf("protect secret setting %q: %w", key, err)
|
||||
@@ -987,25 +1039,11 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
||||
}
|
||||
m.state.Plugins[pluginID] = rec
|
||||
}
|
||||
isSecretMask := func(k string, v any) bool {
|
||||
if info.Settings == nil {
|
||||
return false
|
||||
}
|
||||
prop, ok := info.Settings.Properties[k]
|
||||
if !ok || !prop.Secret {
|
||||
return false
|
||||
}
|
||||
s, ok := v.(string)
|
||||
return ok && s == "••••••••"
|
||||
}
|
||||
if vmName == "" {
|
||||
if rec.AppSettings == nil {
|
||||
rec.AppSettings = map[string]any{}
|
||||
}
|
||||
for k, v := range prepared {
|
||||
if isSecretMask(k, v) {
|
||||
continue
|
||||
}
|
||||
rec.AppSettings[k] = v
|
||||
}
|
||||
} else {
|
||||
@@ -1016,9 +1054,6 @@ func (m *Manager) SetSettings(pluginID, vmName string, values map[string]any) er
|
||||
rec.VMSettings[vmName] = map[string]any{}
|
||||
}
|
||||
for k, v := range prepared {
|
||||
if isSecretMask(k, v) {
|
||||
continue
|
||||
}
|
||||
rec.VMSettings[vmName][k] = v
|
||||
}
|
||||
}
|
||||
|
||||
+15
-11
@@ -24,7 +24,7 @@ type SidecarOptions struct {
|
||||
Registry *Registry
|
||||
IdleTimeout time.Duration // 0 = no idle shutdown
|
||||
MemLimitBytes uintptr // optional Windows Job Object memory cap (L2)
|
||||
MaxRestarts int // circuit breaker threshold (default 3)
|
||||
MaxRestarts int // circuit breaker threshold (default 3)
|
||||
ExtraHandlers map[string]RPCRequestHandler
|
||||
LocaleProvider func() (string, []string, map[string]string) // returns (locale, fallbackChain, mergedBundle)
|
||||
}
|
||||
@@ -45,15 +45,15 @@ type sidecarInstance struct {
|
||||
type SidecarSupervisor struct {
|
||||
opts SidecarOptions
|
||||
|
||||
startMu sync.Mutex
|
||||
mu sync.Mutex
|
||||
cur *sidecarInstance
|
||||
stopped bool
|
||||
crashCount int
|
||||
lastCrash time.Time
|
||||
lastActivity time.Time
|
||||
idleCancel context.CancelFunc
|
||||
capabilities map[string]any
|
||||
startMu sync.Mutex
|
||||
mu sync.Mutex
|
||||
cur *sidecarInstance
|
||||
stopped bool
|
||||
crashCount int
|
||||
lastCrash time.Time
|
||||
lastActivity time.Time
|
||||
idleCancel context.CancelFunc
|
||||
capabilities map[string]any
|
||||
}
|
||||
|
||||
func NewSidecarSupervisor(opts SidecarOptions) *SidecarSupervisor {
|
||||
@@ -209,7 +209,9 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
|
||||
// Collect stderr into rotated plugin audit log using bufio.Reader so lines
|
||||
// >64 KiB are truncated and drained instead of wedging the pipe.
|
||||
stderrDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stderrDone)
|
||||
const maxLineBytes = 8 * 1024
|
||||
br := bufio.NewReaderSize(stderr, 16*1024)
|
||||
var buf []byte
|
||||
@@ -246,8 +248,10 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance
|
||||
}
|
||||
}()
|
||||
|
||||
// Reap via process handle (cmd.Wait), NOT pipe EOF (§8).
|
||||
// StdoutPipe and StderrPipe must be drained before Wait closes their handles.
|
||||
go func() {
|
||||
<-rpcConn.doneCh
|
||||
<-stderrDone
|
||||
err := cmd.Wait()
|
||||
rpcConn.Close()
|
||||
job.Close()
|
||||
|
||||
@@ -67,10 +67,10 @@ type sidecarDownloader struct {
|
||||
contrib DownloaderContribution
|
||||
sup *SidecarSupervisor
|
||||
hub *downloaderProgressHub
|
||||
settingsFn func() map[string]any
|
||||
settingsFn func() (map[string]any, error)
|
||||
}
|
||||
|
||||
func newSidecarDownloader(contrib DownloaderContribution, sup *SidecarSupervisor, hub *downloaderProgressHub, settingsFn func() map[string]any) downloader.Provider {
|
||||
func newSidecarDownloader(contrib DownloaderContribution, sup *SidecarSupervisor, hub *downloaderProgressHub, settingsFn func() (map[string]any, error)) downloader.Provider {
|
||||
return &sidecarDownloader{contrib: contrib, sup: sup, hub: hub, settingsFn: settingsFn}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,11 @@ func (s *sidecarDownloader) Download(ctx context.Context, req downloader.Request
|
||||
|
||||
var settings map[string]any
|
||||
if s.settingsFn != nil {
|
||||
settings = s.settingsFn()
|
||||
var err error
|
||||
settings, err = s.settingsFn()
|
||||
if err != nil {
|
||||
return fmt.Errorf("load downloader settings: %w", err)
|
||||
}
|
||||
}
|
||||
var resp struct {
|
||||
OK bool `json:"ok"`
|
||||
|
||||
@@ -300,6 +300,16 @@
|
||||
"err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install <archive>` first",
|
||||
"err.macos.disabled": "macOS VM Support is disabled; enable it on the Plugins page first",
|
||||
"err.vm_not_running": "VM {name} is not running",
|
||||
"err.computer_use.disabled": "Virtual machine interaction is disabled. Enable it on the Plugins page and try again",
|
||||
"err.computer_use.unavailable": "The virtual machine interaction service is currently unavailable",
|
||||
"err.computer_use.unsupported_driver": "The selected VM driver does not support computer use",
|
||||
"err.computer_use.vm_not_running": "VM {name} is not running",
|
||||
"err.computer_use.phase_confirmation": "VM {name} is in the {phase} phase and requires confirmation in Reims-Go",
|
||||
"err.computer_use.phase.installer": "installer",
|
||||
"err.computer_use.phase.recovery": "Recovery mode",
|
||||
"err.computer_use.access_disabled": "MCP access to VM {name} is disabled in plugin settings",
|
||||
"err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone",
|
||||
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
|
||||
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
|
||||
"err.vm_window_not_found": "Couldn’t find the display window for {name}",
|
||||
"err.fullscreen_failed": "Couldn’t toggle full screen for {name}",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"pluginSettings": "Plugin settings",
|
||||
"pluginGlobalSettings": "Plugin settings",
|
||||
"pluginClearSecret": "Clear",
|
||||
"pluginFailLoad": "Couldn’t load plugins",
|
||||
"pluginFailToggle": "Couldn’t toggle plugin",
|
||||
"pluginFailEnable": "Couldn’t enable plugin",
|
||||
|
||||
@@ -300,6 +300,16 @@
|
||||
"err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`",
|
||||
"err.macos.disabled": "「macOS 虚拟机支持」插件已停用,请先在插件页启用",
|
||||
"err.vm_not_running": "虚拟机 {name} 未运行",
|
||||
"err.computer_use.disabled": "虚拟机交互服务已停用,请在插件页启用后重试",
|
||||
"err.computer_use.unavailable": "虚拟机交互服务当前不可用",
|
||||
"err.computer_use.unsupported_driver": "当前虚拟机驱动不支持虚拟机交互",
|
||||
"err.computer_use.vm_not_running": "虚拟机 {name} 未运行",
|
||||
"err.computer_use.phase_confirmation": "虚拟机 {name} 处于 {phase} 阶段,操作需要先在 Reims-Go 中确认",
|
||||
"err.computer_use.phase.installer": "安装器",
|
||||
"err.computer_use.phase.recovery": "恢复模式",
|
||||
"err.computer_use.access_disabled": "MCP 插件在设置中无权访问虚拟机 {name}",
|
||||
"err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆",
|
||||
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
|
||||
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
|
||||
"err.vm_window_not_found": "找不到 {name} 的显示窗口",
|
||||
"err.fullscreen_failed": "无法切换 {name} 的全屏状态",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"pluginSettings": "插件设置",
|
||||
"pluginGlobalSettings": "插件全局设置",
|
||||
"pluginClearSecret": "清除",
|
||||
"pluginFailLoad": "加载插件列表失败",
|
||||
"pluginFailToggle": "切换插件状态失败",
|
||||
"pluginFailEnable": "启用插件失败",
|
||||
|
||||
Reference in new issue
Block a user