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

+35
View File
@@ -188,3 +188,38 @@ func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) {
t.Fatalf("retry after re-register: %v, want nil", err)
}
}
// A lease generation is an ownership proof: a stale opener whose pending
// request a re-login dropped cannot close the lease someone else acquired
// afterwards, while the current owner can still close its own.
func TestCloseTerminalSessionLeaseIgnoresRenewedLease(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
stale, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("first open: %v", err)
}
// Re-login drops the pending request without an OnTerminalClosed event.
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
current, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("second open: %v", err)
}
if h.CloseTerminalSessionLease("dev", stale) {
t.Fatal("a stale generation closed the renewed lease")
}
if !h.HasTerminalSession("dev") {
t.Fatal("renewed lease was torn down by the stale close")
}
if !h.CloseTerminalSessionLease("dev", current) {
t.Fatal("the owning generation could not close its lease")
}
if h.HasTerminalSession("dev") {
t.Fatal("lease still held after the owner closed it")
}
}