From bd4e85af1a48ddf09750ef780a85cd0d8678b2bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Fri, 4 Dec 2026 23:49:43 -0700 Subject: [PATCH] feat(plugin): scope MCP connections and add held input, region capture and force stop - Each plugin connect connection gets a session id that is forwarded with channel//message; when the connection ends the host notifies the sidecar with channel//closed so it can cancel calls and release input. - host/console.screenshot crops a region from the full-resolution frame, optionally measured in a reference image size, and full frames now honor max_width up to 2560. - host/console.key can hold or release one key, and host/console.release lifts keys and pointer buttons in one call. Driver consoles stay press-only. - host/vm.shutdown accepts force, and host/vm.snapshot.list needs only vm:read. Co-Authored-By: Claude Opus 5.5 --- changes/mcp-host-session-input.json | 7 + docs/plugin-architecture.md | 4 +- internal/app/computer_use_host.go | 160 +++++++++++++++++++---- internal/app/computer_use_region_test.go | 72 ++++++++++ internal/app/console_router.go | 65 +++++++++ internal/app/plugin_connect.go | 22 +++- internal/console/held_key_test.go | 24 ++++ internal/console/manager.go | 9 ++ internal/control/control.go | 37 ++++++ internal/control/control_other.go | 6 +- internal/control/control_windows.go | 26 +++- internal/control/session_windows_test.go | 90 +++++++++++++ internal/plugin/manager.go | 22 +++- 13 files changed, 499 insertions(+), 45 deletions(-) create mode 100644 changes/mcp-host-session-input.json create mode 100644 internal/app/computer_use_region_test.go create mode 100644 internal/console/held_key_test.go create mode 100644 internal/control/session_windows_test.go diff --git a/changes/mcp-host-session-input.json b/changes/mcp-host-session-input.json new file mode 100644 index 0000000..1fed521 --- /dev/null +++ b/changes/mcp-host-session-input.json @@ -0,0 +1,7 @@ +{ + "group": "improvements", + "order": 0, + "authors": ["Nwflower"], + "zh": "MCP 插件接口按连接区分会话,客户端断开后会通知插件释放仍按住的输入;截图支持按源分辨率裁剪局部区域,按键支持单独按住和松开,关机支持强制停止,读取恢复点列表只需读取权限。", + "en": "The MCP plugin interface now scopes each client connection as its own session and notifies the plugin when a client disconnects so held input is released. Screenshots can crop a region at source resolution, keys can be held and released individually, shutdown can force-stop, and listing restore points needs only read permission." +} diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index c6c5889..583219f 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -35,9 +35,9 @@ flowchart TB 内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。 -L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。 +L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。每条连接带一个会话标识,宿主随 `channel/<通道>/message` 一并转发,插件按会话区分请求 ID 和取消。连接结束后,宿主向正在运行的 Sidecar 发送 `channel/<通道>/closed` 通知,插件据此取消该连接的调用并释放按住的输入。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。 -Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。 +Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率。宿主在全分辨率帧上裁剪区域后再缩放。按键可单独按住和松开,释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。 ## 生命周期、参数账本与资源预算 diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go index f10c02f..bf89967 100644 --- a/internal/app/computer_use_host.go +++ b/internal/app/computer_use_host.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "image" "os" "path/filepath" "slices" @@ -20,6 +21,7 @@ import ( ) const computerUsePreviewWidth = 1280 +const computerUseMaxImageWidth = 2560 const computerUseMaxTextRunes = 4000 const computerUseSecretPluginID = "reims.agent" @@ -55,13 +57,14 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[ "host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)), "host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone), "host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete), - "host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList), + "host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList), "host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate), "host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore), "host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot), "host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer), "host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey), "host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType), + "host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease), } // The plugin ID is supplied by the manager while wiring the sidecar, never // by the channel payload. Keep the handler registered for a stable method @@ -209,7 +212,8 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { var req struct { - VM string `json:"vm"` + VM string `json:"vm"` + Force bool `json:"force"` } if err := json.Unmarshal(raw, &req); err != nil { return nil, err @@ -218,7 +222,7 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage if err != nil { return nil, err } - if err := a.StopVM(vm.DriverID, vm.Name, false); err != nil { + if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil { return nil, err } return map[string]any{"ok": true}, nil @@ -783,18 +787,80 @@ func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) { return a.resolveVMInfo("", ref) } +// computerUseRegion is a rectangle in source-frame pixels. +type computerUseRegion struct { + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` +} + +// computerUseRegionFrame cuts region from a full-resolution frame, clipped to +// the screen, and shrinks the cut to at most maxWidth pixels wide. It returns +// the region that was actually used. +func computerUseRegionFrame(full image.Image, region computerUseRegion, maxWidth int) (image.Image, computerUseRegion, error) { + area := image.Rect(region.X, region.Y, region.X+region.Width, region.Y+region.Height).Intersect(full.Bounds()) + if area.Empty() { + return nil, computerUseRegion{}, errors.New("region does not intersect the screen") + } + sub, ok := full.(interface { + SubImage(image.Rectangle) image.Image + }) + if !ok { + return nil, computerUseRegion{}, errors.New("screen frame cannot be cropped") + } + applied := computerUseRegion{X: area.Min.X, Y: area.Min.Y, Width: area.Dx(), Height: area.Dy()} + return thumb.Scale(sub.SubImage(area), maxWidth), applied, nil +} + +// computerUseRegionToSource maps a region given in a refW x refH image of the +// screen onto the source frame, widening it outward so no selected pixel is +// lost to rounding. +func computerUseRegionToSource(region computerUseRegion, refW, refH int, source image.Point) computerUseRegion { + if refW <= 0 || refH <= 0 { + return region + } + x0 := region.X * source.X / refW + y0 := region.Y * source.Y / refH + x1 := ((region.X+region.Width)*source.X + refW - 1) / refW + y1 := ((region.Y+region.Height)*source.Y + refH - 1) / refH + return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0} +} + func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { var req struct { - VM string `json:"vm"` + VM string `json:"vm"` + Region *computerUseRegion `json:"region"` + MaxWidth int `json:"max_width"` + // Width and Height name the image the region was measured in; without + // them the region is in source pixels. + Width int `json:"width"` + Height int `json:"height"` } if err := json.Unmarshal(raw, &req); err != nil { return nil, err } + maxWidth := req.MaxWidth + if maxWidth == 0 { + maxWidth = computerUsePreviewWidth + } + if maxWidth < 64 || maxWidth > computerUseMaxImageWidth { + return nil, fmt.Errorf("max_width must be between 64 and %d", computerUseMaxImageWidth) + } + if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) { + return nil, errors.New("region width and height must be positive") + } _, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) if err != nil { return nil, err } - path, format, cleanup, err := a.consoleCapture(ctx, route, computerUsePreviewWidth) + // A region is cut from the full-resolution frame, so the driver must not + // shrink it first. + captureEdge := maxWidth + if req.Region != nil { + captureEdge = 0 + } + path, format, cleanup, err := a.consoleCapture(ctx, route, captureEdge) if err != nil { return nil, err } @@ -803,26 +869,43 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa if err != nil { return nil, err } - // A blank frame is a normal screen state during boot, login and display - // switches. Return it with a flag so pollers can keep waiting through it. - preview, blank, err := thumb.LoadPreviewFrame(path, format, computerUsePreviewWidth) + var ( + frame image.Image + blank bool + ) + result := map[string]any{"mime_type": "image/jpeg", "source_width": sourceSize.X, "source_height": sourceSize.Y} + if req.Region == nil { + // A blank frame is a normal screen state during boot, login and display + // switches. Return it with a flag so pollers can keep waiting through it. + frame, blank, err = thumb.LoadPreviewFrame(path, format, maxWidth) + if err != nil { + return nil, err + } + } else { + full, err := thumb.Load(path, format) + if err != nil { + return nil, err + } + var applied computerUseRegion + region := computerUseRegionToSource(*req.Region, req.Width, req.Height, full.Bounds().Size()) + result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy() + frame, applied, err = computerUseRegionFrame(full, region, maxWidth) + if err != nil { + return nil, err + } + blank = thumb.Blank(full) + result["region"] = applied + } + encoded, err := thumb.JPEG(frame, 84) if err != nil { return nil, err } - encoded, err := thumb.JPEG(preview, 84) - if err != nil { - return nil, err - } - bounds := preview.Bounds() - return map[string]any{ - "mime_type": "image/jpeg", - "width": bounds.Dx(), - "height": bounds.Dy(), - "source_width": sourceSize.X, - "source_height": sourceSize.Y, - "blank": blank, - "data": base64.StdEncoding.EncodeToString(encoded), - }, nil + bounds := frame.Bounds() + result["width"] = bounds.Dx() + result["height"] = bounds.Dy() + result["blank"] = blank + result["data"] = base64.StdEncoding.EncodeToString(encoded) + return result, nil } func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { @@ -859,6 +942,8 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr VM string `json:"vm"` Key string `json:"key"` Modifiers []string `json:"modifiers"` + // Down holds (true) or releases (false) one key instead of pressing it. + Down *bool `json:"down"` } if err := json.Unmarshal(raw, &req); err != nil { return nil, err @@ -866,11 +951,40 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr if strings.TrimSpace(req.Key) == "" { return nil, errors.New("key is required") } + if req.Down != nil && len(req.Modifiers) > 0 { + return nil, errors.New("a held key takes no modifiers; hold each key separately") + } _, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) if err != nil { return nil, err } - if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil { + if req.Down != nil { + err = a.consoleKeyState(ctx, route, req.Key, *req.Down) + } else { + err = a.consoleKey(ctx, route, req.Key, req.Modifiers) + } + if err != nil { + return nil, err + } + return map[string]any{"ok": true}, nil +} + +// handleComputerUseRelease lifts the given keys and pointer buttons in one +// report, so a client that stops mid-gesture never leaves input held. +func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) { + var req struct { + VM string `json:"vm"` + Keys []string `json:"keys"` + Buttons []string `json:"buttons"` + } + if err := json.Unmarshal(raw, &req); err != nil { + return nil, err + } + _, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM) + if err != nil { + return nil, err + } + if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil { return nil, err } return map[string]any{"ok": true}, nil diff --git a/internal/app/computer_use_region_test.go b/internal/app/computer_use_region_test.go new file mode 100644 index 0000000..f67a569 --- /dev/null +++ b/internal/app/computer_use_region_test.go @@ -0,0 +1,72 @@ +package app + +import ( + "image" + "image/color" + "testing" +) + +func TestComputerUseRegionFrameCropsSourcePixels(t *testing.T) { + full := image.NewRGBA(image.Rect(0, 0, 400, 300)) + for y := 100; y < 150; y++ { + for x := 200; x < 260; x++ { + full.SetRGBA(x, y, color.RGBA{R: 255, A: 255}) + } + } + frame, applied, err := computerUseRegionFrame(full, computerUseRegion{X: 200, Y: 100, Width: 60, Height: 50}, 1280) + if err != nil { + t.Fatal(err) + } + if applied != (computerUseRegion{X: 200, Y: 100, Width: 60, Height: 50}) { + t.Fatalf("实际区域 = %+v", applied) + } + b := frame.Bounds() + if b.Dx() != 60 || b.Dy() != 50 { + t.Fatalf("区域未保持源分辨率:%dx%d", b.Dx(), b.Dy()) + } + if r, _, _, _ := frame.At(b.Min.X, b.Min.Y).RGBA(); r>>8 != 255 { + t.Fatal("裁剪结果不是所选区域的像素") + } +} + +func TestComputerUseRegionFrameClipsAndShrinks(t *testing.T) { + full := image.NewRGBA(image.Rect(0, 0, 4000, 2000)) + frame, applied, err := computerUseRegionFrame(full, computerUseRegion{X: 1000, Y: 1500, Width: 3500, Height: 1000}, 1500) + if err != nil { + t.Fatal(err) + } + if applied != (computerUseRegion{X: 1000, Y: 1500, Width: 3000, Height: 500}) { + t.Fatalf("越界区域未裁到屏幕内:%+v", applied) + } + if got := frame.Bounds().Dx(); got != 1500 { + t.Fatalf("宽区域未缩放到 max_width:%d", got) + } + if _, _, err := computerUseRegionFrame(full, computerUseRegion{X: 5000, Y: 0, Width: 10, Height: 10}, 1280); err == nil { + t.Fatal("屏幕外的区域应报错") + } +} + +func TestComputerUseRegionToSourceScalesFromReferenceImage(t *testing.T) { + got := computerUseRegionToSource(computerUseRegion{X: 100, Y: 50, Width: 33, Height: 20}, 1280, 720, image.Pt(2560, 1440)) + if got != (computerUseRegion{X: 200, Y: 100, Width: 66, Height: 40}) { + t.Fatalf("缩放后的区域 = %+v", got) + } + odd := computerUseRegionToSource(computerUseRegion{X: 1, Y: 1, Width: 1, Height: 1}, 3, 3, image.Pt(4, 4)) + if odd.X != 1 || odd.Y != 1 || odd.Width < 1 || odd.Height < 1 { + t.Fatalf("取整后丢失了所选像素:%+v", odd) + } + same := computerUseRegion{X: 5, Y: 6, Width: 7, Height: 8} + if computerUseRegionToSource(same, 0, 0, image.Pt(100, 100)) != same { + t.Fatal("未给出参考尺寸时应按源像素处理") + } +} + +func TestNormalizeReleaseButtons(t *testing.T) { + got, err := normalizeReleaseButtons([]string{" Left", "middle"}) + if err != nil || len(got) != 2 || got[0] != "left" || got[1] != "middle" { + t.Fatalf("got %v, %v", got, err) + } + if _, err := normalizeReleaseButtons([]string{"wheel-up"}); err == nil { + t.Fatal("滚轮不是可按住的按键,应被拒绝") + } +} diff --git a/internal/app/console_router.go b/internal/app/console_router.go index cf3d4f3..2b17be3 100644 --- a/internal/app/console_router.go +++ b/internal/app/console_router.go @@ -7,6 +7,7 @@ import ( "os" "strings" + "github.com/Nwflower/reims-go/internal/console" "github.com/Nwflower/reims-go/internal/driver" ) @@ -171,6 +172,70 @@ func (a *App) consolePointer(ctx context.Context, route consoleRoute, req driver return fmt.Errorf("unsupported pointer action %q", req.Action) } +// consoleKeyState holds or releases one key. Only the host's QMP console can +// hold a key; a driver console exposes presses alone. +func (a *App) consoleKeyState(ctx context.Context, route consoleRoute, key string, down bool) error { + if route.kind == consoleRouteDriver { + return fmt.Errorf("computer_use_unsupported: driver %q cannot hold a key", route.vm.DriverID) + } + code, err := console.NormalizeHeldKey(key) + if err != nil { + return err + } + service, err := a.computerUseService() + if err != nil { + return err + } + return service.SendKey(ctx, route.vm.Directory, code, down) +} + +// consoleRelease lifts held keys and pointer buttons on the VM's console. +func (a *App) consoleRelease(ctx context.Context, route consoleRoute, keys, buttons []string) error { + buttons, err := normalizeReleaseButtons(buttons) + if err != nil { + return err + } + if route.kind == consoleRouteDriver { + // A driver console cannot hold keys, so only its buttons need lifting. + up := false + for _, button := range buttons { + if err := route.console.ConsolePointer(ctx, route.vm.Name, driver.ConsolePointerRequest{Action: "button", Button: button, Down: &up}); err != nil { + return err + } + } + return nil + } + codes := make([]string, 0, len(keys)) + for _, key := range keys { + code, err := console.NormalizeHeldKey(key) + if err != nil { + return err + } + codes = append(codes, code) + } + if len(codes)+len(buttons) == 0 { + return nil + } + service, err := a.computerUseService() + if err != nil { + return err + } + return service.ReleaseInputs(ctx, route.vm.Directory, codes, buttons) +} + +func normalizeReleaseButtons(buttons []string) ([]string, error) { + out := make([]string, 0, len(buttons)) + for _, button := range buttons { + switch name := strings.ToLower(strings.TrimSpace(button)); name { + case "left", "right", "middle": + out = append(out, name) + default: + return nil, fmt.Errorf("unsupported pointer button %q", button) + } + } + return out, nil +} + // consoleKey presses one key on the VM's console. func (a *App) consoleKey(ctx context.Context, route consoleRoute, key string, modifiers []string) error { if route.kind == consoleRouteDriver { diff --git a/internal/app/plugin_connect.go b/internal/app/plugin_connect.go index 786e753..655d9f7 100644 --- a/internal/app/plugin_connect.go +++ b/internal/app/plugin_connect.go @@ -6,6 +6,7 @@ import ( "errors" "github.com/Nwflower/reims-go/internal/control" + "github.com/Nwflower/reims-go/internal/plugin" ) func (a *App) startPluginControlServer() { @@ -16,15 +17,26 @@ func (a *App) startPluginControlServer() { } a.mu.Unlock() - server, err := control.Listen(func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { + currentManager := func() *plugin.Manager { a.mu.Lock() - mgr := a.pluginMgr - a.mu.Unlock() + defer a.mu.Unlock() + return a.pluginMgr + } + server, err := control.ListenWithOptions(control.PipeName(), func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { + mgr := currentManager() if mgr == nil { return nil, errors.New("plugin manager is not ready") } - return mgr.ChannelMessage(ctx, pluginID, channel, message) - }) + return mgr.ChannelMessage(ctx, pluginID, channel, control.SessionFrom(ctx), message) + }, control.Options{OnSessionEnd: func(session string, targets []control.Target) { + mgr := currentManager() + if mgr == nil { + return + } + for _, target := range targets { + mgr.ChannelSessionClosed(target.PluginID, target.Channel, session) + } + }}) if err != nil { a.emitLog("plugin", "Could not open local plugin control channel: "+err.Error()) return diff --git a/internal/console/held_key_test.go b/internal/console/held_key_test.go new file mode 100644 index 0000000..a5debee --- /dev/null +++ b/internal/console/held_key_test.go @@ -0,0 +1,24 @@ +package console + +import "testing" + +func TestNormalizeHeldKeyAcceptsModifiersAndKeys(t *testing.T) { + cases := map[string]string{ + "cmd": "meta_l", + "Command": "meta_l", + "option": "alt", + "shift": "shift", + "a": "a", + "Return": "ret", + "space": "spc", + } + for in, want := range cases { + got, err := NormalizeHeldKey(in) + if err != nil || got != want { + t.Errorf("NormalizeHeldKey(%q) = %q, %v; want %q", in, got, err, want) + } + } + if _, err := NormalizeHeldKey("cmd+a"); err == nil { + t.Error("组合键不能作为单个按住的按键") + } +} diff --git a/internal/console/manager.go b/internal/console/manager.go index a785801..13f2780 100644 --- a/internal/console/manager.go +++ b/internal/console/manager.go @@ -266,6 +266,15 @@ func normalizeKeyCode(key string) (string, error) { return code, nil } +// NormalizeHeldKey maps a key or modifier name to the QMP key code that +// SendKey and ReleaseInputs take, so a caller can hold Command as well as A. +func NormalizeHeldKey(key string) (string, error) { + if code, err := normalizeModifier(key); err == nil { + return code, nil + } + return normalizeKeyCode(key) +} + func normalizeModifier(modifier string) (string, error) { code := strings.ToLower(strings.TrimSpace(modifier)) switch code { diff --git a/internal/control/control.go b/internal/control/control.go index 1aa09c7..9181d83 100644 --- a/internal/control/control.go +++ b/internal/control/control.go @@ -2,6 +2,7 @@ package control import ( "context" + "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" @@ -29,6 +30,42 @@ type Response struct { type Handler func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) +// Target names one plugin channel that a control connection used. +type Target struct { + PluginID string + Channel string +} + +// Options configures a control server. OnSessionEnd runs once per connection +// after its last in-flight call returns, with the channels it reached. +type Options struct { + OnSessionEnd func(session string, targets []Target) +} + +type sessionKey struct{} + +// WithSession tags ctx with the control connection that issued a call. +func WithSession(ctx context.Context, session string) context.Context { + return context.WithValue(ctx, sessionKey{}, session) +} + +// SessionFrom returns the control connection identifier carried by ctx. +func SessionFrom(ctx context.Context) string { + if ctx == nil { + return "" + } + session, _ := ctx.Value(sessionKey{}).(string) + return session +} + +func newSessionID() string { + var raw [12]byte + if _, err := rand.Read(raw[:]); err != nil { + return "" + } + return hex.EncodeToString(raw[:]) +} + // PipeName gives the desktop process and its CLI clients a deterministic // endpoint scoped to this installation path and Windows user. func PipeName() string { diff --git a/internal/control/control_other.go b/internal/control/control_other.go index 79badc1..542e8f0 100644 --- a/internal/control/control_other.go +++ b/internal/control/control_other.go @@ -12,11 +12,7 @@ type Server struct{} func currentUserScope() string { return "unsupported" } -func Listen(Handler) (*Server, error) { - return nil, errors.ErrUnsupported -} - -func ListenAt(string, Handler) (*Server, error) { +func ListenWithOptions(string, Handler, Options) (*Server, error) { return nil, errors.ErrUnsupported } diff --git a/internal/control/control_windows.go b/internal/control/control_windows.go index 1715c29..534aea0 100644 --- a/internal/control/control_windows.go +++ b/internal/control/control_windows.go @@ -30,6 +30,7 @@ func currentUserScope() string { type Server struct { listener net.Listener handler Handler + options Options cancel context.CancelFunc mu sync.Mutex @@ -37,11 +38,7 @@ type Server struct { wg sync.WaitGroup } -func Listen(handler Handler) (*Server, error) { - return ListenAt(PipeName(), handler) -} - -func ListenAt(pipeName string, handler Handler) (*Server, error) { +func ListenWithOptions(pipeName string, handler Handler, options Options) (*Server, error) { if handler == nil { return nil, errors.New("control handler is required") } @@ -60,7 +57,7 @@ func ListenAt(pipeName string, handler Handler) (*Server, error) { return nil, fmt.Errorf("listen on the Reims-Go control pipe: %w", err) } ctx, cancel := context.WithCancel(context.Background()) - s := &Server{listener: listener, handler: handler, cancel: cancel, conns: make(map[net.Conn]struct{})} + s := &Server{listener: listener, handler: handler, options: options, cancel: cancel, conns: make(map[net.Conn]struct{})} s.wg.Add(1) go s.acceptLoop(ctx) return s, nil @@ -99,8 +96,22 @@ func (s *Server) serveConn(serverCtx context.Context, conn net.Conn) { _ = conn.Close() }() - connCtx, cancel := context.WithCancel(serverCtx) + session := newSessionID() + connCtx, cancel := context.WithCancel(WithSession(serverCtx, session)) defer cancel() + // Only the read loop below writes targets; the deferred report runs after + // every handler has returned. + targets := make(map[Target]struct{}) + defer func() { + if s.options.OnSessionEnd == nil || session == "" || len(targets) == 0 { + return + } + list := make([]Target, 0, len(targets)) + for target := range targets { + list = append(list, target) + } + s.options.OnSessionEnd(session, list) + }() var handlers sync.WaitGroup var writeMu sync.Mutex writer := bufio.NewWriter(conn) @@ -137,6 +148,7 @@ func (s *Server) serveConn(serverCtx context.Context, conn net.Conn) { } continue } + targets[Target{PluginID: req.PluginID, Channel: req.Channel}] = struct{}{} handlers.Add(1) go func(req Request) { defer handlers.Done() diff --git a/internal/control/session_windows_test.go b/internal/control/session_windows_test.go new file mode 100644 index 0000000..27ffbbe --- /dev/null +++ b/internal/control/session_windows_test.go @@ -0,0 +1,90 @@ +//go:build windows + +package control + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "sync" + "testing" + "time" + + "github.com/Microsoft/go-winio" +) + +// TestSessionsAreScopedPerConnection checks that each control connection gets +// its own session, that every call on one connection carries the same one, +// and that the end of a connection is reported with the channels it used. +func TestSessionsAreScopedPerConnection(t *testing.T) { + pipe := fmt.Sprintf(`\\.\pipe\reims-go-control-test-%d`, time.Now().UnixNano()) + var mu sync.Mutex + seen := map[string]int{} + ended := make(chan []Target, 4) + endedSessions := make(chan string, 4) + server, err := ListenWithOptions(pipe, func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { + mu.Lock() + seen[SessionFrom(ctx)]++ + mu.Unlock() + return json.RawMessage(`{"ok":true}`), nil + }, Options{OnSessionEnd: func(session string, targets []Target) { + endedSessions <- session + ended <- targets + }}) + if err != nil { + t.Fatal(err) + } + defer server.Close() + + call := func(n int) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + conn, err := winio.DialPipeContext(ctx, pipe) + if err != nil { + t.Fatal(err) + } + encoder := json.NewEncoder(conn) + reader := bufio.NewScanner(conn) + for i := range n { + if err := encoder.Encode(Request{PluginID: "p", Channel: "mcp", Message: json.RawMessage(`{"id":1}`), RequestID: json.RawMessage(fmt.Sprint(i))}); err != nil { + t.Fatal(err) + } + if !reader.Scan() { + t.Fatal("没有收到响应") + } + } + if err := encoder.Encode(Request{CloseInput: true}); err != nil { + t.Fatal(err) + } + _ = conn.Close() + } + call(2) + call(1) + + sessions := map[string]bool{} + for range 2 { + select { + case targets := <-ended: + if len(targets) != 1 || targets[0] != (Target{PluginID: "p", Channel: "mcp"}) { + t.Fatalf("连接结束时报告的通道 = %+v", targets) + } + sessions[<-endedSessions] = true + case <-time.After(5 * time.Second): + t.Fatal("连接结束后没有回调") + } + } + mu.Lock() + defer mu.Unlock() + if len(seen) != 2 || len(sessions) != 2 { + t.Fatalf("两条连接应各有一个会话:calls=%v ended=%v", seen, sessions) + } + for session, count := range seen { + if session == "" || !sessions[session] { + t.Fatalf("会话 %q 未被报告结束", session) + } + if count != 1 && count != 2 { + t.Fatalf("会话 %q 调用次数异常:%d", session, count) + } + } +} diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 6c08679..e37e11e 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -143,9 +143,21 @@ func (m *Manager) NotifySidecar(pluginID, method string, params any) { } } +// ChannelSessionClosed tells pluginID's running Sidecar that one client +// connection to channelID has ended, so it can cancel that connection's calls +// and release anything it still holds. It never wakes an idle Sidecar. +func (m *Manager) ChannelSessionClosed(pluginID, channelID, session string) { + if m == nil || session == "" || strings.TrimSpace(channelID) == "" { + return + } + m.NotifySidecar(pluginID, "channel/"+channelID+"/closed", map[string]string{"session": session}) +} + // ChannelMessage forwards one JSON line to a declared, active Sidecar channel. -// Channel payloads are never written to the host audit log. -func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID string, message json.RawMessage) (json.RawMessage, error) { +// session identifies the client connection, so a Sidecar can scope request ids +// and cancellation per connection. Channel payloads are never written to the +// host audit log. +func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID, session string, message json.RawMessage) (json.RawMessage, error) { if m == nil || m.registry == nil { return nil, errors.New("plugin manager is unavailable") } @@ -181,7 +193,11 @@ func (m *Manager) ChannelMessage(ctx context.Context, pluginID, channelID string var response struct { Message json.RawMessage `json:"message"` } - err := supervisor.Call(ctx, "channel/"+channelID+"/message", map[string]json.RawMessage{"message": message}, &response) + params := map[string]any{"message": message} + if session != "" { + params["session"] = session + } + err := supervisor.Call(ctx, "channel/"+channelID+"/message", params, &response) if err != nil { return nil, err }