Files
SimpleRemoter/server/go/mcp/tools_term_test.go
T
yuanyuanxianganddeepseek-flash 808747f9d2 Feature(Go): terminal_close, idle sweep and legacy-client guard
Add the terminal_close tool so a caller can release a shell session
explicitly instead of waiting for it to age out. The tool is idempotent
for the session it names, rejects a session_id that does not match the
live session with -32002, and runs without the per-device lock so it can
interrupt a terminal_exec call that is still polling on the same device.

Give hub leases a generation counter: the generation is bumped when a
pending lease is created and carried across a device re-login. MCP-side
closes pass the generation, so a stale session can no longer tear down a
shell a human operator opened after the device reconnected. The reaper
runs on a 30 s ticker (shortened when TermIdle is smaller), skips
sessions that are still opening, and reclaims idle sessions as well as
commands overdue past the one-hour busy cap.

The pre-bind terminal-close path in cmd no longer closes
unconditionally; it touches only a pending lease, because an unbound
sub-connection carries no lease identity and may be a stale orphan.

Covered by unit tests for close semantics, lock exemption, reaper
lifecycle and lease-generation ownership, plus a live run against a
Debug ghost: close before and during a command, reopen, idle reap and
mismatched-id rejection all behave as specified.

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

770 lines
25 KiB
Go

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. The
// loop keeps answering, so a test can close a session and reopen at once.
go func() {
for {
select {
case <-rig.opened:
h.BindTerminalConn("1001", sub, isPTY)
case <-rig.stop:
return
}
}
}()
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))
}
// callClose runs terminal_close directly on the handler, bypassing the HTTP
// layer's device lock (which the handler must ignore anyway).
func (r *termRig) callClose(args string) (terminalCloseOutput, *rpcError) {
r.t.Helper()
res, rerr := r.s.callTerminalClose(context.Background(), json.RawMessage(args))
if rerr != nil {
return terminalCloseOutput{}, rerr
}
tr, ok := res.(toolResult)
if !ok {
r.t.Fatalf("unexpected close result type %T", res)
}
if len(tr.Content) != 1 || tr.Content[0].Text != "closed" {
r.t.Fatalf("close content = %+v", tr.Content)
}
out, ok := tr.StructuredContent.(terminalCloseOutput)
if !ok {
r.t.Fatalf("unexpected close structured content %T", tr.StructuredContent)
}
return out, nil
}
// runToCompletion runs one command through the rig to its sentinel.
func (r *termRig) runToCompletion(command, output string) termCall {
r.t.Helper()
ch := r.callAsync(fmt.Sprintf(`{"id":"1001","command":%q,"timeout_ms":5000}`, command))
_, nonce := r.nextCommandWire()
r.feed("@" + "echo off & " + command + "\r\n" + output + "\r\n__MCP_DONE_" + nonce + "__0\r\n")
res := r.wait(ch)
if res.err != nil || !res.out.Done {
r.t.Fatalf("runToCompletion(%q) = %+v / %v", command, res.out, res.err)
}
return res
}
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)
}
}
// terminal_close releases the MCP-owned session and is idempotent: a second
// close (or a close after a reap) still answers closed instead of an error.
func TestTerminalCloseIsIdempotent(t *testing.T) {
rig := newTermRig(t, "", "", true)
sid := rig.runToCompletion("echo hello", "hello").out.SessionID
out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
if rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
if rig.h.HasTerminalSession("1001") {
t.Fatal("closed session still holds the hub lease")
}
out, rerr = rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
if rerr != nil || !out.Closed {
t.Fatalf("second close = %+v / %v", out, rerr)
}
}
func TestTerminalCloseRejectsMismatchedSession(t *testing.T) {
rig := newTermRig(t, "", "", true)
rig.runToCompletion("echo hello", "hello")
_, rerr := rig.callClose(`{"id":"1001","session_id":"s-000000"}`)
if rerr == nil || rerr.Code != CodeOffline || !strings.Contains(rerr.Message, "mismatch") {
t.Fatalf("mismatched close = %+v", rerr)
}
if rig.s.sessions.get("1001") == nil {
t.Fatal("mismatched close removed the session")
}
}
func TestTerminalCloseRejectsBadArgs(t *testing.T) {
rig := newTermRig(t, "", "", true)
for _, args := range []string{
`{"session_id":"s-abcdef"}`, // missing id
`{"id":"abc","session_id":"s-abcdef"}`, // id not decimal
`{"id":"1001"}`, // missing session_id
} {
if _, rerr := rig.callClose(args); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("%s: %+v", args, rerr)
}
}
}
// A terminal_close that lands while terminal_exec is waiting must wake that
// call: it delivers the bytes buffered so far and reports the shell gone.
func TestTerminalCloseInterruptsRunningCommand(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":5000}`)
_, _ = rig.nextCommandWire()
rig.feed("partial output\r\n")
sess := rig.s.sessions.get("1001")
if sess == nil {
t.Fatal("session missing while the command runs")
}
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sess.id)); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("exec after close: %v", res.err)
}
if res.out.Stdout != "partial output" || !res.out.Done {
t.Fatalf("exec after close = %+v, want the buffered tail", res.out)
}
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
t.Fatalf("exit code = %+v, want -1", res.out.ExitCode)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
}
// With no waiter, close discards the tail but still releases the device slot:
// the next poll reports the session gone rather than serving stale bytes.
func TestTerminalCloseWithoutWaiterReleasesSlot(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`)
_, _ = 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("orphan\r\n")
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
if rig.h.HasTerminalSession("1001") {
t.Fatal("closed session still holds the hub lease")
}
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("poll after close = %+v", res.err)
}
}
// A closed session must not keep the device slot: the very next command opens
// a fresh shell immediately.
func TestTerminalCloseAllowsImmediateReopen(t *testing.T) {
rig := newTermRig(t, "", "", true)
sid := rig.runToCompletion("echo one", "one").out.SessionID
if _, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil {
t.Fatalf("close: %v", rerr)
}
start := time.Now()
res := rig.runToCompletion("echo two", "two")
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("reopen took %v, want under 1s", elapsed)
}
if res.out.SessionID == sid {
t.Fatalf("reopen reused the closed session id %q", sid)
}
if res.out.Stdout != "two" {
t.Fatalf("reopen output = %q", res.out.Stdout)
}
}
// terminal_close only knows MCP's own table: a shell the web console holds has
// no MCP session, so the call is a no-op for the hub lease.
func TestTerminalCloseLeavesBrowserSessionAlone(t *testing.T) {
rig := newTermRig(t, "", "", true)
if err := rig.h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("browser open: %v", err)
}
if out, rerr := rig.callClose(`{"id":"1001","session_id":"s-abcdef"}`); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if !rig.h.HasTerminalSession("1001") {
t.Fatal("terminal_close released a browser-held lease")
}
}
// The HTTP layer must not make terminal_close wait on the per-device lock:
// an in-flight terminal_exec holds it for the whole call timeout.
func TestTerminalCloseIgnoresDeviceLock(t *testing.T) {
rig := newTermRig(t, "", "", true)
rig.runToCompletion("echo hello", "hello") // the session stays open after a finished command
sess := rig.s.sessions.get("1001")
if sess == nil {
t.Fatal("session missing")
}
if _, ok := rig.s.locks.tryAcquire("1001", "terminal_exec"); !ok {
t.Fatal("could not take the device lock")
}
defer rig.s.locks.release("1001")
if _, rerr := rig.s.callTool(context.Background(), json.RawMessage(
fmt.Sprintf(`{"name":"terminal_close","arguments":{"id":"1001","session_id":%q}}`, sess.id))); rerr != nil {
t.Fatalf("close through tools/call: %v", rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("close through tools/call did not release the session")
}
}