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

+86 -27
View File
@@ -22,8 +22,8 @@ var errNoDeviceHub = errors.New("no device hub configured")
// 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)
OpenTerminalSessionLease(deviceID string) (uint64, error)
CloseTerminalSessionLease(deviceID string, lease uint64) bool
HasTerminalSession(deviceID string) bool
SendToTerminal(deviceID string, data []byte) error
}
@@ -72,7 +72,8 @@ func (t *sessionTable) open(deviceID string) (*termSession, error) {
t.byDevice[deviceID] = sess
t.mu.Unlock()
if err := t.hub.OpenTerminalSession(deviceID); err != nil {
lease, err := t.hub.OpenTerminalSessionLease(deviceID)
if err != nil {
t.mu.Lock()
delete(t.byDevice, deviceID)
t.mu.Unlock()
@@ -87,6 +88,7 @@ func (t *sessionTable) open(deviceID string) (*termSession, error) {
sess.mu.Lock()
sess.opening = false
sess.lease = lease
sess.mu.Unlock()
// An explicit close (or shutdown) may have removed the entry while the hub
@@ -96,7 +98,7 @@ func (t *sessionTable) open(deviceID string) (*termSession, error) {
cur, ok := t.byDevice[deviceID]
t.mu.Unlock()
if !ok || cur != sess {
t.hub.CloseTerminalSession(deviceID)
t.hub.CloseTerminalSessionLease(deviceID, lease)
return nil, errSessionClosed
}
return sess, nil
@@ -192,63 +194,120 @@ func (t *sessionTable) closeSession(deviceID string) bool {
// 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 {
return t.closeIf(deviceID, want, func(*termSession) string { return "closed" })
}
// closeIf closes a session if decide says so. decide runs with both locks held
// (table then session), so it must read only session fields and lock nothing:
// the staleness reaper uses it to re-check under the same lock that deletes,
// closing the scan-then-close window where a poll could refresh the session.
// A returned "" cancels the close and nothing is touched.
func (t *sessionTable) closeIf(deviceID string, want *termSession, decide func(*termSession) string) 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()
reason := decide(sess)
if reason == "" {
sess.mu.Unlock()
t.mu.Unlock()
return false
}
delete(t.byDevice, deviceID)
wasClosed := sess.closed
lease := sess.lease
sess.closed = true
sess.closeReason = "closed"
sess.closeReason = reason
sess.cond.Broadcast()
sess.mu.Unlock()
t.mu.Unlock()
// A session that was already closed lost its hub lease when the close event
// arrived; the hub may since have handed a fresh shell to another viewer (a
// reconnected device). Only an explicit close of a live session may touch it.
if t.hub != nil && !wasClosed {
// Fires OnTerminalClosed, which is a no-op now that the entry is gone.
t.hub.CloseTerminalSession(deviceID)
// reconnected device). Only an explicit close of a live session may touch
// it, and even then only the lease MCP itself opened (the generation check
// in the hub), never whatever lease the device holds now.
if t.hub != nil && !wasClosed && lease != 0 {
t.hub.CloseTerminalSessionLease(deviceID, lease)
}
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.
// termBusyMax bounds how long one command may hold a session with nobody
// polling it. Without it a hung command — or a model that never comes back —
// would lock the device's single terminal slot forever. MFC reclaims at the
// same one-hour limit (McpServer.cpp:4674).
const termBusyMax = time.Hour
// sweepIdle closes sessions whose last use is older than idle, plus live
// commands that outlived termBusyMax. 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.
// A session with a live command (pending, not done) is skipped no matter how
// quiet it is: a sleep or a slow download still owns the lease and must not be
// reaped just because it printed nothing for a while. A session whose shell is
// already gone is reaped on idle alone — its only remaining value is the
// undelivered tail, and a model that never polls it must not pin the slot.
// A session that never became ready is left alone: its open is still waiting
// on a caller, which releases it (with a lease-checked close) on its own.
func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int {
type staleEntry struct {
type entry struct {
id string
sess *termSession
}
var stale []staleEntry
var candidates []entry
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})
}
candidates = append(candidates, entry{id, sess})
}
t.mu.Unlock()
n := 0
for _, e := range stale {
if t.closeSessionIf(e.id, e.sess) {
for _, e := range candidates {
if t.closeIf(e.id, e.sess, func(s *termSession) string {
return s.reclaimReasonLocked(now, idle)
}) {
n++
}
}
return n
}
// reclaimReasonLocked returns why the session should be dropped, or "" to keep
// it. Callers hold s.mu.
func (s *termSession) reclaimReasonLocked(now time.Time, idle time.Duration) string {
inactive := func() string {
return fmt.Sprintf(
"Terminal session was reclaimed after %s of inactivity; call terminal_exec again to open a new one", idle)
}
if !s.ready {
// Still waiting for the shell to bind; a caller holds this session and
// releases it when its own wait ends. Reaping here would kill a live
// open (and, if the lease changed hands meanwhile, someone else's).
return ""
}
if s.closed {
if now.Sub(s.lastUsed) >= idle {
return inactive()
}
return ""
}
if p := s.pending; p != nil && !p.done {
if now.Sub(p.busySince) >= termBusyMax {
return fmt.Sprintf(
"Terminal session was reclaimed after the command ran longer than %s; call terminal_exec again to open a new one", termBusyMax)
}
return ""
}
if now.Sub(s.lastUsed) >= idle {
return inactive()
}
return ""
}
// 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() {