Files
SimpleRemoter/server/go/mcp/session_test.go
T
yuanyuanxianganddeepseek-flash 599c891c00 Feature(Go): terminal_exec with sentinel cleaning and polling
Implement M4b of the Go MCP minimal plan: terminal_exec runs one command in a
device's persistent shell and polls the rest of a timed-out command.

Wire format follows the Win32 server: ConPTY sends "@echo off & <cmd>" plus a
sentinel line carrying %errorlevel%; POSIX PTY clears PS1 and uses $?. Output
cleaning is a byte-faithful port of the MFC stages (ANSI, CRLF, echoed input,
sentinel remnants) and is shared by commands and polls.

A timed-out call leaves the session and the command running; the next call with
only session_id delivers from the cursor it left. Per-window output is bounded
by max_output_bytes, truncated on a line boundary, and ring evictions are
reported as dropped_bytes. When the shell dies mid-command the session stays
reachable until its buffered tail has been polled, then is released without
touching the hub, which may already belong to a new viewer.

Adds ClientCapTerminal (0x8000) for the Android gate; older APKs, macOS and
legacy non-PTY shells are refused with -32005.

Co-Authored-By: deepseek-flash
2026-11-12 21:38:00 +01:00

411 lines
12 KiB
Go

package mcp
import (
"bytes"
"errors"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
)
// terminalTestServer builds a server backed by a real hub with one online
// device (1001) whose shell commands are accepted by a no-op sender.
func terminalTestServer(t *testing.T) (*Server, *hub.Hub) {
t.Helper()
h := hub.New()
h.SetSender(func(*connection.Context, []byte) error { return nil })
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
s := New(Config{Token: testToken, Hub: h})
t.Cleanup(s.Close)
return s, h
}
// termPacket wraps shell output the way cmd/main.go publishes it.
func termPacket(s string) []byte {
p := make([]byte, 4+len(s))
copy(p, "TRM1")
copy(p[4:], s)
return p
}
func TestTermRingTrimsOldest(t *testing.T) {
sess := newTermSession("1001")
payload := make([]byte, 1<<20)
for i := range payload {
payload[i] = byte(i*7 + 1)
}
sess.mu.Lock()
sess.appendLocked(payload)
data, next, lost := sess.readLocked(0, 1<<20)
size, total, dropped := sess.size, sess.total, sess.droppedBytes
sess.mu.Unlock()
if size != termRingCap {
t.Fatalf("retained = %d, want cap %d", size, termRingCap)
}
if total != 1<<20 {
t.Fatalf("total = %d, want %d", total, 1<<20)
}
if dropped != uint64((1<<20)-termRingCap) {
t.Fatalf("dropped = %d, want %d", dropped, (1<<20)-termRingCap)
}
if !lost {
t.Fatal("reading from 0 after overflow should report lost data")
}
if len(data) != termRingCap || next != 1<<20 {
t.Fatalf("read len/next = %d/%d, want %d/%d", len(data), next, termRingCap, 1<<20)
}
if want := payload[(1<<20)-termRingCap:]; !bytes.Equal(data, want) {
t.Fatal("retained data is not the newest window of the stream")
}
}
func TestTermRingWraps(t *testing.T) {
sess := newTermSession("1001")
var want []byte
for i := range 10 {
chunk := bytes.Repeat([]byte{byte('a' + i)}, 40<<10)
want = append(want, chunk...)
sess.mu.Lock()
sess.appendLocked(chunk)
sess.mu.Unlock()
}
sess.mu.Lock()
base, total := sess.baseLocked(), sess.total
data, next, lost := sess.readLocked(0, termRingCap)
tail, _, _ := sess.readLocked(total-100, 100)
sess.mu.Unlock()
if !lost {
t.Fatal("reading from 0 after wraparound should report lost data")
}
if base != uint64(len(want)-termRingCap) {
t.Fatalf("base = %d, want %d", base, len(want)-termRingCap)
}
if next != total {
t.Fatalf("next = %d, want total %d", next, total)
}
if wantWin := want[len(want)-termRingCap:]; !bytes.Equal(data, wantWin) {
t.Fatal("wrapped ring does not return the newest window in order")
}
if wantTail := want[len(want)-100:]; !bytes.Equal(tail, wantTail) {
t.Fatal("tail read is not the newest bytes")
}
}
func TestScanSentinel(t *testing.T) {
const sentinel = "__MCP_DONE_abc123__"
cases := []struct {
name string
in string
code int
ok bool
}{
{"plain", "x\r\n" + sentinel + "0\r\n", 0, true},
{"nonzero", sentinel + "42", 42, true},
{"negative", sentinel + "-1073741510", -1073741510, true},
{"echo then real", sentinel + "%errorlevel%\r\n" + sentinel + "1\r\n", 1, true},
{"posix echo then real", sentinel + "$?\n" + sentinel + "0\n", 0, true},
{"command echo only", sentinel + "%errorlevel%", 0, false},
{"absent", "hello world", 0, false},
{"empty", "", 0, false},
}
for _, tc := range cases {
code, start, end, ok := scanSentinel([]byte(tc.in), sentinel)
if ok != tc.ok {
t.Errorf("%s: ok = %v, want %v", tc.name, ok, tc.ok)
continue
}
if ok && code != tc.code {
t.Errorf("%s: code = %d, want %d", tc.name, code, tc.code)
}
if ok && (start < 0 || start >= end || end > len(tc.in)) {
t.Errorf("%s: start/end = %d/%d, want 0<=start<end<=%d", tc.name, start, end, len(tc.in))
}
}
if _, _, _, ok := scanSentinel([]byte("123"), ""); ok {
t.Fatal("empty sentinel must never match")
}
}
func TestOpenSessionWaitsForReadyAndBuffers(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
if !strings.HasPrefix(sess.id, "s-") || len(sess.id) != 8 {
t.Fatalf("session id = %q, want s-XXXXXX", sess.id)
}
sess.mu.Lock()
ready := sess.ready
sess.mu.Unlock()
if ready {
t.Fatal("session must not be ready before OnTerminalReady")
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
ready, isPTY := sess.ready, sess.isPTY
sess.mu.Unlock()
if !ready || !isPTY {
t.Fatalf("after ready: ready=%v isPTY=%v", ready, isPTY)
}
// The browser demux prefix is stripped; a raw chunk is accepted as-is.
s.OnTerminalData("1001", termPacket("hello "))
s.OnTerminalData("1001", []byte("world"))
sess.mu.Lock()
data, next, lost := sess.readLocked(0, 1<<10)
sess.mu.Unlock()
if string(data) != "hello world" || next != 11 || lost {
t.Fatalf("buffered = %q next=%d lost=%v", data, next, lost)
}
// Simulate a genuine teardown: the hub releases the lease first, then its
// event reaches the MCP subscriber.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
sess.mu.Lock()
closed, reason := sess.closed, sess.closeReason
sess.mu.Unlock()
if !closed || reason != "closed" {
t.Fatalf("session state: closed=%v reason=%q", closed, reason)
}
}
func TestOpenSessionBusyWithBrowser(t *testing.T) {
s, h := terminalTestServer(t)
_ = s
// The web console opens the shell first (same call it makes today).
if err := h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("browser open: %v", err)
}
tbl := newSessionTable(h)
if _, err := tbl.open("1001"); !errors.Is(err, hub.ErrTerminalBusy) {
t.Fatalf("open while browser holds it = %v, want ErrTerminalBusy", err)
}
if tbl.get("1001") != nil {
t.Fatal("failed open must not leave a session marker behind")
}
// After the browser closes, MCP can claim the shell.
h.CloseTerminalSession("1001")
if _, err := tbl.open("1001"); err != nil {
t.Fatalf("open after browser closed: %v", err)
}
}
func TestTerminalSentinelWakesPending(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
sess.mu.Unlock()
s.OnTerminalData("1001", termPacket("dir\r\nfile.txt\r\n__MCP_DONE_abc123__1\r\n"))
sess.mu.Lock()
p := sess.pending
done, code, end := p.done, p.exitCode, p.outputEnd
sess.mu.Unlock()
if !done || code != 1 {
t.Fatalf("pending: done=%v code=%d", done, code)
}
if end == 0 {
t.Fatal("sentinel end offset not recorded")
}
}
func TestSessionIdleSweep(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
sess.mu.Lock()
sess.lastUsed = time.Now().Add(-time.Hour)
sess.mu.Unlock()
if n := s.sessions.sweepIdle(time.Now(), time.Minute); n != 1 {
t.Fatalf("swept = %d, want 1", n)
}
if s.sessions.get("1001") != nil {
t.Fatal("idle session still in the table")
}
sess.mu.Lock()
closed := sess.closed
sess.mu.Unlock()
if !closed {
t.Fatal("swept session not marked closed")
}
}
func TestSessionTableCloseAll(t *testing.T) {
s, h := terminalTestServer(t)
h.Register(&hub.Device{ID: "2002", PeerIP: "10.0.0.2"},
&connection.Context{RemoteAddr: "10.0.0.2:54321"})
for _, id := range []string{"1001", "2002"} {
if _, err := s.sessions.open(id); err != nil {
t.Fatalf("open %s: %v", id, err)
}
}
s.Close()
for _, id := range []string{"1001", "2002"} {
if s.sessions.get(id) != nil {
t.Fatalf("session %s survived Close", id)
}
}
}
// A close event emitted by the previous viewer's teardown must not delete a
// session whose open already owns the hub lease. Regression for the race where
// the web console closes as MCP opens.
func TestStaleTerminalCloseKeepsSession(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
// The hub still holds our (new) pending lease, so this event describes the
// viewer that just went away.
s.OnTerminalClosed("1001", "closed")
if got := s.sessions.get("1001"); got != sess {
t.Fatal("stale close event removed the fresh session")
}
sess.mu.Lock()
closed := sess.closed
sess.mu.Unlock()
if closed {
t.Fatal("stale close event marked the fresh session closed")
}
// Once the hub really has no session, the event is genuine.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != nil {
t.Fatal("genuine close event did not remove the session")
}
}
func TestClosedIgnoredWhileOpening(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.opening = true
tbl.byDevice["1001"] = sess
tbl.closed("1001", "closed")
if tbl.get("1001") != sess {
t.Fatal("close event during open removed the session")
}
sess.mu.Lock()
sess.opening = false
sess.mu.Unlock()
tbl.closed("1001", "closed")
if tbl.get("1001") != nil {
t.Fatal("close after open finished did not remove the session")
}
}
// sweepIdle snapshots sessions before closing them; if the entry was replaced
// in between, the close must not take out the new session.
func TestSweepSkipsReplacedSession(t *testing.T) {
tbl := newSessionTable(nil)
old := newTermSession("1001")
old.lastUsed = old.lastUsed.Add(-time.Hour)
fresh := newTermSession("1001")
tbl.byDevice["1001"] = fresh
if tbl.closeSessionIf("1001", old) {
t.Fatal("closeSessionIf closed a session it did not own")
}
if tbl.get("1001") != fresh {
t.Fatal("replacement session was removed")
}
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
t.Fatalf("swept = %d, want 0", n)
}
}
// A draining session's close must not tear down a hub lease that a reconnected
// viewer has since opened: the shell the session referred to is already gone.
func TestCloseOfEndedSessionLeavesNewHubLease(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
if _, rerr := sess.beginCommand("ab12cd34", "cmd", ""); rerr != nil {
t.Fatalf("begin: %v", rerr)
}
s.OnTerminalData("1001", termPacket("out\r\n"))
// The shell ends with output the client has not polled yet: the session
// stays in the table so the tail can still be collected. The hub event is
// delivered to subscribers by cmd/main.go's wiring.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != sess {
t.Fatal("draining session was dropped")
}
// Another viewer (or the same device after reconnecting) gets a fresh lease.
if err := h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("new lease: %v", err)
}
if !h.HasTerminalSession("1001") {
t.Fatal("new lease not established")
}
if !s.sessions.closeSessionIf("1001", sess) {
t.Fatal("close did not remove the draining session")
}
if !h.HasTerminalSession("1001") {
t.Fatal("closing the ended session tore down the new viewer's shell")
}
}
func TestSentinelSplitAcrossChunks(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
sess.mu.Unlock()
// The sentinel prefix ends more than 64 bytes before the chunk boundary,
// so the retained overlap is what lets the second chunk complete it.
s.OnTerminalData("1001", termPacket(strings.Repeat("x", 100)+"__MCP_DONE_ab"))
s.OnTerminalData("1001", termPacket("c123__3\r\n"))
sess.mu.Lock()
p := sess.pending
done, code := p.done, p.exitCode
sess.mu.Unlock()
if !done || code != 3 {
t.Fatalf("split sentinel: done=%v code=%d", done, code)
}
}