package mcp import ( "context" "encoding/json" "fmt" "net" "strings" "testing" "time" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // termRig is a live MCP server plus a hub whose device's shell answers every // open request immediately. Tests drive the shell by feeding OnTerminalData // packets, i.e. exactly what cmd/main.go delivers from the TCP read loop. type termRig struct { t *testing.T s *Server h *hub.Hub main *connection.Context sub *connection.Context writes chan []byte opened chan struct{} stop chan struct{} } func newTermRig(t *testing.T, clientType, capability string, isPTY bool) *termRig { t.Helper() h := hub.New() main := &connection.Context{RemoteAddr: "10.0.0.1:4000"} main.Info.ClientType = clientType // The hub closes the shell sub-conn 500 ms after teardown; a real net.Conn // keeps that path from dereferencing nil. shellConn, peer := net.Pipe() t.Cleanup(func() { _ = shellConn.Close(); _ = peer.Close() }) sub := &connection.Context{RemoteAddr: "10.0.0.1:4001", Conn: shellConn} rig := &termRig{ t: t, h: h, main: main, sub: sub, writes: make(chan []byte, 64), opened: make(chan struct{}, 4), stop: make(chan struct{}), } h.SetSender(func(ctx *connection.Context, data []byte) error { switch ctx { case main: if len(data) == 1 && data[0] == protocol.CommandShell { select { case rig.opened <- struct{}{}: default: } } case sub: select { case rig.writes <- append([]byte(nil), data...): default: } } return nil }) h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: capability}, main) rig.s = New(Config{Token: testToken, Hub: h}) t.Cleanup(func() { close(rig.stop) }) // Subscribe like cmd/main.go does, so OnTerminalReady/Data/Closed flow. unsub := h.Subscribe(rig.s) t.Cleanup(unsub) t.Cleanup(rig.s.Close) // The device answers COMMAND_SHELL by opening a shell sub-connection. go func() { select { case <-rig.opened: h.BindTerminalConn("1001", sub, isPTY) case <-rig.stop: } }() return rig } type termCall struct { out terminalExecOutput err *rpcError } func (r *termRig) callAsync(args string) <-chan termCall { ch := make(chan termCall, 1) go func() { res, rerr := r.s.callTerminalExec(context.Background(), json.RawMessage(args)) if rerr != nil { ch <- termCall{err: rerr} return } tr, ok := res.(toolResult) if !ok { ch <- termCall{err: errf(CodeInternal, "unexpected result type %T", res)} return } out, ok := tr.StructuredContent.(terminalExecOutput) if !ok { ch <- termCall{err: errf(CodeInternal, "unexpected structured content %T", tr.StructuredContent)} return } ch <- termCall{out: out} }() return ch } func (r *termRig) wait(ch <-chan termCall) termCall { r.t.Helper() select { case c := <-ch: return c case <-time.After(5 * time.Second): r.t.Fatal("timed out waiting for the tool call") return termCall{} } } // nextCommandWire returns the next write to the shell that carries a sentinel // and the nonce embedded in it. func (r *termRig) nextCommandWire() (wire, nonce string) { r.t.Helper() deadline := time.After(5 * time.Second) for { select { case b := <-r.writes: s := string(b) i := strings.Index(s, "__MCP_DONE_") if i < 0 { continue } rest := s[i+len("__MCP_DONE_"):] j := strings.Index(rest, "__") if j <= 0 { continue } return s, rest[:j] case <-deadline: r.t.Fatal("timed out waiting for the command wire") return "", "" } } } func (r *termRig) feed(text string) { r.s.OnTerminalData("1001", termPacket(text)) } func TestTerminalExecRunsCommand(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":5000}`) wire, nonce := rig.nextCommandWire() if !strings.HasPrefix(wire, "@echo off & echo hello\r\necho __MCP_DONE_"+nonce+"__%errorlevel%\r\n") { t.Fatalf("wire = %q", wire) } // ConPTY: the first line is the echoed command; the real output follows. rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n") res := rig.wait(ch) if res.err != nil { t.Fatalf("call failed: %v", res.err) } out := res.out if out.Stdout != "hello" || !out.Done || out.ExitCode == nil || *out.ExitCode != 0 { t.Fatalf("out = %+v", out) } if !out.IsPTY || out.Reused || out.Truncated || out.DroppedBytes != 0 { t.Fatalf("flags = %+v", out) } if !strings.HasPrefix(out.SessionID, "s-") { t.Fatalf("session id = %q", out.SessionID) } if out.ElapsedMS < 0 { t.Fatalf("elapsed = %d", out.ElapsedMS) } } func TestTerminalExecTimeoutThenPoll(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`) _, nonce := rig.nextCommandWire() res := rig.wait(ch) if res.err != nil { t.Fatalf("first call: %v", res.err) } if res.out.Done || res.out.Stdout != "" { t.Fatalf("timeout result = %+v", res.out) } sid := res.out.SessionID rig.feed("part1\r\n") ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid)) res = rig.wait(ch) if res.err != nil { t.Fatalf("poll 1: %v", res.err) } if res.out.Done || res.out.Stdout != "part1\n" { t.Fatalf("poll 1 = %+v", res.out) } if res.out.SessionID != sid { t.Fatalf("poll 1 session id = %q, want %q", res.out.SessionID, sid) } rig.feed("part2\r\n__MCP_DONE_" + nonce + "__3\r\n") ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid)) res = rig.wait(ch) if res.err != nil { t.Fatalf("poll 2: %v", res.err) } if !res.out.Done || res.out.Stdout != "part2" || res.out.ExitCode == nil || *res.out.ExitCode != 3 { t.Fatalf("poll 2 = %+v", res.out) } // The command is drained; polling an idle session is a caller mistake. ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid)) res = rig.wait(ch) if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "idle") { t.Fatalf("idle poll = %+v", res.err) } } func TestTerminalExecBusyWhileRunning(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`) _, nonce := rig.nextCommandWire() if res := rig.wait(ch); res.err != nil || res.out.Done { t.Fatalf("first call = %+v / %v", res.out, res.err) } ch = rig.callAsync(`{"id":"1001","command":"echo again","timeout_ms":100}`) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeBusy { t.Fatalf("busy call = %+v", res.err) } // Finish the first command so cleanup does not tear down a running shell. rig.feed("__MCP_DONE_" + nonce + "__0\r\n") } func TestTerminalExecRejectsNonPTY(t *testing.T) { rig := newTermRig(t, "", "", false) ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":1000}`) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "PTY") { t.Fatalf("non-PTY = %+v", res.err) } if rig.s.sessions.get("1001") != nil { t.Fatal("rejected session still in the table") } if rig.h.HasTerminalSession("1001") { t.Fatal("rejected session still holds the hub lease") } } func TestTerminalExecUnknownSession(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","session_id":"s-abcdef","timeout_ms":100}`) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") { t.Fatalf("unknown session = %+v", res.err) } } func TestTerminalExecRejectsBadArgs(t *testing.T) { rig := newTermRig(t, "", "", true) cases := []string{ `{"id":"1001","timeout_ms":100}`, // poll without session_id `{"id":"1001","command":"a\nb","timeout_ms":100}`, // control char `{"command":"echo hi","timeout_ms":100}`, // missing id `{"id":"abc","command":"echo hi","timeout_ms":100}`, // id not decimal } for _, args := range cases { ch := rig.callAsync(args) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeInvalidParams { t.Fatalf("%s: %+v", args, res.err) } } select { case b := <-rig.writes: t.Fatalf("rejected command was written to the shell: %q", b) default: } } func TestTerminalExecAPKCapabilityGate(t *testing.T) { rig := newTermRig(t, "APK", "0400", true) // no CLIENT_CAP_TERMINAL (0x8000) ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "too old") { t.Fatalf("APK gate = %+v", res.err) } } func TestTerminalExecAPKWithTerminalCap(t *testing.T) { rig := newTermRig(t, "APK", "8400", true) // 0x8000 | 0x0400 ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":5000}`) wire, nonce := rig.nextCommandWire() // POSIX PTY: PS1 is cleared first and the sentinel uses $?. if !strings.HasPrefix(wire, "PS1=\r\necho hi\r\necho __MCP_DONE_"+nonce+"__$?\r\n") { t.Fatalf("POSIX wire = %q", wire) } rig.feed("PS1=\r\necho hi\r\nhi\r\n__MCP_DONE_" + nonce + "__0\r\n") res := rig.wait(ch) if res.err != nil { t.Fatalf("APK exec: %v", res.err) } if res.out.Stdout != "hi" || !res.out.Done { t.Fatalf("APK out = %+v", res.out) } } func TestTerminalExecMACRejected(t *testing.T) { rig := newTermRig(t, "MAC", "", true) ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`) res := rig.wait(ch) if res.err == nil || res.err.Code != CodeUnsupported { t.Fatalf("MAC = %+v", res.err) } } func TestTerminalExecTruncatesOnLineBoundary(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":5000,"max_output_bytes":1024}`) _, nonce := rig.nextCommandWire() var payload strings.Builder for i := 0; i < 300; i++ { fmt.Fprintf(&payload, "line-%03d-xxxxxxxxxxxxxx\r\n", i) } payload.WriteString("__MCP_DONE_" + nonce + "__0\r\n") rig.feed(payload.String()) var got strings.Builder const wantLines = 300 for i := 0; i < 100; i++ { res := rig.wait(ch) if res.err != nil { t.Fatalf("window %d: %v", i, res.err) } got.WriteString(res.out.Stdout) if res.out.ExitCode == nil || *res.out.ExitCode != 0 { t.Fatalf("window %d exit = %+v", i, res.out) } if !res.out.Done { t.Fatalf("window %d: command should already be done", i) } if !res.out.Truncated { break } if len(res.out.Stdout) > 1024 { t.Fatalf("window %d exceeded max_output_bytes: %d", i, len(res.out.Stdout)) } ch = rig.callAsync(fmt.Sprintf( `{"id":"1001","session_id":%q,"timeout_ms":5000,"max_output_bytes":1024}`, res.out.SessionID)) } lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n") if len(lines) != wantLines { t.Fatalf("got %d lines, want %d", len(lines), wantLines) } for i, line := range lines { if want := fmt.Sprintf("line-%03d-xxxxxxxxxxxxxx", i); line != want { t.Fatalf("line %d = %q, want %q", i, line, want) } } } // A shell that dies mid-command keeps its undelivered output in the session: // the device is offline, but the next poll must still collect the tail. func TestTerminalExecDrainsAfterClose(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`) _, _ = rig.nextCommandWire() first := rig.wait(ch) if first.err != nil || first.out.Done { t.Fatalf("first call = %+v / %v", first.out, first.err) } sid := first.out.SessionID rig.feed("partial output\r\n") // The device goes away: the hub releases the shell, then the main conn. rig.h.CloseTerminalSession("1001") rig.h.Unregister("1001") ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid)) res := rig.wait(ch) if res.err != nil { t.Fatalf("drain poll: %v", res.err) } if res.out.Stdout != "partial output" || !res.out.Done { t.Fatalf("drain = %+v", res.out) } if res.out.ExitCode == nil || *res.out.ExitCode != -1 { t.Fatalf("closed exit code = %+v", res.out.ExitCode) } if res.out.SessionID != sid { t.Fatalf("session id = %q, want %q", res.out.SessionID, sid) } // Fully delivered: the ended session is released, so the offline host now // reports it as gone instead of serving it forever. ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid)) res = rig.wait(ch) if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") { t.Fatalf("post-drain poll = %+v", res.err) } } // Closing with more than max_output_bytes buffered must still deliver every // line across polls, even though the shell is gone after the first window. func TestTerminalExecCloseKeepsTruncatedTail(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":50}`) _, _ = rig.nextCommandWire() first := rig.wait(ch) if first.err != nil || first.out.Done { t.Fatalf("first call = %+v / %v", first.out, first.err) } sid := first.out.SessionID var payload strings.Builder for i := 0; i < 100; i++ { fmt.Fprintf(&payload, "line-%03d-xxxxxxxx\r\n", i) } rig.feed(payload.String()) rig.h.CloseTerminalSession("1001") var got strings.Builder ch = rig.callAsync(fmt.Sprintf( `{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid)) for i := 0; i < 20; i++ { res := rig.wait(ch) if res.err != nil { t.Fatalf("window %d: %v", i, res.err) } got.WriteString(res.out.Stdout) if !res.out.Done { t.Fatalf("window %d should be done: %+v", i, res.out) } if res.out.ExitCode == nil || *res.out.ExitCode != -1 { t.Fatalf("window %d exit = %+v", i, res.out.ExitCode) } if !res.out.Truncated { break } ch = rig.callAsync(fmt.Sprintf( `{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid)) } lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n") if len(lines) != 100 { t.Fatalf("got %d lines, want 100", len(lines)) } for i, line := range lines { if want := fmt.Sprintf("line-%03d-xxxxxxxx", i); line != want { t.Fatalf("line %d = %q, want %q", i, line, want) } } } // The PTY echo can arrive after the command call timed out. The poll must still // recognise it as the echo and not print the command line as output. func TestTerminalExecPollStripsLateEcho(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":50}`) _, nonce := rig.nextCommandWire() first := rig.wait(ch) if first.err != nil || first.out.Done || first.out.Stdout != "" { t.Fatalf("first = %+v / %v", first.out, first.err) } rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n") ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, first.out.SessionID)) res := rig.wait(ch) if res.err != nil { t.Fatalf("poll: %v", res.err) } if res.out.Stdout != "hello" || !res.out.Done { t.Fatalf("poll = %+v, want the echo removed", res.out) } } // A finished command with nothing left to collect must not answer "busy": its // stale pending entry is dropped and the new command runs. func TestTerminalExecCommandAfterDrainedFinish(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"slow","timeout_ms":50}`) _, nonce := rig.nextCommandWire() rig.feed("early\r\n") first := rig.wait(ch) if first.err != nil || first.out.Done || first.out.Stdout != "early\n" { t.Fatalf("first = %+v / %v", first.out, first.err) } // The sentinel arrives after the call returned; everything it ends was // already delivered, so the session is effectively idle. rig.feed("__MCP_DONE_" + nonce + "__0\r\n") ch = rig.callAsync(`{"id":"1001","command":"echo next","timeout_ms":5000}`) _, nonce2 := rig.nextCommandWire() rig.feed("next-out\r\n__MCP_DONE_" + nonce2 + "__0\r\n") res := rig.wait(ch) if res.err != nil { t.Fatalf("next command: %v", res.err) } if res.out.Stdout != "next-out" || !res.out.Done { t.Fatalf("next command = %+v", res.out) } } // A command naming a session that already ended must not destroy the tail it // still holds; the caller is told to poll instead. func TestTerminalExecEndedSessionAsksForPoll(t *testing.T) { rig := newTermRig(t, "", "", true) ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`) _, _ = rig.nextCommandWire() first := rig.wait(ch) if first.err != nil || first.out.Done { t.Fatalf("first = %+v / %v", first.out, first.err) } sid := first.out.SessionID rig.feed("tail\r\n") rig.h.CloseTerminalSession("1001") ch = rig.callAsync(fmt.Sprintf( `{"id":"1001","session_id":%q,"command":"echo again","timeout_ms":200}`, sid)) if res := rig.wait(ch); res.err == nil || !strings.Contains(res.err.Message, sid) || !strings.Contains(res.err.Message, "session_id") { t.Fatalf("command on an ended session = %+v, want a pointer to drain it by id", res.err) } ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid)) res := rig.wait(ch) if res.err != nil { t.Fatalf("drain after ended command: %v", res.err) } if res.out.Stdout != "tail" || !res.out.Done { t.Fatalf("drain = %+v", res.out) } } // The POSIX bootstrap wait is capped by the call's own timeout, not always 2 s. func TestTerminalExecBootstrapHonoursCallTimeout(t *testing.T) { rig := newTermRig(t, "APK", "8400", true) // POSIX: the bootstrap wait applies start := time.Now() ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":300}`) _, _ = rig.nextCommandWire() res := rig.wait(ch) if res.err != nil { t.Fatalf("call: %v", res.err) } if elapsed := time.Since(start); elapsed > 1500*time.Millisecond { t.Fatalf("bootstrap ignored the call timeout: %v", elapsed) } }