Files
SimpleRemoter/server/go/mcp/session.go
T
yuanyuanxianganddeepseek-flash 12b1bd4786 Feature(Go): MCP terminal sessions with a 256 KiB ring buffer
Add the server-side half of the terminal tools: a per-device session
table that claims the hub's single-viewer shell lease for MCP, and an
output ring that survives a timed-out request so a later poll can still
collect the command's result (terminal_exec itself arrives in M4b).

The ring keeps the newest 256 KiB of shell output, tracks absolute
offsets, and counts dropped bytes so callers can report truncation. A
sentinel scanner looks for the per-command done marker, skipping the
echoed command line and accepting Windows' negative error codes; its
scan position is incremental with a small overlap so a marker split
across TCP reads is still found.

Server implements hub.EventHandler and cmd subscribes it when the
endpoint is enabled; only the three terminal callbacks do work, and
OnTerminalData stays cheap on the TCP read loop (lookup, append, scan,
broadcast). Opening inserts the session before calling the hub so an
early OnTerminalReady cannot be lost, stale close events that race a
fresh open are ignored while the hub still holds the lease, and idle
sweeps verify session identity. The reaper and terminal_close land in
M4c.

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

280 lines
8.6 KiB
Go

package mcp
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// errNoDeviceHub means the endpoint was built without a device registry, so
// no shell can be opened. Mirrors the local tools' nil-Hub behaviour (-32000).
var errNoDeviceHub = errors.New("no device hub configured")
// terminalHub is the slice of *hub.Hub the session table needs. An interface
// keeps the table testable and documents that MCP never touches a terminal
// sub-connection directly — it goes through the hub's single-viewer lease.
type terminalHub interface {
OpenTerminalSession(deviceID string) error
CloseTerminalSession(deviceID string)
HasTerminalSession(deviceID string) bool
}
// sessionTable owns the MCP-created terminal sessions, keyed by device. A
// session is created before hub.OpenTerminalSession so OnTerminalReady (which
// can fire on another goroutine as soon as the client answers) always finds
// the object; a failed open rolls the entry back.
type sessionTable struct {
hub terminalHub
mu sync.Mutex
byDevice map[string]*termSession
}
func newSessionTable(h terminalHub) *sessionTable {
return &sessionTable{hub: h, byDevice: make(map[string]*termSession)}
}
func (t *sessionTable) get(deviceID string) *termSession {
t.mu.Lock()
defer t.mu.Unlock()
return t.byDevice[deviceID]
}
// errSessionClosed means the session disappeared while its open was in
// flight (shutdown or an explicit close raced it).
var errSessionClosed = errors.New("terminal session closed during open")
// open claims a shell for the device. ErrTerminalBusy comes back when a web
// console (or another MCP call) already holds it; the hub enforces the
// single-viewer lease, so v1 never pre-empts a human.
func (t *sessionTable) open(deviceID string) (*termSession, error) {
if t.hub == nil {
return nil, errNoDeviceHub
}
t.mu.Lock()
if _, ok := t.byDevice[deviceID]; ok {
t.mu.Unlock()
return nil, hub.ErrTerminalBusy
}
sess := newTermSession(deviceID)
// Until the hub call returns, any OnTerminalClosed for this device belongs
// to the viewer that just released the lease, not to this session.
sess.opening = true
t.byDevice[deviceID] = sess
t.mu.Unlock()
if err := t.hub.OpenTerminalSession(deviceID); err != nil {
t.mu.Lock()
delete(t.byDevice, deviceID)
t.mu.Unlock()
sess.mu.Lock()
sess.opening = false
sess.closed = true
sess.closeReason = "open failed"
sess.cond.Broadcast()
sess.mu.Unlock()
return nil, err
}
sess.mu.Lock()
sess.opening = false
sess.mu.Unlock()
// An explicit close (or shutdown) may have removed the entry while the hub
// call was in flight. The hub lease is ours by now, so release it instead
// of returning a session nobody can reach.
t.mu.Lock()
cur, ok := t.byDevice[deviceID]
t.mu.Unlock()
if !ok || cur != sess {
t.hub.CloseTerminalSession(deviceID)
return nil, errSessionClosed
}
return sess, nil
}
// ready records that the shell sub-conn is bound. Called from the hub's TCP
// read loop, so it must stay short (a mutex and a broadcast).
func (t *sessionTable) ready(deviceID string, isPTY bool) {
sess := t.get(deviceID)
if sess == nil {
return
}
sess.mu.Lock()
sess.isPTY = isPTY
sess.ready = true
sess.lastUsed = time.Now()
sess.cond.Broadcast()
sess.mu.Unlock()
}
// closed runs when the shell ends for any reason — device-side exit, sub-conn
// drop, or an explicit teardown. Waiters wake up and deliver whatever output
// is already buffered.
func (t *sessionTable) closed(deviceID, reason string) {
// A web console's teardown can race a fresh open: by the time this event is
// delivered, the hub lease may already belong to a new MCP session. The hub
// is the authority on whether a session still exists; if it does, the event
// described the previous viewer and must not touch ours.
if t.hub != nil && t.hub.HasTerminalSession(deviceID) {
return
}
t.mu.Lock()
sess, ok := t.byDevice[deviceID]
if !ok {
t.mu.Unlock()
return
}
sess.mu.Lock()
if sess.opening {
// Our own hub call has not returned yet, so any close for this device
// still refers to whoever held the lease before us.
sess.mu.Unlock()
t.mu.Unlock()
return
}
delete(t.byDevice, deviceID)
t.mu.Unlock()
sess.closed = true
sess.closeReason = reason
sess.cond.Broadcast()
sess.mu.Unlock()
}
// closeSession tears down the MCP-owned session for deviceID, if any. It is
// idempotent: a call for a device MCP does not own returns false and leaves
// the web console's session alone.
func (t *sessionTable) closeSession(deviceID string) bool {
return t.closeSessionIf(deviceID, nil)
}
// closeSessionIf closes the device's session only if the table still holds
// exactly want. The identity check matters for sweepIdle: between its scan
// and the close, the stale session can be replaced by a fresh one.
func (t *sessionTable) closeSessionIf(deviceID string, want *termSession) bool {
t.mu.Lock()
sess, ok := t.byDevice[deviceID]
if !ok || (want != nil && sess != want) {
t.mu.Unlock()
return false
}
delete(t.byDevice, deviceID)
t.mu.Unlock()
sess.mu.Lock()
sess.closed = true
sess.closeReason = "closed"
sess.cond.Broadcast()
sess.mu.Unlock()
if t.hub != nil {
// Fires OnTerminalClosed, which is a no-op now that the entry is gone.
t.hub.CloseTerminalSession(deviceID)
}
return true
}
// sweepIdle closes sessions whose last use is older than idle. Intended for
// the periodic reaper: a model that forgets terminal_close must not lock a
// human out of the device's shell.
//
// The M4c reaper must skip sessions with an in-flight command (pending !=
// nil): a quiet command (sleep, a slow download) still owns the lease and
// must not be reaped just because it printed nothing for a while.
func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int {
type staleEntry struct {
id string
sess *termSession
}
var stale []staleEntry
t.mu.Lock()
for id, sess := range t.byDevice {
sess.mu.Lock()
last := sess.lastUsed
sess.mu.Unlock()
if now.Sub(last) >= idle {
stale = append(stale, staleEntry{id, sess})
}
}
t.mu.Unlock()
n := 0
for _, e := range stale {
if t.closeSessionIf(e.id, e.sess) {
n++
}
}
return n
}
// closeAll drops every session; used at shutdown. The hub teardown is still
// best-effort because the TCP servers may already be stopping.
func (t *sessionTable) closeAll() {
t.mu.Lock()
ids := make([]string, 0, len(t.byDevice))
for id := range t.byDevice {
ids = append(ids, id)
}
t.mu.Unlock()
for _, id := range ids {
t.closeSession(id)
}
}
// sessionIDFallback numbers ids when crypto/rand is unavailable. It is only a
// last resort: ids are opaque to clients, and uniqueness matters, not secrecy.
var sessionIDFallback atomic.Uint32
func newSessionID() string {
var b [3]byte
if _, err := rand.Read(b[:]); err == nil {
return "s-" + hex.EncodeToString(b[:])
}
return fmt.Sprintf("s-%06x", sessionIDFallback.Add(1)&0xffffff)
}
// Server implements hub.EventHandler so the endpoint can observe shell
// traffic. Only the terminal events do work; the screen and lifecycle events
// are ignored (the web console owns those views).
var _ hub.EventHandler = (*Server)(nil)
func (s *Server) OnDeviceOnline(hub.DeviceInfo) {}
func (s *Server) OnDeviceOffline(string) {}
func (s *Server) OnDeviceUpdate(string, int, string) {}
func (s *Server) OnScreenFrame(string, []byte, bool) {}
func (s *Server) OnResolutionChange(string, int, int) {}
func (s *Server) OnCursorChange(string, byte, int, int) {}
func (s *Server) OnClipboardText(string, string) {}
func (s *Server) OnTerminalReady(deviceID string, isPTY bool) { s.sessions.ready(deviceID, isPTY) }
func (s *Server) OnTerminalClosed(deviceID, reason string) { s.sessions.closed(deviceID, reason) }
// OnTerminalData runs on the device's TCP read loop. It must never block:
// look up the session, strip the browser demux prefix, append to the ring,
// check the in-flight sentinel and wake any waiter. Sessions MCP did not
// create (the web console's) are dropped at the map lookup with no work.
func (s *Server) OnTerminalData(deviceID string, packet []byte) {
sess := s.sessions.get(deviceID)
if sess == nil {
return
}
if len(packet) >= len(protocol.TerminalBinaryMagic) &&
bytes.Equal(packet[:len(protocol.TerminalBinaryMagic)], protocol.TerminalBinaryMagic[:]) {
packet = packet[len(protocol.TerminalBinaryMagic):]
}
sess.mu.Lock()
if sess.closed {
sess.mu.Unlock()
return
}
sess.appendLocked(packet)
sess.scanPendingLocked()
sess.cond.Broadcast()
sess.mu.Unlock()
}