From 98aea3bd143e97f4879d2906d85cef8399b22398 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: Wed, 2 Dec 2026 07:59:14 -0700 Subject: [PATCH] feat(mcp): add cursor-tolerant wait_for_screen, computer_batch, and round-trip optimizations --- internal/mcp/screen.go | 569 +++++++++++++++++++++++++++++++++ internal/mcp/screen_test.go | 201 ++++++++++++ internal/mcp/server.go | 619 ++++++++++++++++++++++++------------ internal/mcp/server_test.go | 14 +- 4 files changed, 1198 insertions(+), 205 deletions(-) create mode 100644 internal/mcp/screen.go create mode 100644 internal/mcp/screen_test.go diff --git a/internal/mcp/screen.go b/internal/mcp/screen.go new file mode 100644 index 0000000..6a74038 --- /dev/null +++ b/internal/mcp/screen.go @@ -0,0 +1,569 @@ +package mcp + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "image" + "image/jpeg" + "math" + "strings" + "sync" + "time" +) + +const ( + thumbW = 160 + thumbH = 90 + pixelDiffThreshold = 16 + defaultTolerance = 0.002 // 0.2% + maxFrameCacheEntries = 64 + defaultWaitPollPeriod = 250 * time.Millisecond +) + +type cachedFrame struct { + hash string + gray []uint8 + width int + height int + blank bool +} + +type screenCache struct { + mu sync.Mutex + byHash map[string][]uint8 + order []string + vmSize map[string][2]int + vmFrame map[string]cachedFrame +} + +func newScreenCache() *screenCache { + return &screenCache{ + byHash: make(map[string][]uint8), + vmSize: make(map[string][2]int), + vmFrame: make(map[string]cachedFrame), + } +} + +func (c *screenCache) record(vm string, screen hostReply) cachedFrame { + digest := sha256.Sum256([]byte(screen.Data)) + hash := hex.EncodeToString(digest[:]) + gray, _ := decodeGrayThumb(screen.Data) + cf := cachedFrame{ + hash: hash, + gray: gray, + width: screen.Width, + height: screen.Height, + blank: screen.Blank, + } + c.mu.Lock() + defer c.mu.Unlock() + if gray != nil { + if _, exists := c.byHash[hash]; !exists { + if len(c.order) >= maxFrameCacheEntries { + oldest := c.order[0] + c.order = c.order[1:] + delete(c.byHash, oldest) + } + c.order = append(c.order, hash) + } + c.byHash[hash] = gray + } + if vm != "" { + if screen.Width > 0 && screen.Height > 0 { + c.vmSize[vm] = [2]int{screen.Width, screen.Height} + } + c.vmFrame[vm] = cf + } + return cf +} + +func (c *screenCache) grayByHash(hash string) []uint8 { + if hash == "" { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + return c.byHash[hash] +} + +func (c *screenCache) sizeForVM(vm string) (int, int, bool) { + c.mu.Lock() + defer c.mu.Unlock() + sz, ok := c.vmSize[vm] + if !ok || sz[0] <= 0 || sz[1] <= 0 { + return 0, 0, false + } + return sz[0], sz[1], true +} + +func (c *screenCache) lastFrameForVM(vm string) (cachedFrame, bool) { + c.mu.Lock() + defer c.mu.Unlock() + cf, ok := c.vmFrame[vm] + return cf, ok +} + +func decodeGrayThumb(encoded string) ([]uint8, bool) { + if encoded == "" { + return nil, false + } + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, false + } + img, err := jpeg.Decode(bytes.NewReader(raw)) + if err != nil { + return nil, false + } + b := img.Bounds() + srcW, srcH := b.Dx(), b.Dy() + if srcW <= 0 || srcH <= 0 { + return nil, false + } + gray := make([]uint8, thumbW*thumbH) + for y := range thumbH { + sy := b.Min.Y + (y*srcH)/thumbH + rowOff := y * thumbW + for x := range thumbW { + sx := b.Min.X + (x*srcW)/thumbW + r, g, bl, _ := img.At(sx, sy).RGBA() + // Rec.601 luma from 16-bit channels to 8-bit. + luma := (299*(r>>8) + 587*(g>>8) + 114*(bl>>8)) / 1000 + gray[rowOff+x] = uint8(luma) + } + } + return gray, true +} + +func frameDiffRatio(a, b []uint8) float64 { + if len(a) == 0 || len(a) != len(b) { + return 1.0 + } + diff := 0 + for i := range a { + d := int(a[i]) - int(b[i]) + if d < 0 { + d = -d + } + if d > pixelDiffThreshold { + diff++ + } + } + return float64(diff) / float64(len(a)) +} + +func framesDifferent(hashA string, grayA []uint8, hashB string, grayB []uint8, tolerance float64) bool { + if grayA != nil && grayB != nil { + return frameDiffRatio(grayA, grayB) >= tolerance + } + return hashA != hashB +} + +func scaleJPEG(encoded string, scale float64) (string, int, int, error) { + if scale <= 0 || scale >= 1 { + return encoded, 0, 0, nil + } + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return "", 0, 0, err + } + img, err := jpeg.Decode(bytes.NewReader(raw)) + if err != nil { + return "", 0, 0, err + } + b := img.Bounds() + srcW, srcH := b.Dx(), b.Dy() + dstW := max(1, int(math.Round(float64(srcW)*scale))) + dstH := max(1, int(math.Round(float64(srcH)*scale))) + dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH)) + for y := range dstH { + sy := b.Min.Y + (y*srcH)/dstH + for x := range dstW { + sx := b.Min.X + (x*srcW)/dstW + dst.Set(x, y, img.At(sx, sy)) + } + } + var buf bytes.Buffer + if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 80}); err != nil { + return "", 0, 0, err + } + return base64.StdEncoding.EncodeToString(buf.Bytes()), dstW, dstH, nil +} + +func validateScale(scale float64) (float64, error) { + if scale == 0 { + return 1.0, nil + } + if math.IsNaN(scale) || math.IsInf(scale, 0) || scale < 0.25 || scale > 1.0 { + return 0, fmt.Errorf("%w: scale must be between 0.25 and 1.0", errInvalidParams) + } + return scale, nil +} + +func boolOrDefault(ptr *bool, fallback bool) bool { + if ptr == nil { + return fallback + } + return *ptr +} + +func formatScreenResult(screen hostReply, hash string, summary string, scale float64, returnImage bool) (map[string]any, error) { + text := fmt.Sprintf("%s sha256=%s blank=%t", summary, hash, screen.Blank) + if !returnImage || screen.Data == "" { + return map[string]any{"content": []any{ + map[string]any{"type": "text", "text": text}, + }}, nil + } + data := screen.Data + mime := screen.MIMEType + if mime == "" { + mime = "image/jpeg" + } + if scale > 0 && scale < 1.0 { + scaled, _, _, err := scaleJPEG(data, scale) + if err == nil && scaled != "" { + data = scaled + mime = "image/jpeg" + } + } + return map[string]any{"content": []any{ + map[string]any{"type": "image", "data": data, "mimeType": mime}, + map[string]any{"type": "text", "text": text}, + }}, nil +} + +type waitOptions struct { + VM string + BaselineHash string + BaselineGray []uint8 + Mode string // "stable", "change", "change_then_stable" + TimeoutMS int + MaxTimeoutMS int + StableMS int + Tolerance float64 + AcceptBlank bool + RetryHostErr bool // true during vm_start boot waiting + Scale float64 + ReturnImage bool +} + +type waitOutcome struct { + screen hostReply + frame cachedFrame + hasFrame bool + timedOut bool + mode string +} + +func (s *Server) waitScreenInternal(ctx context.Context, opts waitOptions) (waitOutcome, error) { + if opts.VM == "" { + return waitOutcome{}, fmt.Errorf("%w: vm is required", errInvalidParams) + } + maxTimeout := opts.MaxTimeoutMS + if maxTimeout <= 0 { + maxTimeout = 30000 + } + if opts.TimeoutMS <= 0 { + opts.TimeoutMS = 10000 + } + if opts.TimeoutMS > maxTimeout || opts.StableMS < 0 || opts.StableMS > opts.TimeoutMS { + return waitOutcome{}, fmt.Errorf("%w: timeout_ms must be between 1 and %d and stable_ms <= timeout_ms", errInvalidParams, maxTimeout) + } + mode := strings.ToLower(strings.TrimSpace(opts.Mode)) + if mode == "" { + if opts.BaselineHash != "" { + mode = "change_then_stable" + } else { + mode = "stable" + } + } + switch mode { + case "stable", "change", "change_then_stable": + default: + return waitOutcome{}, fmt.Errorf("%w: mode must be stable, change, or change_then_stable", errInvalidParams) + } + tol := opts.Tolerance + if tol == 0 { + tol = defaultTolerance + } + if math.IsNaN(tol) || math.IsInf(tol, 0) || tol < 0 || tol > 1 { + return waitOutcome{}, fmt.Errorf("%w: tolerance must be between 0 and 1", errInvalidParams) + } + + baselineHash := opts.BaselineHash + baselineGray := opts.BaselineGray + if baselineGray == nil && baselineHash != "" { + baselineGray = s.screens.grayByHash(baselineHash) + } + + waitCtx, cancel := context.WithTimeout(ctx, time.Duration(opts.TimeoutMS)*time.Millisecond) + defer cancel() + deadline := time.NewTimer(time.Duration(opts.TimeoutMS) * time.Millisecond) + defer deadline.Stop() + + var ( + lastScreen hostReply + lastFrame cachedFrame + hasLast bool + anchor cachedFrame + hasAnchor bool + stableSince time.Time + ) + + makeTimeout := func() waitOutcome { + return waitOutcome{ + screen: lastScreen, + frame: lastFrame, + hasFrame: hasLast, + timedOut: true, + mode: mode, + } + } + + for { + var screen hostReply + err := s.host.Call(waitCtx, "host/console.screenshot", map[string]any{"vm": opts.VM}, &screen) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { + return makeTimeout(), nil + } + if ctx.Err() != nil { + return waitOutcome{}, ctx.Err() + } + if !opts.RetryHostErr { + return waitOutcome{}, err + } + } else { + if waitCtx.Err() != nil { + if ctx.Err() == nil { + return makeTimeout(), nil + } + return waitOutcome{}, ctx.Err() + } + cf := s.screens.record(opts.VM, screen) + lastScreen, lastFrame, hasLast = screen, cf, true + + if !screen.Blank || opts.AcceptBlank { + if !hasAnchor { + anchor = cf + hasAnchor = true + stableSince = time.Now() + if baselineHash == "" && (mode == "change" || mode == "change_then_stable") { + baselineHash = cf.hash + baselineGray = cf.gray + } + } else if framesDifferent(anchor.hash, anchor.gray, cf.hash, cf.gray, tol) { + anchor = cf + stableSince = time.Now() + } + + changed := true + if mode == "change" || mode == "change_then_stable" { + changed = framesDifferent(baselineHash, baselineGray, cf.hash, cf.gray, tol) + } + settled := true + if mode == "stable" || mode == "change_then_stable" { + settled = opts.StableMS == 0 || time.Since(stableSince) >= time.Duration(opts.StableMS)*time.Millisecond + } + if changed && settled { + return waitOutcome{ + screen: screen, + frame: cf, + hasFrame: true, + timedOut: false, + mode: mode, + }, nil + } + } + } + + timer := time.NewTimer(defaultWaitPollPeriod) + select { + case <-timer.C: + case <-ctx.Done(): + timer.Stop() + return waitOutcome{}, ctx.Err() + case <-deadline.C: + timer.Stop() + return makeTimeout(), nil + } + } +} + +func formatWaitOutcome(out waitOutcome, timeoutMS int, scale float64, returnImage bool) (map[string]any, error) { + if out.timedOut { + var reason string + switch out.mode { + case "stable": + reason = fmt.Sprintf("Screen did not settle within %dms.", timeoutMS) + case "change": + reason = fmt.Sprintf("Screen did not change within %dms.", timeoutMS) + default: + reason = fmt.Sprintf("Screen did not change and settle within %dms.", timeoutMS) + } + summary := fmt.Sprintf("%s timed_out=true mode=%s", reason, out.mode) + if !out.hasFrame { + return map[string]any{"content": []any{ + map[string]any{"type": "text", "text": summary + " sha256= blank=false"}, + }}, nil + } + return formatScreenResult(out.screen, out.frame.hash, summary, scale, returnImage) + } + summary := fmt.Sprintf("Screen ready. mode=%s", out.mode) + return formatScreenResult(out.screen, out.frame.hash, summary, scale, returnImage) +} + +type computerActionArgs struct { + VM string `json:"vm"` + Action string `json:"action"` + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` + Button string `json:"button"` + Text string `json:"text"` + Key string `json:"key"` + Modifiers []string `json:"modifiers"` + X2 int `json:"x2"` + Y2 int `json:"y2"` + Delta int `json:"delta"` + DurationMS int `json:"duration_ms"` + Horizontal bool `json:"horizontal"` + SettleMS int `json:"settle_ms"` + TimeoutMS int `json:"timeout_ms"` + StableMS int `json:"stable_ms"` + Baseline string `json:"baseline_sha256"` + Mode string `json:"mode"` + Tolerance float64 `json:"tolerance"` + AcceptBlank bool `json:"accept_blank"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` +} + +func (s *Server) computerBatch(ctx context.Context, raw json.RawMessage) (any, error) { + var args struct { + VM string `json:"vm"` + Actions []computerActionArgs `json:"actions"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` + } + if err := decodeArguments(raw, &args); err != nil { + return nil, err + } + if strings.TrimSpace(args.VM) == "" { + return nil, fmt.Errorf("%w: vm is required", errInvalidParams) + } + if len(args.Actions) == 0 { + return nil, fmt.Errorf("%w: actions must not be empty", errInvalidParams) + } + scale, err := validateScale(args.Scale) + if err != nil { + return nil, err + } + returnImage := boolOrDefault(args.ReturnImage, true) + + var ( + executed int + lastScreen hostReply + lastFrame cachedFrame + hasScreen bool + ) + + for i, step := range args.Actions { + step.VM = args.VM + if step.Scale == 0 { + step.Scale = scale + } + act := strings.ToLower(strings.TrimSpace(step.Action)) + if act == "wait_stable" { + baseHash := step.Baseline + var baseGray []uint8 + if baseHash == "" { + if hasScreen { + baseHash = lastFrame.hash + baseGray = lastFrame.gray + } else if prev, ok := s.screens.lastFrameForVM(args.VM); ok { + baseHash = prev.hash + baseGray = prev.gray + } + } + out, waitErr := s.waitScreenInternal(ctx, waitOptions{ + VM: args.VM, + BaselineHash: baseHash, + BaselineGray: baseGray, + Mode: step.Mode, + TimeoutMS: step.TimeoutMS, + StableMS: step.StableMS, + Tolerance: step.Tolerance, + AcceptBlank: step.AcceptBlank, + Scale: step.Scale, + ReturnImage: false, + }) + if waitErr != nil { + return s.batchErrorResult(args.VM, executed, i+1, len(args.Actions), waitErr, lastScreen, lastFrame, hasScreen, scale, returnImage), nil + } + if out.hasFrame { + lastScreen, lastFrame, hasScreen = out.screen, out.frame, true + } + executed++ + continue + } + + // Execute single computer action. + res, screenOut, frameOut, gotScreen, stepErr := s.executeComputerAction(ctx, step) + _ = res + if stepErr != nil { + return s.batchErrorResult(args.VM, executed, i+1, len(args.Actions), stepErr, lastScreen, lastFrame, hasScreen, scale, returnImage), nil + } + if gotScreen { + lastScreen, lastFrame, hasScreen = screenOut, frameOut, true + } + executed++ + } + + if !hasScreen { + var screen hostReply + if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err == nil { + lastScreen = screen + lastFrame = s.screens.record(args.VM, screen) + hasScreen = true + } + } + summary := fmt.Sprintf("Batch completed (%d/%d actions).", executed, len(args.Actions)) + if !hasScreen { + return map[string]any{"content": []any{ + map[string]any{"type": "text", "text": summary + " sha256= blank=false"}, + }}, nil + } + return formatScreenResult(lastScreen, lastFrame.hash, summary, scale, returnImage) +} + +func (s *Server) batchErrorResult(vm string, executed, failedStep, total int, stepErr error, lastScreen hostReply, lastFrame cachedFrame, hasScreen bool, scale float64, returnImage bool) map[string]any { + if !hasScreen { + var screen hostReply + if err := s.host.Call(context.Background(), "host/console.screenshot", map[string]any{"vm": vm}, &screen); err == nil { + lastScreen = screen + lastFrame = s.screens.record(vm, screen) + hasScreen = true + } + } + summary := fmt.Sprintf("Batch failed at step %d/%d (executed=%d): %v", failedStep, total, executed, stepErr) + if !hasScreen { + return map[string]any{ + "isError": true, + "content": []any{map[string]any{"type": "text", "text": summary + " sha256= blank=false"}}, + } + } + res, err := formatScreenResult(lastScreen, lastFrame.hash, summary, scale, returnImage) + if err != nil { + return toolError(summary) + } + res["isError"] = true + return res +} diff --git a/internal/mcp/screen_test.go b/internal/mcp/screen_test.go new file mode 100644 index 0000000..48c0d66 --- /dev/null +++ b/internal/mcp/screen_test.go @@ -0,0 +1,201 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/base64" + "image" + "image/color" + "image/jpeg" + "strings" + "testing" +) + +type scriptedScreen struct { + data string + blank bool + w, h int +} + +type scriptedHost struct { + calls []hostCall + screens []scriptedScreen + idx int +} + +func (h *scriptedHost) Call(_ context.Context, method string, params any, out any) error { + h.calls = append(h.calls, hostCall{method: method, params: params}) + if method == "host/console.screenshot" { + i := h.idx + if i >= len(h.screens) { + i = len(h.screens) - 1 + } else { + h.idx++ + } + sc := h.screens[i] + w, hgt := sc.w, sc.h + if w == 0 { + w, hgt = 320, 180 + } + *out.(*hostReply) = hostReply{ + Data: sc.data, MIMEType: "image/jpeg", Width: w, Height: hgt, SourceWidth: w * 2, SourceHeight: hgt * 2, Blank: sc.blank, + } + return nil + } + if r, ok := out.(*hostReply); ok { + *r = hostReply{OK: true, Characters: 5} + } + return nil +} + +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 TestWaitForScreenIgnoresBlinkingCursorAndSkipsBlank(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{R: 0, G: 0, B: 0, A: 255}, false) + + host := &scriptedHost{ + screens: []scriptedScreen{ + {data: blankFrame, blank: true}, + {data: cursorOff, blank: false}, + {data: cursorOn, blank: false}, + {data: cursorOff, blank: false}, + {data: cursorOn, blank: false}, + }, + } + server := New() + var logBuf bytes.Buffer + server.logw = &logBuf + server.BindHost(host) + + resp := sendRequest(t, server, `{"jsonrpc":"2.0","id":101,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","stable_ms":500,"timeout_ms":3000}}}`) + res := parseResponse(t, resp)["result"].(map[string]any) + if res["isError"] == true { + t.Fatalf("unexpected error: %s", resp) + } + text := res["content"].([]any)[1].(map[string]any)["text"].(string) + if strings.Contains(text, "timed_out=true") || !strings.Contains(text, "sha256=") || !strings.Contains(text, "blank=false") { + t.Fatalf("expected settled non-blank frame despite blinking cursor, got: %s", text) + } + if !strings.Contains(logBuf.String(), "tools/call wait_for_screen ") || !strings.Contains(logBuf.String(), " ok\n") { + t.Fatalf("expected tools/call log line, got: %q", logBuf.String()) + } +} + +func TestWaitForScreenTimeoutReturnsLastFrameNotError(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}}} + server := New() + var logBuf bytes.Buffer + server.logw = &logBuf + server.BindHost(host) + + resp := sendRequest(t, server, `{"jsonrpc":"2.0","id":102,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","mode":"stable","stable_ms":600,"timeout_ms":600}}}`) + res := parseResponse(t, resp)["result"].(map[string]any) + if res["isError"] == true { + t.Fatalf("timeout should not set isError: %s", resp) + } + content := res["content"].([]any) + if len(content) != 2 || content[0].(map[string]any)["type"] != "image" { + t.Fatalf("expected last frame image on timeout: %s", resp) + } + text := content[1].(map[string]any)["text"].(string) + if !strings.Contains(text, "Screen did not settle within 600ms") || !strings.Contains(text, "timed_out=true mode=stable") { + t.Fatalf("unexpected timeout text: %s", text) + } + if !strings.Contains(logBuf.String(), " timeout\n") { + t.Fatalf("expected timeout status in log, got: %q", logBuf.String()) + } +} + +func TestClickReusesCachedSizeAndSupportsSettleObservation(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, w: 1280, h: 720}, + {data: after, w: 1280, h: 720}, + {data: after, w: 1280, h: 720}, + }, + } + server := New() + server.BindHost(host) + + // 1) Initial screenshot populates cache. + shot := sendRequest(t, server, `{"jsonrpc":"2.0","id":103,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"screenshot","scale":0.5}}}`) + shotText := parseResponse(t, shot)["result"].(map[string]any)["content"].([]any)[1].(map[string]any)["text"].(string) + if !strings.Contains(shotText, "sha256=") || !strings.Contains(shotText, "blank=false") { + t.Fatalf("screenshot missing sha256/blank: %s", shotText) + } + + // 2) Click without width/height must NOT call screenshot to discover size. + preCalls := len(host.calls) + _ = sendRequest(t, server, `{"jsonrpc":"2.0","id":104,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"left_click","x":100,"y":200}}}`) + for _, c := range host.calls[preCalls:] { + if c.method == "host/console.screenshot" { + t.Fatalf("left_click should reuse cached VM size without taking screenshot") + } + } + + // 3) Click with settle_ms waits for change and returns observation. + settled := sendRequest(t, server, `{"jsonrpc":"2.0","id":105,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"key","key":"return","settle_ms":200,"timeout_ms":2000,"return_image":false}}}`) + res := parseResponse(t, settled)["result"].(map[string]any) + content := res["content"].([]any) + if len(content) != 1 || content[0].(map[string]any)["type"] != "text" || !strings.Contains(content[0].(map[string]any)["text"].(string), "sha256=") { + t.Fatalf("expected text-only settled observation when return_image=false: %s", settled) + } +} + +func TestComputerBatchAndVMStartWaitUntil(t *testing.T) { + f1 := makeFrame(t, 320, 180, color.RGBA{R: 50, G: 50, B: 50, A: 255}, false) + f2 := makeFrame(t, 320, 180, color.RGBA{R: 150, G: 180, B: 200, A: 255}, false) + host := &scriptedHost{ + screens: []scriptedScreen{ + {data: f1, blank: true}, + {data: f1, blank: false}, + {data: f2, blank: false}, + }, + } + server := New() + server.BindHost(host) + + // vm_start with wait_until=screen skips blank and returns first non-blank frame. + startResp := sendRequest(t, server, `{"jsonrpc":"2.0","id":106,"method":"tools/call","params":{"name":"vm_start","arguments":{"vm":"macos1","wait_until":"screen","timeout_ms":3000}}}`) + startContent := parseResponse(t, startResp)["result"].(map[string]any)["content"].([]any) + if len(startContent) != 2 || !strings.Contains(startContent[1].(map[string]any)["text"].(string), "blank=false") { + t.Fatalf("vm_start wait_until=screen failed: %s", startResp) + } + + // computer_batch runs click + type + key + wait_stable in one call. + batchResp := sendRequest(t, server, `{"jsonrpc":"2.0","id":107,"method":"tools/call","params":{"name":"computer_batch","arguments":{"vm":"macos1","actions":[{"action":"left_click","x":10,"y":10},{"action":"type","text":"hello"},{"action":"key","key":"return"},{"action":"wait_stable","stable_ms":100,"timeout_ms":2000}]}}}`) + batchRes := parseResponse(t, batchResp)["result"].(map[string]any) + if batchRes["isError"] == true { + t.Fatalf("computer_batch failed: %s", batchResp) + } + batchText := batchRes["content"].([]any)[1].(map[string]any)["text"].(string) + if !strings.Contains(batchText, "Batch completed (4/4 actions)") || !strings.Contains(batchText, "sha256=") { + t.Fatalf("unexpected batch summary: %s", batchText) + } +} diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 3aa53cc..2cba42a 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -3,14 +3,13 @@ package mcp import ( "bytes" "context" - "crypto/sha256" "encoding/base64" - "encoding/hex" "encoding/json" "errors" "fmt" "image" "image/jpeg" + "io" "net" "net/url" "os" @@ -36,6 +35,8 @@ type Server struct { guest *guest.SSH root string state *agentState + screens *screenCache + logw io.Writer } type request struct { @@ -64,6 +65,7 @@ type hostReply struct { Height int `json:"height"` SourceWidth int `json:"source_width"` SourceHeight int `json:"source_height"` + Blank bool `json:"blank"` Characters int `json:"characters"` VMs []any `json:"vms"` OK bool `json:"ok"` @@ -74,7 +76,22 @@ func New() *Server { if err != nil { root = "." } - return &Server{guest: guest.NewSSH(filepath.Clean(root)), root: filepath.Clean(root), state: newAgentState(filepath.Clean(root)), calls: make(map[string]context.CancelFunc)} + return &Server{ + guest: guest.NewSSH(filepath.Clean(root)), + root: filepath.Clean(root), + state: newAgentState(filepath.Clean(root)), + calls: make(map[string]context.CancelFunc), + screens: newScreenCache(), + logw: os.Stderr, + } +} + +func (s *Server) logToolCall(name string, dur time.Duration, status string) { + w := s.logw + if w == nil { + w = os.Stderr + } + _, _ = fmt.Fprintf(w, "tools/call %s %d %s\n", name, dur.Milliseconds(), status) } func (s *Server) BindHost(host Host) { s.host = host } @@ -225,15 +242,39 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, error) return nil, fmt.Errorf("%w: tool name is required", errInvalidParams) } if s.host == nil { + s.logToolCall(req.Name, 0, "error") return toolError("Reims-Go host is unavailable"), nil } + started := time.Now() result, err := s.invoke(ctx, req.Name, req.Arguments) + dur := time.Since(started) if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + s.logToolCall(req.Name, dur, "timeout") + } else { + s.logToolCall(req.Name, dur, "error") + } if errors.Is(err, context.Canceled) { return nil, err } return toolError(err.Error()), nil } + status := "ok" + if m, ok := result.(map[string]any); ok { + if isErr, _ := m["isError"].(bool); isErr { + status = "error" + } + if items, ok := m["content"].([]any); ok { + for _, it := range items { + if entry, ok := it.(map[string]any); ok { + if txt, _ := entry["text"].(string); strings.Contains(txt, "timed_out=true") { + status = "timeout" + } + } + } + } + } + s.logToolCall(req.Name, dur, status) return result, nil } @@ -261,50 +302,26 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) ( return nil, err } return textResult(out), nil - case "vm_start", "vm_shutdown": + case "vm_start": + return s.vmStart(ctx, raw) + case "vm_shutdown": var args struct { VM string `json:"vm"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - method := "host/vm.start" - if name == "vm_shutdown" { - method = "host/vm.shutdown" - } var out hostReply - if err := s.host.Call(ctx, method, args, &out); err != nil { + if err := s.host.Call(ctx, "host/vm.shutdown", args, &out); err != nil { return nil, err } return textResult(map[string]any{"ok": true}), nil case "vm_unlock": - var args struct { - VM string `json:"vm"` - } - if err := decodeArguments(raw, &args); err != nil { - return nil, err - } - if args.VM == "" { - return nil, fmt.Errorf("%w: vm is required", errInvalidParams) - } - var typed hostReply - if err := s.host.Call(ctx, "host/console.typeSecret", map[string]any{"vm": args.VM, "setting": "login_password"}, &typed); err != nil { - return nil, err - } - var key hostReply - if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil { - return nil, err - } - var screen hostReply - if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - return nil, err - } - return map[string]any{"content": []any{ - map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType}, - map[string]any{"type": "text", "text": "Login password entered. Current screen attached."}, - }}, nil + return s.vmUnlock(ctx, raw) case "computer": return s.computer(ctx, raw) + case "computer_batch": + return s.computerBatch(ctx, raw) case "wait_for_screen": return s.waitForScreen(ctx, raw) case "guest_public_key": @@ -507,22 +524,72 @@ func (s *Server) guestAddress(ctx context.Context, ref string) (string, string, return net.JoinHostPort("127.0.0.1", fmt.Sprint(int(portValue))), username, nil } -func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) { +func (s *Server) vmStart(ctx context.Context, raw json.RawMessage) (any, error) { var args struct { - VM string `json:"vm"` - Action string `json:"action"` - X int `json:"x"` - Y int `json:"y"` - Width int `json:"width"` - Height int `json:"height"` - Button string `json:"button"` - Text string `json:"text"` - Key string `json:"key"` - Modifiers []string `json:"modifiers"` - X2 int `json:"x2"` - Y2 int `json:"y2"` - Delta int `json:"delta"` - Horizontal bool `json:"horizontal"` + VM string `json:"vm"` + WaitUntil string `json:"wait_until"` + TimeoutMS int `json:"timeout_ms"` + StableMS int `json:"stable_ms"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` + } + if err := decodeArguments(raw, &args); err != nil { + return nil, err + } + waitUntil := strings.ToLower(strings.TrimSpace(args.WaitUntil)) + if waitUntil == "" { + waitUntil = "none" + } + switch waitUntil { + case "none", "screen", "stable": + default: + return nil, fmt.Errorf("%w: wait_until must be none, screen, or stable", errInvalidParams) + } + scale, err := validateScale(args.Scale) + if err != nil { + return nil, err + } + var out hostReply + if err := s.host.Call(ctx, "host/vm.start", map[string]any{"vm": args.VM}, &out); err != nil { + return nil, err + } + if waitUntil == "none" { + return textResult(map[string]any{"ok": true}), nil + } + timeoutMS := args.TimeoutMS + if timeoutMS <= 0 { + timeoutMS = 120000 + } + stableMS := args.StableMS + if waitUntil == "screen" { + stableMS = 0 + } else if stableMS <= 0 { + stableMS = 2000 + } + waitRes, err := s.waitScreenInternal(ctx, waitOptions{ + VM: args.VM, + Mode: "stable", + TimeoutMS: timeoutMS, + MaxTimeoutMS: 180000, + StableMS: stableMS, + AcceptBlank: false, + RetryHostErr: true, + Scale: scale, + ReturnImage: boolOrDefault(args.ReturnImage, true), + }) + if err != nil { + return nil, err + } + return formatWaitOutcome(waitRes, timeoutMS, scale, boolOrDefault(args.ReturnImage, true)) +} + +func (s *Server) vmUnlock(ctx context.Context, raw json.RawMessage) (any, error) { + var args struct { + VM string `json:"vm"` + TimeoutMS int `json:"timeout_ms"` + StableMS int `json:"stable_ms"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` } if err := decodeArguments(raw, &args); err != nil { return nil, err @@ -530,65 +597,162 @@ func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) if args.VM == "" { return nil, fmt.Errorf("%w: vm is required", errInvalidParams) } + scale, err := validateScale(args.Scale) + if err != nil { + return nil, err + } + returnImage := boolOrDefault(args.ReturnImage, true) + + // Capture or reuse baseline frame before pressing Return so we wait until + // the display leaves the login screen and skips transitional blank frames. + var baseHash string + var baseGray []uint8 + if prev, ok := s.screens.lastFrameForVM(args.VM); ok && !prev.blank { + baseHash = prev.hash + baseGray = prev.gray + } + + var typed hostReply + if err := s.host.Call(ctx, "host/console.typeSecret", map[string]any{"vm": args.VM, "setting": "login_password"}, &typed); err != nil { + return nil, err + } + var key hostReply + if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil { + return nil, err + } + + timeoutMS := args.TimeoutMS + if timeoutMS <= 0 { + timeoutMS = 20000 + } + stableMS := args.StableMS + if stableMS < 0 { + return nil, fmt.Errorf("%w: stable_ms must be >= 0", errInvalidParams) + } + if args.StableMS == 0 && args.TimeoutMS == 0 { + stableMS = 1500 + } + mode := "change_then_stable" + if baseHash == "" { + mode = "stable" + } + waitRes, err := s.waitScreenInternal(ctx, waitOptions{ + VM: args.VM, + BaselineHash: baseHash, + BaselineGray: baseGray, + Mode: mode, + TimeoutMS: timeoutMS, + MaxTimeoutMS: 60000, + StableMS: stableMS, + AcceptBlank: false, + Scale: scale, + ReturnImage: returnImage, + }) + if err != nil { + return nil, err + } + if waitRes.timedOut { + return formatWaitOutcome(waitRes, timeoutMS, scale, returnImage) + } + return formatScreenResult(waitRes.screen, waitRes.frame.hash, "Login password entered. Current screen attached.", scale, returnImage) +} + +func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) { + var args computerActionArgs + if err := decodeArguments(raw, &args); err != nil { + return nil, err + } + res, _, _, _, err := s.executeComputerAction(ctx, args) + return res, err +} + +func (s *Server) executeComputerAction(ctx context.Context, args computerActionArgs) (any, hostReply, cachedFrame, bool, error) { + if args.VM == "" { + return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: vm is required", errInvalidParams) + } + scale, err := validateScale(args.Scale) + if err != nil { + return nil, hostReply{}, cachedFrame{}, false, err + } + returnImage := boolOrDefault(args.ReturnImage, true) + if args.SettleMS < 0 || args.SettleMS > 30000 { + return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: settle_ms must be between 0 and 30000", errInvalidParams) + } + action := strings.ToLower(strings.TrimSpace(args.Action)) if action == "screenshot" { var screen hostReply if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } - return map[string]any{ - "content": []any{ - map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType}, - map[string]any{"type": "text", "text": fmt.Sprintf("Screen %dx%d, framebuffer %dx%d", screen.Width, screen.Height, screen.SourceWidth, screen.SourceHeight)}, - }, - }, nil + cf := s.screens.record(args.VM, screen) + summary := fmt.Sprintf("Screen %dx%d, framebuffer %dx%d", screen.Width, screen.Height, screen.SourceWidth, screen.SourceHeight) + res, err := formatScreenResult(screen, cf.hash, summary, scale, returnImage) + return res, screen, cf, true, err } if action == "zoom" { var screen hostReply if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } + cf := s.screens.record(args.VM, screen) cropped, width, height, err := cropJPEG(screen.Data, args.X, args.Y, args.Width, args.Height) if err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } - return map[string]any{"content": []any{map[string]any{"type": "image", "data": cropped, "mimeType": "image/jpeg"}, map[string]any{"type": "text", "text": fmt.Sprintf("Crop %dx%d", width, height)}}}, nil - } - if action == "type" { - var out hostReply - if err := s.host.Call(ctx, "host/console.type", map[string]any{"vm": args.VM, "text": args.Text}, &out); err != nil { - return nil, err + text := fmt.Sprintf("Crop %dx%d sha256=%s blank=%t", width, height, cf.hash, screen.Blank) + if !returnImage { + return map[string]any{"content": []any{map[string]any{"type": "text", "text": text}}}, screen, cf, true, nil } - return textResult(map[string]any{"characters": out.Characters}), nil - } - if action == "key" { - var out hostReply - if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": args.Key, "modifiers": args.Modifiers}, &out); err != nil { - return nil, err - } - return textResult(map[string]any{"ok": true}), nil + return map[string]any{"content": []any{ + map[string]any{"type": "image", "data": cropped, "mimeType": "image/jpeg"}, + map[string]any{"type": "text", "text": text}, + }}, screen, cf, true, nil } if action == "wait" { - timeout := time.Duration(args.Delta) * time.Millisecond + waitMS := args.DurationMS + if waitMS == 0 { + waitMS = args.Delta + } + timeout := time.Duration(waitMS) * time.Millisecond if timeout < 0 || timeout > 30*time.Second { - return nil, fmt.Errorf("%w: wait delta must be between 0 and 30000 milliseconds", errInvalidParams) + return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: wait duration_ms/delta must be between 0 and 30000 milliseconds", errInvalidParams) } timer := time.NewTimer(timeout) defer timer.Stop() select { case <-timer.C: case <-ctx.Done(): - return nil, ctx.Err() + return nil, hostReply{}, cachedFrame{}, false, ctx.Err() } - return textResult(map[string]any{"waited_ms": timeout.Milliseconds()}), nil + return textResult(map[string]any{"waited_ms": timeout.Milliseconds()}), hostReply{}, cachedFrame{}, false, nil } - button := "left" - buttonActions := map[string]string{"left_click": "left", "right_click": "right", "middle_click": "middle", "double_click": "left"} - if mapped, ok := buttonActions[action]; ok { - button = mapped + var preFrame cachedFrame + var hasPreFrame bool + if args.SettleMS > 0 { + preFrame, hasPreFrame = s.screens.lastFrameForVM(args.VM) + } + + var baseResult any + switch action { + case "type": + var out hostReply + if err := s.host.Call(ctx, "host/console.type", map[string]any{"vm": args.VM, "text": args.Text}, &out); err != nil { + return nil, hostReply{}, cachedFrame{}, false, err + } + baseResult = textResult(map[string]any{"characters": out.Characters}) + case "key": + var out hostReply + if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": args.Key, "modifiers": args.Modifiers}, &out); err != nil { + return nil, hostReply{}, cachedFrame{}, false, err + } + baseResult = textResult(map[string]any{"ok": true}) + case "left_click", "right_click", "middle_click", "double_click": + buttonActions := map[string]string{"left_click": "left", "right_click": "right", "middle_click": "middle", "double_click": "left"} + button := buttonActions[action] if err := s.movePointer(ctx, args); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } clicks := 1 if action == "double_click" { @@ -597,24 +761,22 @@ func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) for range clicks { var out hostReply if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "click", "button": button}, &out); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } } - return textResult(map[string]any{"ok": true}), nil - } - if action == "mouse_move" { + baseResult = textResult(map[string]any{"ok": true}) + case "mouse_move": if err := s.movePointer(ctx, args); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } - return textResult(map[string]any{"ok": true}), nil - } - if action == "left_click_drag" { + baseResult = textResult(map[string]any{"ok": true}) + case "left_click_drag": if err := s.movePointer(ctx, args); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } var out hostReply if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": true}, &out); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) defer cancel() @@ -630,50 +792,72 @@ func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) return err } defer func() { _ = release() }() - args.X, args.Y = args.X2, args.Y2 - if err := s.movePointer(ctx, args); err != nil { - return nil, err + dragEnd := args + dragEnd.X, dragEnd.Y = args.X2, args.Y2 + if err := s.movePointer(ctx, dragEnd); err != nil { + return nil, hostReply{}, cachedFrame{}, false, err } if err := release(); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } - return textResult(map[string]any{"ok": true}), nil - } - if action == "scroll" { + baseResult = textResult(map[string]any{"ok": true}) + case "scroll": if err := s.movePointer(ctx, args); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } var out hostReply if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "scroll", "delta": args.Delta, "horizontal": args.Horizontal}, &out); err != nil { - return nil, err + return nil, hostReply{}, cachedFrame{}, false, err } - return textResult(map[string]any{"ok": true}), nil + baseResult = textResult(map[string]any{"ok": true}) + default: + return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("unknown computer action %q", action) } - return nil, fmt.Errorf("unknown computer action %q", action) + + if args.SettleMS > 0 { + timeoutMS := args.TimeoutMS + if timeoutMS <= 0 { + timeoutMS = min(30000, max(args.SettleMS+5000, 10000)) + } + waitOpts := waitOptions{ + VM: args.VM, + Mode: "change_then_stable", + TimeoutMS: timeoutMS, + StableMS: args.SettleMS, + Tolerance: args.Tolerance, + AcceptBlank: args.AcceptBlank, + Scale: scale, + ReturnImage: returnImage, + } + if hasPreFrame { + waitOpts.BaselineHash = preFrame.hash + waitOpts.BaselineGray = preFrame.gray + } else { + waitOpts.Mode = "stable" + } + waitRes, waitErr := s.waitScreenInternal(ctx, waitOpts) + if waitErr != nil { + return nil, hostReply{}, cachedFrame{}, false, waitErr + } + res, fmtErr := formatWaitOutcome(waitRes, timeoutMS, scale, returnImage) + return res, waitRes.screen, waitRes.frame, waitRes.hasFrame, fmtErr + } + + return baseResult, hostReply{}, cachedFrame{}, false, nil } -func (s *Server) movePointer(ctx context.Context, args struct { - VM string `json:"vm"` - Action string `json:"action"` - X int `json:"x"` - Y int `json:"y"` - Width int `json:"width"` - Height int `json:"height"` - Button string `json:"button"` - Text string `json:"text"` - Key string `json:"key"` - Modifiers []string `json:"modifiers"` - X2 int `json:"x2"` - Y2 int `json:"y2"` - Delta int `json:"delta"` - Horizontal bool `json:"horizontal"` -}) error { +func (s *Server) movePointer(ctx context.Context, args computerActionArgs) error { if args.Width <= 0 || args.Height <= 0 { - var screen hostReply - if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - return err + if w, h, ok := s.screens.sizeForVM(args.VM); ok { + args.Width, args.Height = w, h + } else { + var screen hostReply + if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { + return err + } + s.screens.record(args.VM, screen) + args.Width, args.Height = screen.Width, screen.Height } - args.Width, args.Height = screen.Width, screen.Height } var out hostReply return s.host.Call(ctx, "host/console.pointer", map[string]any{ @@ -683,72 +867,42 @@ func (s *Server) movePointer(ctx context.Context, args struct { func (s *Server) waitForScreen(ctx context.Context, raw json.RawMessage) (any, error) { var args struct { - VM string `json:"vm"` - Baseline string `json:"baseline_sha256"` - TimeoutMS int `json:"timeout_ms"` - StableMS int `json:"stable_ms"` + VM string `json:"vm"` + Baseline string `json:"baseline_sha256"` + Mode string `json:"mode"` + TimeoutMS int `json:"timeout_ms"` + StableMS int `json:"stable_ms"` + Tolerance float64 `json:"tolerance"` + AcceptBlank bool `json:"accept_blank"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - if args.VM == "" { - return nil, fmt.Errorf("%w: vm is required", errInvalidParams) + scale, err := validateScale(args.Scale) + if err != nil { + return nil, err } - if args.TimeoutMS <= 0 { - args.TimeoutMS = 10000 + timeoutMS := args.TimeoutMS + if timeoutMS <= 0 { + timeoutMS = 10000 } - if args.TimeoutMS > 30000 || args.StableMS < 0 || args.StableMS > args.TimeoutMS { - return nil, fmt.Errorf("%w: timeout must be <= 30000 ms and stable_ms <= timeout_ms", errInvalidParams) + out, err := s.waitScreenInternal(ctx, waitOptions{ + VM: args.VM, + BaselineHash: args.Baseline, + Mode: args.Mode, + TimeoutMS: timeoutMS, + StableMS: args.StableMS, + Tolerance: args.Tolerance, + AcceptBlank: args.AcceptBlank, + Scale: scale, + ReturnImage: boolOrDefault(args.ReturnImage, true), + }) + if err != nil { + return nil, err } - waitCtx, cancel := context.WithTimeout(ctx, time.Duration(args.TimeoutMS)*time.Millisecond) - defer cancel() - deadline := time.NewTimer(time.Duration(args.TimeoutMS) * time.Millisecond) - defer deadline.Stop() - var previous string - stableSince := time.Time{} - for { - var screen hostReply - if err := s.host.Call(waitCtx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { - return toolTimeout(previous), nil - } - return nil, err - } - if err := waitCtx.Err(); err != nil { - if ctx.Err() == nil { - return toolTimeout(previous), nil - } - return nil, ctx.Err() - } - digest := sha256.Sum256([]byte(screen.Data)) - current := hex.EncodeToString(digest[:]) - if current != previous { - previous = current - stableSince = time.Now() - } - changed := args.Baseline == "" || current != args.Baseline - stable := args.StableMS == 0 || time.Since(stableSince) >= time.Duration(args.StableMS)*time.Millisecond - if changed && stable { - return map[string]any{"content": []any{ - map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType}, - map[string]any{"type": "text", "text": fmt.Sprintf("Screen changed or stable. sha256=%s", current)}, - }}, nil - } - timer := time.NewTimer(250 * time.Millisecond) - select { - case <-timer.C: - case <-ctx.Done(): - timer.Stop() - return nil, ctx.Err() - case <-deadline.C: - timer.Stop() - return toolTimeout(current), nil - } - } -} - -func toolTimeout(lastHash string) map[string]any { - return map[string]any{"isError": true, "content": []any{map[string]any{"type": "text", "text": "Timed out waiting for a screen change. Last frame sha256=" + lastHash}}} + return formatWaitOutcome(out, timeoutMS, scale, boolOrDefault(args.ReturnImage, true)) } func (s *Server) readResource(ctx context.Context, raw json.RawMessage) (any, error) { @@ -862,29 +1016,98 @@ func marshal(value any) (json.RawMessage, error) { var toolCatalog = []map[string]any{ {"name": "vm_list", "description": "List virtual machines visible to Reims-Go.", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": false}}, {"name": "vm_get", "description": "Read the state and capabilities of one virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, - {"name": "vm_start", "description": "Start a virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, - {"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, + {"name": "vm_start", "description": "Start a virtual machine and optionally wait until a non-blank screen appears or settles.", "inputSchema": objectSchema(map[string]any{ + "vm": map[string]any{"type": "string", "description": "VM reference (name or driver_id:name)."}, + "wait_until": map[string]any{"type": "string", "enum": []string{"none", "screen", "stable"}, "description": "Optional post-start wait: none (default), screen (first non-blank frame), or stable (non-blank frame settled for stable_ms)."}, + "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 180000, "description": "Wait timeout in milliseconds when wait_until != none (default 120000, max 180000)."}, + "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Required stability duration in milliseconds when wait_until is stable (default 2000)."}, + "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0) to reduce payload size."}, + "return_image": map[string]any{"type": "boolean", "description": "Whether to include the screenshot image (default true). Set false to return only sha256 and metadata."}, + }, []string{"vm"})}, + {"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})}, {"name": "snapshot_list", "description": "List restore points for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, {"name": "snapshot_create", "description": "Create a restore point for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})}, {"name": "snapshot_restore", "description": "Restore a restore point on an MCP-owned temporary VM.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})}, {"name": "session_create", "description": "Create an isolated CoW VM session for a test run. Restore-point bases are unavailable on the current host.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "isolation": map[string]any{"type": "string", "enum": []string{"clone", "live"}}}, []string{"vm"})}, {"name": "session_dispose", "description": "Dispose an MCP-owned temporary VM session.", "inputSchema": objectSchema(map[string]any{"session_id": map[string]any{"type": "string"}}, []string{"session_id"})}, - {"name": "vm_unlock", "description": "Enter the host-stored macOS login password and return the current screen.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, - {"name": "computer", "description": "Capture or interact with a virtual machine display.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string"}, - "action": map[string]any{"type": "string", "enum": []string{"screenshot", "left_click", "right_click", "middle_click", "double_click", "mouse_move", "left_click_drag", "scroll", "key", "type", "wait", "zoom"}}, - "x": map[string]any{"type": "integer"}, "y": map[string]any{"type": "integer"}, - "width": map[string]any{"type": "integer"}, "height": map[string]any{"type": "integer"}, - "button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}}, - "text": map[string]any{"type": "string"}, "key": map[string]any{"type": "string"}, - "modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "x2": map[string]any{"type": "integer"}, "y2": map[string]any{"type": "integer"}, - "delta": map[string]any{"type": "integer"}, "horizontal": map[string]any{"type": "boolean"}, + {"name": "vm_unlock", "description": "Enter the host-stored macOS login password, wait for the desktop to settle (skipping transitional blank frames), and return the screen.", "inputSchema": objectSchema(map[string]any{ + "vm": map[string]any{"type": "string", "description": "VM reference."}, + "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 60000, "description": "Max milliseconds to wait for the unlocked screen to settle (default 20000)."}, + "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Stability window in milliseconds after leaving the login screen (default 1500)."}, + "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, + "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the resulting screen image (default true)."}, + }, []string{"vm"})}, + {"name": "computer", "description": "Capture or interact with a virtual machine display. Coordinates are based on the most recent screenshot size; width and height may be omitted.", "inputSchema": objectSchema(map[string]any{ + "vm": map[string]any{"type": "string", "description": "VM reference."}, + "action": map[string]any{"type": "string", "enum": []string{"screenshot", "left_click", "right_click", "middle_click", "double_click", "mouse_move", "left_click_drag", "scroll", "key", "type", "wait", "zoom"}, "description": "Action to perform on the VM display."}, + "x": map[string]any{"type": "integer", "description": "X coordinate in the most recent screenshot pixel space."}, + "y": map[string]any{"type": "integer", "description": "Y coordinate in the most recent screenshot pixel space."}, + "width": map[string]any{"type": "integer", "description": "Reference width (optional for clicks/moves/scroll; defaults to the cached last screenshot width; required for zoom)."}, + "height": map[string]any{"type": "integer", "description": "Reference height (optional for clicks/moves/scroll; defaults to the cached last screenshot height; required for zoom)."}, + "button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}, "description": "Mouse button name."}, + "text": map[string]any{"type": "string", "description": "UTF-8 text to type for action=type."}, + "key": map[string]any{"type": "string", "description": "Key name for action=key (e.g. return, esc, tab, space, up, down, left, right, page_up, page_down, a-z, 0-9)."}, + "modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "Modifier keys for action=key (cmd/command, ctrl/control, alt/option, shift)."}, + "x2": map[string]any{"type": "integer", "description": "Drag destination X coordinate for action=left_click_drag."}, + "y2": map[string]any{"type": "integer", "description": "Drag destination Y coordinate for action=left_click_drag."}, + "duration_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Wait duration in milliseconds for action=wait (preferred over delta)."}, + "delta": map[string]any{"type": "integer", "description": "Scroll amount for action=scroll, or legacy wait duration in milliseconds for action=wait."}, + "horizontal": map[string]any{"type": "boolean", "description": "Scroll horizontally when true for action=scroll."}, + "settle_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "When >0 on input actions, wait for the screen to change and settle for settle_ms and return the resulting screenshot and sha256."}, + "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000, "description": "Optional timeout in milliseconds when settle_ms > 0."}, + "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1, "description": "Pixel-diff ratio tolerance (default 0.002 = 0.2%) used with settle_ms."}, + "accept_blank": map[string]any{"type": "boolean", "description": "Whether blank frames satisfy settle_ms (default false)."}, + "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, + "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the screenshot image (default true)."}, }, []string{"vm", "action"})}, - {"name": "wait_for_screen", "description": "Wait for a virtual machine screen frame to change or remain stable.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string"}, "baseline_sha256": map[string]any{"type": "string"}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}, - "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, + {"name": "computer_batch", "description": "Run a sequence of computer actions (plus wait_stable) in one round-trip, stopping on first error and returning the final frame and sha256.", "inputSchema": objectSchema(map[string]any{ + "vm": map[string]any{"type": "string", "description": "VM reference."}, + "actions": map[string]any{ + "type": "array", + "minItems": 1, + "description": "Ordered list of computer actions or wait_stable steps.", + "items": map[string]any{ + "type": "object", + "properties": map[string]any{ + "action": map[string]any{"type": "string", "enum": []string{"screenshot", "left_click", "right_click", "middle_click", "double_click", "mouse_move", "left_click_drag", "scroll", "key", "type", "wait", "zoom", "wait_stable"}, "description": "Step action name."}, + "x": map[string]any{"type": "integer"}, + "y": map[string]any{"type": "integer"}, + "width": map[string]any{"type": "integer"}, + "height": map[string]any{"type": "integer"}, + "button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}}, + "text": map[string]any{"type": "string"}, + "key": map[string]any{"type": "string"}, + "modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + "x2": map[string]any{"type": "integer"}, + "y2": map[string]any{"type": "integer"}, + "duration_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, + "delta": map[string]any{"type": "integer"}, + "horizontal": map[string]any{"type": "boolean"}, + "settle_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, + "baseline_sha256": map[string]any{"type": "string"}, + "mode": map[string]any{"type": "string", "enum": []string{"stable", "change", "change_then_stable"}}, + "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}, + "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, + "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1}, + "accept_blank": map[string]any{"type": "boolean"}, + }, + "required": []string{"action"}, + "additionalProperties": false, + }, + }, + "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0) for the final frame."}, + "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the final screenshot image (default true)."}, + }, []string{"vm", "actions"})}, + {"name": "wait_for_screen", "description": "Wait for a virtual machine screen frame to change or settle (ignoring blinking cursor noise). On timeout, returns the last frame with timed_out=true instead of an error.", "inputSchema": objectSchema(map[string]any{ + "vm": map[string]any{"type": "string", "description": "VM reference."}, + "baseline_sha256": map[string]any{"type": "string", "description": "Previous frame sha256 to compare against."}, + "mode": map[string]any{"type": "string", "enum": []string{"stable", "change", "change_then_stable"}, "description": "Wait mode: defaults to stable when baseline_sha256 is omitted, or change_then_stable when baseline_sha256 is provided."}, + "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000, "description": "Maximum wait duration in milliseconds (default 10000, max 30000)."}, + "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Required stability duration in milliseconds."}, + "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1, "description": "Fraction of 160x90 luma pixels differing by >16 to count as changed (default 0.002 = 0.2%)."}, + "accept_blank": map[string]any{"type": "boolean", "description": "When true, blank frames may satisfy the wait (default false)."}, + "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, + "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the final screenshot image (default true)."}, }, []string{"vm"})}, {"name": "guest_public_key", "description": "Create or return this plugin's SSH public key for explicit guest-side installation.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, {"name": "guest_wait_ready", "description": "Wait for guest SSH and report a host fingerprint that must be reviewed before trust.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}}, []string{"vm"})}, diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go index c79ec64..8a1730e 100644 --- a/internal/mcp/server_test.go +++ b/internal/mcp/server_test.go @@ -188,8 +188,8 @@ func TestScreenshotAndZoomReturnImages(t *testing.T) { } zoom := sendRequest(t, server, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"zoom","x":0,"y":0,"width":1,"height":1}}}`) zoomContent := parseResponse(t, zoom)["result"].(map[string]any)["content"].([]any) - if zoomContent[0].(map[string]any)["type"] != "image" || zoomContent[1].(map[string]any)["text"] != "Crop 1x1" { - t.Fatalf("zoom result missing cropped image: %s", zoom) + if zoomContent[0].(map[string]any)["type"] != "image" || !strings.HasPrefix(zoomContent[1].(map[string]any)["text"].(string), "Crop 1x1 sha256=") { + t.Fatalf("zoom result missing cropped image or sha256: %s", zoom) } } @@ -198,12 +198,12 @@ func TestVMUnlockNeverReturnsThePassword(t *testing.T) { host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretValue: password} server := New() server.BindHost(host) - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`) + response := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1","timeout_ms":500,"stable_ms":0}}}`) if strings.Contains(string(response), password) { t.Fatalf("vm_unlock leaked password in MCP response: %s", response) } - if len(host.calls) != 3 { - t.Fatalf("vm_unlock host calls = %d, want typeSecret, key and screenshot", len(host.calls)) + if len(host.calls) < 3 { + t.Fatalf("vm_unlock host calls = %d, want at least typeSecret, key and screenshot", len(host.calls)) } var secretParams map[string]any encoded, _ := json.Marshal(host.calls[0].params) @@ -240,8 +240,8 @@ func TestWaitForScreenAppliesTimeoutToHostCall(t *testing.T) { t.Fatalf("wait_for_screen exceeded its timeout: %s", elapsed) } result := parseResponse(t, response)["result"].(map[string]any) - if result["isError"] != true || !strings.Contains(result["content"].([]any)[0].(map[string]any)["text"].(string), "Timed out") { - t.Fatalf("wait_for_screen did not report its timeout: %s", response) + if result["isError"] == true || !strings.Contains(result["content"].([]any)[0].(map[string]any)["text"].(string), "timed_out=true") { + t.Fatalf("wait_for_screen timeout must return non-error timed_out=true: %s", response) } }