Files
SimpleRemoter/server/go/mcp/term.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

211 lines
6.7 KiB
Go

package mcp
import (
"bytes"
"strconv"
"sync"
"time"
)
// termRingCap bounds one session's retained output. A shell that floods the
// session (a log tail, a build) must not grow server memory without bound;
// the oldest bytes are dropped and the loss is surfaced as truncated output
// (design §6.3).
const termRingCap = 256 << 10
// pendingCmd is one command whose output is still being collected. It lives
// on the session so a timed-out terminal_exec can hand the same command back
// to a later polling call: the shell keeps running and its output keeps
// accumulating whether or not an HTTP request is attached.
type pendingCmd struct {
sentinel string // "__MCP_DONE_<6 hex>__"
nonce string // the 6-hex id inside sentinel, for output cleaning
cmdLine string // wire command line, removed from the PTY's echo
sentLine string // wire sentinel line, removed from the PTY's echo
start uint64 // absolute offset where this command's output begins
scanPos uint64 // absolute offset scanned so far (sentinel may span chunks)
deadline time.Time // when the current waiter gives up (the session survives)
done bool
exitCode int
outputEnd uint64 // absolute offset where the delivered output ends (sentinel start)
lost uint64 // this command's bytes evicted by the ring, cumulative
// firstChunk is true until the command's first delivery window is cleaned:
// the PTY echoes the input exactly once, at the start.
firstChunk bool
busySince time.Time // when the command started, for the M4c busy reaper
}
// termSession is the server-side view of one shell child. All mutable state
// is guarded by mu; cond wakes a waiter when data arrives, the command ends,
// or the session closes.
type termSession struct {
id string
deviceID string
createdAt time.Time
mu sync.Mutex
cond *sync.Cond
lastUsed time.Time
buf []byte // ring of termRingCap bytes
head int // index the next write goes to
size int // valid bytes in buf
total uint64 // bytes the shell produced, including dropped ones
delivered uint64 // absolute offset already handed to the client
droppedBytes uint64
isPTY bool
ready bool // OnTerminalReady seen
sawOutput bool // shell printed its first screen (prompt); bootstrap done
opening bool // hub.OpenTerminalSession still in flight
lease uint64 // hub lease generation; 0 until the open completes
closed bool
closeReason string
pending *pendingCmd // nil = idle
}
func newTermSession(deviceID string) *termSession {
now := time.Now()
s := &termSession{
id: newSessionID(),
deviceID: deviceID,
createdAt: now,
lastUsed: now,
buf: make([]byte, termRingCap),
}
s.cond = sync.NewCond(&s.mu)
return s
}
// baseLocked is the absolute offset of the oldest retained byte.
func (s *termSession) baseLocked() uint64 { return s.total - uint64(s.size) }
// appendLocked writes p into the ring, dropping the oldest bytes on overflow.
// total counts every byte the shell produced, including dropped ones, so the
// absolute offsets stay monotonic and a client can tell that it lost data.
func (s *termSession) appendLocked(p []byte) {
s.lastUsed = time.Now()
if len(p) == 0 {
return
}
s.sawOutput = true
if len(p) > len(s.buf) {
drop := len(p) - len(s.buf)
s.droppedBytes += uint64(drop)
s.total += uint64(drop)
p = p[drop:]
}
if overflow := s.size + len(p) - len(s.buf); overflow > 0 {
// The oldest overflow bytes are simply forgotten: head still marks
// the next write, and size now describes a shorter prefix.
s.droppedBytes += uint64(overflow)
s.size -= overflow
}
if n := copy(s.buf[s.head:], p); n < len(p) {
copy(s.buf, p[n:])
}
s.head = (s.head + len(p)) % len(s.buf)
s.size += len(p)
s.total += uint64(len(p))
}
// readLocked returns up to max bytes starting at absolute offset. lost is
// true when the requested offset predates the ring's oldest byte; the data
// then starts at the oldest retained byte instead.
func (s *termSession) readLocked(offset uint64, max int) (data []byte, next uint64, lost bool) {
if max <= 0 {
return nil, offset, false
}
base := s.baseLocked()
if offset < base {
offset = base
lost = true
}
if offset >= s.total {
return nil, s.total, lost
}
n := int(min(s.total-offset, uint64(max)))
idx := (s.head - s.size + int(offset-base)) % len(s.buf)
if idx < 0 {
idx += len(s.buf)
}
data = make([]byte, n)
first := copy(data, s.buf[idx:min(idx+n, len(s.buf))])
copy(data[first:], s.buf[:n-first])
return data, offset + uint64(n), lost
}
// scanPendingLocked looks for the in-flight command's sentinel in the bytes
// appended since the last look. A tail overlap is retained so a sentinel split
// across two TCP reads is still found.
func (s *termSession) scanPendingLocked() {
p := s.pending
if p == nil || p.done {
return
}
from := max(p.scanPos, s.baseLocked())
if from >= s.total {
return
}
data, next, _ := s.readLocked(from, int(s.total-from))
if code, start, _, ok := scanSentinel(data, p.sentinel); ok {
p.done = true
p.exitCode = code
// Deliver only up to the sentinel itself: the echoed sentinel line and
// the prompt printed after it are not the command's output.
p.outputEnd = from + uint64(start)
s.cond.Broadcast()
return
}
// Keep the last few bytes: the next chunk may complete a sentinel whose
// prefix sits just before the boundary.
const overlap = 64
if next > overlap {
next -= overlap
}
if next > p.scanPos {
p.scanPos = next
}
}
// scanSentinel finds the first occurrence of sentinel followed by a decimal
// exit code. The Windows %errorlevel% is signed (0xC000013A prints as
// -1073741510), so a leading '-' is accepted. start is where the sentinel
// begins (delivery stops there); end is one past the last digit.
//
// Echoed command lines contain the sentinel too but not the exit code
// ("__MCP_DONE_x__$?" / "__MCP_DONE_x__%errorlevel%"), so occurrences without
// digits are skipped rather than reported.
func scanSentinel(data []byte, sentinel string) (code, start, end int, ok bool) {
if sentinel == "" {
// Defensive: an empty needle matches everywhere and would spin the
// device read loop. Callers always mint a non-empty sentinel.
return 0, 0, 0, false
}
needle := []byte(sentinel)
from := 0
for {
idx := bytes.Index(data[from:], needle)
if idx < 0 {
return 0, 0, 0, false
}
idx += from
rest := data[idx+len(needle):]
i := 0
if i < len(rest) && rest[i] == '-' {
i++
}
digits := i
for i < len(rest) && rest[i] >= '0' && rest[i] <= '9' {
i++
}
if i > digits {
if n, err := strconv.Atoi(string(rest[:i])); err == nil {
return n, idx, idx + len(needle) + i, true
}
}
from = idx + len(needle)
}
}