From 32b6eb8cda5f78544dcb7404aa75402ae28c8002 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 17:21:29 -0600 Subject: [PATCH] fix(chat): deregister sessions via cleanup middleware instead of p.Wait() (#4515) --- pkgs/chat/main.go | 61 +++++++++++++++++-- pkgs/chat/session_cleanup_test.go | 99 +++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 pkgs/chat/session_cleanup_test.go diff --git a/pkgs/chat/main.go b/pkgs/chat/main.go index dcd8bb64c..a27f5b4bf 100644 --- a/pkgs/chat/main.go +++ b/pkgs/chat/main.go @@ -121,6 +121,7 @@ type app struct { sendMu sync.Mutex progs []sender dispatches map[sender]*recipientQueue + sessions map[ssh.Session]sender } // register adds a running program and its ordered delivery worker. @@ -137,6 +138,49 @@ func (a *app) register(p sender) { a.dispatches[p] = newRecipientQueue(p) } +// registerSession binds p to its session s in addition to registering it, +// so the session's end can deregister exactly this program. +func (a *app) registerSession(s ssh.Session, p sender) { + a.register(p) + a.mu.Lock() + defer a.mu.Unlock() + if a.sessions == nil { + a.sessions = make(map[ssh.Session]sender) + } + a.sessions[s] = p +} + +// deregisterSession removes the program bound to s, if any. It runs when +// the session's handler chain has returned — for the bubbletea middleware +// that is after p.Run() has finished and the program has been killed — so +// removal is tied to this session's completion, never to the shared +// connection context (which survives individual sessions on multiplexed +// connections) and never to p.Wait() (whose finished channel is only +// created inside Run, so a Wait started by the handler can block on a nil +// channel forever; #4515). +func (a *app) deregisterSession(s ssh.Session) { + a.mu.Lock() + p, ok := a.sessions[s] + if ok { + delete(a.sessions, s) + } + a.mu.Unlock() + if ok { + a.remove(p) + } +} + +// sessionCleanupMiddleware deregisters the session's program after the +// inner handler chain returns. wish composes middleware outside-in from +// the end of the WithMiddleware list, so this must be listed after the +// bubbletea middleware for its post-handler step to run after p.Run(). +func (a *app) sessionCleanupMiddleware(next ssh.Handler) ssh.Handler { + return func(s ssh.Session) { + next(s) + a.deregisterSession(s) + } +} + // send enqueues a message for each running program in a single broadcast // order. A recipient can have one in-flight Send and at most // recipientQueueDepth queued messages; a full queue prunes that recipient. @@ -163,6 +207,11 @@ func (a *app) send(msg tea.Msg) { func (a *app) remove(p sender) { a.mu.Lock() var dispatch *recipientQueue + for s, q := range a.sessions { + if q == p { + delete(a.sessions, s) + } + } for i, q := range a.progs { if q == p { a.progs = append(a.progs[:i], a.progs[i+1:]...) @@ -185,6 +234,7 @@ func newApp() *app { wish.WithHostKeyPath(".ssh/term_info_ed25519"), wish.WithMiddleware( bm.MiddlewareWithProgramHandler(a.ProgramHandler, termenv.ANSI256), + a.sessionCleanupMiddleware, lm.Middleware(), ), ) @@ -245,11 +295,12 @@ func (a *app) ProgramHandler(s ssh.Session) *tea.Program { model.id = s.User() p := tea.NewProgram(model, tea.WithOutput(s), tea.WithInput(s)) - a.register(p) - go func() { - p.Wait() - a.remove(p) - }() + // Deregistration happens in sessionCleanupMiddleware when this + // session's handler chain returns after p.Run() — not via p.Wait(), + // whose finished channel Run creates only after this handler has + // returned, so an early Wait can block on a nil channel forever and + // leak the registry entry (#4515). + a.registerSession(s, p) return p } diff --git a/pkgs/chat/session_cleanup_test.go b/pkgs/chat/session_cleanup_test.go new file mode 100644 index 000000000..c6f8fb93a --- /dev/null +++ b/pkgs/chat/session_cleanup_test.go @@ -0,0 +1,99 @@ +// lane-scratch: code-e lane-e-20261110-scratch task 14746 +package main + +import ( + "testing" + + "github.com/charmbracelet/ssh" +) + +// fakeSession is a distinct ssh.Session identity per instance. The +// embedded nil interface satisfies ssh.Session; the registry and the +// cleanup middleware use a session only as an identity key and pass it +// through, never calling its methods. +type fakeSession struct { + ssh.Session + id int +} + +func registrySize(a *app) int { + a.mu.RLock() + defer a.mu.RUnlock() + return len(a.progs) +} + +// TestSessionCleanupDeregistersOnHandlerReturn covers the #4515 waiter +// lifecycle: the program stays registered while the session's handler +// chain runs, and the cleanup middleware removes it when the chain +// returns (after p.Run() completes) — no p.Wait() goroutine involved. +func TestSessionCleanupDeregistersOnHandlerReturn(t *testing.T) { + a := &app{} + p := &fakeProg{} + s := &fakeSession{id: 1} + a.registerSession(s, p) + + handler := a.sessionCleanupMiddleware(func(sess ssh.Session) { + if n := registrySize(a); n != 1 { + t.Fatalf("registry has %d programs while session is live, want 1", n) + } + }) + handler(s) + + if n := registrySize(a); n != 0 { + t.Fatalf("registry has %d programs after session handler returned, want 0", n) + } +} + +// TestSessionCleanupLeavesOtherSessions covers the Codex finding on +// PR #4521: sessions sharing one SSH connection are independent — +// ending one session must deregister only its own program while a +// still-live session on the same connection keeps its registration. +func TestSessionCleanupLeavesOtherSessions(t *testing.T) { + a := &app{} + p1, p2 := &fakeProg{}, &fakeProg{} + s1, s2 := &fakeSession{id: 1}, &fakeSession{id: 2} + a.registerSession(s1, p1) + a.registerSession(s2, p2) + + a.deregisterSession(s1) + + if n := registrySize(a); n != 1 { + t.Fatalf("registry has %d programs after one session ended, want 1", n) + } + a.mu.RLock() + remaining := a.progs[0] + a.mu.RUnlock() + if remaining != sender(p2) { + t.Fatal("the surviving registration is not the live session's program") + } + + // Deregistering an unknown or already-removed session is a no-op. + a.deregisterSession(s1) + a.deregisterSession(&fakeSession{id: 99}) + if n := registrySize(a); n != 1 { + t.Fatalf("registry has %d programs after no-op deregistrations, want 1", n) + } +} + +// TestRemoveDropsSessionBinding ensures the queue-prune path (remove) +// cannot leave a stale session binding behind for a later +// deregisterSession to act on. +func TestRemoveDropsSessionBinding(t *testing.T) { + a := &app{} + p := &fakeProg{} + s := &fakeSession{id: 1} + a.registerSession(s, p) + + a.remove(p) + + a.mu.RLock() + bindings := len(a.sessions) + a.mu.RUnlock() + if bindings != 0 { + t.Fatalf("%d session bindings remain after remove, want 0", bindings) + } + a.deregisterSession(s) + if n := registrySize(a); n != 0 { + t.Fatalf("registry has %d programs, want 0", n) + } +}