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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 21:53:54 +01:00
1 parent 599c891c00
commit 808747f9d2
10 files changed
+633 -52

No files matched your search

+215 -5
View File
@@ -69,12 +69,16 @@ func newTermRig(t *testing.T, clientType, capability string, isPTY bool) *termRi
t.Cleanup(unsub)
t.Cleanup(rig.s.Close)
// The device answers COMMAND_SHELL by opening a shell sub-connection.
// 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() {
select {
case <-rig.opened:
h.BindTerminalConn("1001", sub, isPTY)
case <-rig.stop:
for {
select {
case <-rig.opened:
h.BindTerminalConn("1001", sub, isPTY)
case <-rig.stop:
return
}
}
}()
return rig
@@ -149,6 +153,41 @@ 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}`)
@@ -557,3 +596,174 @@ func TestTerminalExecBootstrapHonoursCallTimeout(t *testing.T) {
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")
}
}