Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 56 additions & 5 deletions pkgs/chat/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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:]...)
Expand All @@ -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(),
),
)
Expand Down Expand Up @@ -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
}
Expand Down
99 changes: 99 additions & 0 deletions pkgs/chat/session_cleanup_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading