package pluginsdk import ( "bufio" "bytes" "context" "encoding/json" "errors" "io" "testing" "time" "github.com/Nwflower/reims-go/pkg/pluginproto" ) // newFeatureServer starts a Server whose handshake advertises features and // returns it with the pipes a fake host answers on. The pipes are closed on // cleanup so a blocked write or read never keeps the test binary alive. func newFeatureServer(t *testing.T, features []string) (*Server, context.Context, *io.PipeReader, *io.PipeWriter) { t.Helper() inR, inW := io.Pipe() outR, outW := io.Pipe() t.Cleanup(func() { _ = inW.Close() _ = outR.Close() }) srv := NewWithIO(inR, outW) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) go func() { _ = srv.Serve(ctx) }() if err := writeRPCFrame(inW, map[string]any{ "jsonrpc": "2.0", "id": 1, "method": "plugin/initialize", "params": map[string]any{ "pluginId": "acme.tool", "pluginApi": "1.3.0", "dataDir": t.TempDir(), "features": features, }, }); err != nil { t.Fatalf("write initialize: %v", err) } // The features arrive with the handshake, so wait for it before calling. deadline := time.Now().Add(2 * time.Second) for srv.InitInfo().PluginID == "" && time.Now().Before(deadline) { time.Sleep(5 * time.Millisecond) } if srv.InitInfo().PluginID == "" { t.Fatal("the handshake never completed") } return srv, ctx, outR, inW } // answerHostCalls answers the SDK's Host API calls from a queue and reports // each request on got. Frames without a method are the SDK's own responses and // are skipped, and the loop keeps draining so the SDK never blocks on a write. func answerHostCalls(out *io.PipeReader, in *io.PipeWriter, replies []any, got chan<- envelope) { br := bufio.NewReader(out) queue := append([]any(nil), replies...) for { frame, err := readFrame(br) if err != nil { return } var req envelope if json.Unmarshal(frame, &req) != nil || req.Method == "" || len(req.ID) == 0 { continue } if got != nil { got <- req } if len(queue) == 0 { continue } result := queue[0] queue = queue[1:] raw, _ := json.Marshal(result) if err := writeRPCFrame(in, map[string]any{ "jsonrpc": "2.0", "id": json.RawMessage(req.ID), "result": json.RawMessage(raw), }); err != nil { return } } } func TestVMAndConsoleCallsUseTheContractShapes(t *testing.T) { srv, ctx, outR, inW := newFeatureServer(t, pluginproto.Features()) got := make(chan envelope, 16) go answerHostCalls(outR, inW, []any{ map[string]any{"vms": []map[string]any{{"vm": "d:dev", "name": "dev", "driver_id": "d", "state": "running", "authorized": true, "phase": "normal", "owned": false}}}, map[string]any{"ok": true}, map[string]any{"mime_type": "image/jpeg", "width": 640, "height": 360, "source_width": 2560, "source_height": 1440, "blank": false, "data": "AAA", "region": map[string]any{"x": 0, "y": 0, "width": 2560, "height": 1440}}, map[string]any{"ok": true}, map[string]any{"ok": true}, map[string]any{"characters": 5}, }, got) vms, err := srv.ListVMs(ctx) if err != nil || len(vms) != 1 || vms[0].Name != "dev" || !vms[0].Authorized { t.Fatalf("ListVMs = %+v, %v", vms, err) } if req := <-got; req.Method != "host/vm.list" { t.Fatalf("list request = %s", req.Method) } if err := srv.StartVM(ctx, "d:dev"); err != nil { t.Fatalf("StartVM: %v", err) } req := <-got var start pluginproto.VMParams if req.Method != "host/vm.start" || json.Unmarshal(req.Params, &start) != nil || start.VM != "d:dev" { t.Fatalf("start request = %s %s", req.Method, req.Params) } shot, err := srv.Screenshot(ctx, pluginproto.ScreenshotParams{ VM: "d:dev", MaxWidth: 640, Width: 1280, Height: 720, Region: &pluginproto.Region{X: 0, Y: 0, Width: 640, Height: 360}, }) if err != nil || shot.Width != 640 || shot.Region == nil || shot.Region.Width != 2560 { t.Fatalf("Screenshot = %+v, %v", shot, err) } req = <-got if req.Method != "host/console.screenshot" || !bytes.Contains(req.Params, []byte(`"max_width":640`)) || !bytes.Contains(req.Params, []byte(`"region"`)) { t.Fatalf("screenshot request = %s %s", req.Method, req.Params) } if err := srv.KeyDown(ctx, "d:dev", "cmd"); err != nil { t.Fatalf("KeyDown: %v", err) } req = <-got var key pluginproto.KeyParams if req.Method != "host/console.key" || json.Unmarshal(req.Params, &key) != nil || key.Key != "cmd" || key.Down == nil || !*key.Down { t.Fatalf("key request = %s %s", req.Method, req.Params) } if err := srv.Release(ctx, "d:dev", []string{"cmd"}, []string{"left"}); err != nil { t.Fatalf("Release: %v", err) } req = <-got var release pluginproto.ReleaseParams if req.Method != "host/console.release" || json.Unmarshal(req.Params, &release) != nil || len(release.Keys) != 1 || len(release.Buttons) != 1 { t.Fatalf("release request = %s %s", req.Method, req.Params) } n, err := srv.Type(ctx, "d:dev", "hello") if err != nil || n != 5 { t.Fatalf("Type = %d, %v", n, err) } if req := <-got; req.Method != "host/console.type" { t.Fatalf("type request = %s", req.Method) } } func TestUnadvertisedMethodIsRefusedBeforeItIsSent(t *testing.T) { srv, ctx, outR, inW := newFeatureServer(t, []string{"host.vm.list"}) got := make(chan envelope, 4) go answerHostCalls(outR, inW, nil, got) // The host serves host/console.screenshot, but this handshake does not // advertise it, so the SDK must not send the call. _, err := srv.Screenshot(ctx, pluginproto.ScreenshotParams{VM: "d:dev"}) var sdkErr *Error if !errors.As(err, &sdkErr) || sdkErr.Code != MethodNotFound { t.Fatalf("err = %v, want a method-not-found SDK error", err) } select { case req := <-got: t.Fatalf("the SDK sent %s to a host that does not advertise it", req.Method) default: } } func TestHostErrorCodeReachesTheCaller(t *testing.T) { srv, ctx, outR, inW := newFeatureServer(t, pluginproto.Features()) go func() { br := bufio.NewReader(outR) for { frame, err := readFrame(br) if err != nil { return } var req envelope if json.Unmarshal(frame, &req) != nil || req.Method == "" || len(req.ID) == 0 { continue } _ = writeRPCFrame(inW, map[string]any{ "jsonrpc": "2.0", "id": json.RawMessage(req.ID), "error": map[string]any{"code": InvalidParams, "message": `host/console.key: json: unknown field "hold_ms"`}, }) return } }() err := srv.KeyDown(ctx, "d:dev", "cmd") var sdkErr *Error if !errors.As(err, &sdkErr) || sdkErr.Code != InvalidParams { t.Fatalf("err = %v, want code %d", err, InvalidParams) } }