Files
reims-agent/internal/mcp/screen_test.go
T
千川白浪andClaude Opus 5.5 d682620fe5 feat(mcp)!: 工具设计范式更新到 0.2.0 (#6)
Serve six computer-use tools on the mcp channel and add the guest,
restore point, clone and test tools on a new mcp-dev channel.

- vm_power replaces vm_start, vm_shutdown, vm_suspend and vm_resume and adds
  force_stop.
- screen replaces the screenshot and zoom actions and wait_for_screen: it can
  wait for a change or a stable frame (up to 180 s while booting) and return
  one region at up to source resolution.
- computer_input replaces computer and computer_batch: it checks every step
  before sending input, holds modifiers around pointer actions, stops on a
  wait_screen timeout, and releases held keys and buttons on success, error
  or cancellation.
- Coordinates follow the last full image returned, so scaled screenshots no
  longer misplace clicks; results report the image size and a short sha256
  as compact JSON and structuredContent.
- Calls on one VM run in order instead of all tools sharing one lock;
  request ids and cancellation are scoped per client connection, and a
  closed connection cancels its calls.
- guest_wait_ready returns the plugin public key; logs_read pages guest and
  test logs; test_wait returns the result once finished; sessions and test
  runs always use a clone. Removed the screen resource.
- Tools carry annotations and one-sentence descriptions, and arguments the
  schema does not name are refused.

Requires a Reims-Go host with region screenshots, held-key input,
host/console.release and forced shutdown.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:52:45 -07:00

229 lines
8.6 KiB
Go

package mcp
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"image"
"image/color"
"image/jpeg"
"strings"
"sync"
"testing"
)
type scriptedScreen struct {
data string
blank bool
w, h int
err error
}
// scriptedHost plays screens in order, repeating the last one, and accepts
// every other call.
type scriptedHost struct {
mu sync.Mutex
calls []hostCall
screens []scriptedScreen
idx int
failOn func(method string, params map[string]any) error
}
func (h *scriptedHost) Call(_ context.Context, method string, params any, out any) error {
h.mu.Lock()
defer h.mu.Unlock()
h.calls = append(h.calls, hostCall{method: method, params: params})
args, _ := params.(map[string]any)
if h.failOn != nil {
if err := h.failOn(method, args); err != nil {
return err
}
}
if method != "host/console.screenshot" {
if r, ok := out.(*hostReply); ok {
*r = hostReply{OK: true, Characters: 5}
}
return nil
}
sc := h.screens[min(h.idx, len(h.screens)-1)]
h.idx++
if sc.err != nil {
return sc.err
}
w, hgt := sc.w, sc.h
if w == 0 {
w, hgt = 320, 180
}
reply := hostReply{Data: sc.data, MIMEType: "image/jpeg", Width: w, Height: hgt, SourceWidth: w * 2, SourceHeight: hgt * 2, Blank: sc.blank}
if area, ok := args["region"].(region); ok {
reply.Region = &area
reply.Width, reply.Height = area.Width, area.Height
}
*out.(*hostReply) = reply
return nil
}
func (h *scriptedHost) callsTo(method string) []map[string]any {
h.mu.Lock()
defer h.mu.Unlock()
var found []map[string]any
for _, call := range h.calls {
if call.method == method {
args, _ := call.params.(map[string]any)
found = append(found, args)
}
}
return found
}
func makeFrame(t *testing.T, w, h int, bg color.RGBA, cursorOn bool) string {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := range h {
for x := range w {
img.Set(x, y, bg)
}
}
if cursorOn {
// 2x14 blinking caret in the middle of the frame (~0.05% of pixels)
for y := h/2 - 7; y < h/2+7; y++ {
img.Set(w/2, y, color.RGBA{R: 255, G: 255, B: 255, A: 255})
img.Set(w/2+1, y, color.RGBA{R: 255, G: 255, B: 255, A: 255})
}
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
t.Fatal(err)
}
return base64.StdEncoding.EncodeToString(buf.Bytes())
}
func structured(t *testing.T, result map[string]any) map[string]any {
t.Helper()
info, ok := result["structuredContent"].(map[string]any)
if !ok {
t.Fatalf("result has no structuredContent: %v", result)
}
var fromText map[string]any
if err := json.Unmarshal([]byte(resultText(t, result)), &fromText); err != nil || len(fromText) != len(info) {
t.Fatalf("text should be the structured result as compact JSON: %q", resultText(t, result))
}
return info
}
func TestScreenReportsImageSizeAndShortHash(t *testing.T) {
host := &scriptedHost{screens: []scriptedScreen{{data: makeFrame(t, 64, 36, color.RGBA{R: 40, A: 255}, false), w: 640, h: 360}}}
server := New()
server.BindHost(host)
result := callTool(t, server, "screen", `{"vm":"macos1","scale":0.5}`)
info := structured(t, result)
if info["width"] != float64(640) || info["height"] != float64(360) || info["source_width"] != float64(1280) || len(info["sha256"].(string)) != hashHexLength {
t.Fatalf("screen info = %v", info)
}
if result["content"].([]any)[0].(map[string]any)["type"] != "image" {
t.Fatal("screen should attach the image by default")
}
if got := host.callsTo("host/console.screenshot")[0]["max_width"]; got != 640 {
t.Fatalf("scale 0.5 should ask the host for 640 px, got %v", got)
}
if result := callTool(t, server, "screen", `{"vm":"macos1","return_image":false}`); len(result["content"].([]any)) != 1 {
t.Fatal("return_image false should leave only the text")
}
}
func TestScreenRegionIsMeasuredInTheLastImage(t *testing.T) {
host := &scriptedHost{screens: []scriptedScreen{{data: makeFrame(t, 64, 36, color.RGBA{G: 90, A: 255}, false), w: 640, h: 360}}}
server := New()
server.BindHost(host)
callTool(t, server, "screen", `{"vm":"macos1","scale":0.5}`)
info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","region":{"x":10,"y":20,"width":100,"height":50}}`))
shots := host.callsTo("host/console.screenshot")
last := shots[len(shots)-1]
if last["region"] != (region{X: 10, Y: 20, Width: 100, Height: 50}) || last["width"] != 640 || last["height"] != 360 {
t.Fatalf("region request = %v", last)
}
if info["region"] == nil {
t.Fatalf("region result should report the source region: %v", info)
}
// A region is a detail view; it does not change the coordinate space.
if frame, _ := server.screens.lastFrame("macos1"); frame.width != 640 {
t.Fatalf("region capture replaced the reference image: %+v", frame)
}
if result := callTool(t, server, "screen", `{"vm":"macos1","region":{"x":700,"y":0,"width":10,"height":10}}`); result["isError"] != true {
t.Fatal("a region starting outside the image must fail")
}
}
func TestScreenWaitIgnoresBlinkingCursorAndSkipsBlank(t *testing.T) {
cursorOff := makeFrame(t, 320, 180, color.RGBA{R: 30, G: 40, B: 50, A: 255}, false)
cursorOn := makeFrame(t, 320, 180, color.RGBA{R: 30, G: 40, B: 50, A: 255}, true)
blankFrame := makeFrame(t, 320, 180, color.RGBA{A: 255}, false)
host := &scriptedHost{screens: []scriptedScreen{
{data: blankFrame, blank: true}, {data: cursorOff}, {data: cursorOn}, {data: cursorOff}, {data: cursorOn},
}}
server := New()
var logBuf bytes.Buffer
server.logw = &logBuf
server.BindHost(host)
info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":500,"timeout_ms":3000}}`))
if info["timed_out"] != nil || info["blank"] != false {
t.Fatalf("expected a settled non-blank frame despite the blinking cursor: %v", info)
}
if !strings.Contains(logBuf.String(), "tools/call screen ") || !strings.Contains(logBuf.String(), " ok\n") {
t.Fatalf("expected tools/call log line, got: %q", logBuf.String())
}
}
func TestScreenWaitTimeoutReturnsLastFrameNotError(t *testing.T) {
f1 := makeFrame(t, 320, 180, color.RGBA{R: 20, G: 20, B: 20, A: 255}, false)
f2 := makeFrame(t, 320, 180, color.RGBA{R: 220, G: 220, B: 220, A: 255}, false)
host := &scriptedHost{screens: []scriptedScreen{{data: f1}, {data: f2}, {data: f1}, {data: f2}, {data: f1}, {data: f2}}}
server := New()
var logBuf bytes.Buffer
server.logw = &logBuf
server.BindHost(host)
result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":600,"timeout_ms":600}}`)
if result["isError"] == true || result["content"].([]any)[0].(map[string]any)["type"] != "image" {
t.Fatalf("a timeout should return the last frame without an error: %v", result)
}
if info := structured(t, result); info["timed_out"] != true || info["until"] != "stable" {
t.Fatalf("timeout info = %v", info)
}
if !strings.Contains(logBuf.String(), " timeout\n") {
t.Fatalf("expected timeout status in log, got: %q", logBuf.String())
}
}
func TestScreenWaitForChangeStartsFromTheLastImage(t *testing.T) {
before := makeFrame(t, 320, 180, color.RGBA{R: 10, G: 20, B: 30, A: 255}, false)
after := makeFrame(t, 320, 180, color.RGBA{R: 200, G: 210, B: 220, A: 255}, false)
host := &scriptedHost{screens: []scriptedScreen{{data: before}, {data: after}}}
server := New()
server.BindHost(host)
first := structured(t, callTool(t, server, "screen", `{"vm":"macos1"}`))
// The screen changed between calls; the wait must still notice.
info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"change","timeout_ms":2000}}`))
if info["timed_out"] != nil || info["sha256"] == first["sha256"] {
t.Fatalf("wait for change should end on the new frame: first=%v now=%v", first, info)
}
if result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"baseline":"0000000000000000"}}`); result["isError"] != true {
t.Fatal("an unknown baseline must fail rather than wait against nothing")
}
}
func TestScreenWaitRetriesHostErrorsWhileBooting(t *testing.T) {
ready := makeFrame(t, 320, 180, color.RGBA{R: 120, G: 140, B: 160, A: 255}, false)
host := &scriptedHost{screens: []scriptedScreen{{err: errors.New("vm is not running")}, {err: errors.New("vm is not running")}, {data: ready}}}
server := New()
server.BindHost(host)
info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":0,"timeout_ms":5000}}`))
if info["timed_out"] != nil || info["blank"] != false {
t.Fatalf("wait should ride out capture errors during boot: %v", info)
}
if result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"timeout_ms":180001}}`); result["isError"] != true {
t.Fatal("timeout_ms above 180000 must fail")
}
}