Skip to content
Draft
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
15 changes: 12 additions & 3 deletions cmd/root/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s
if err != nil {
return err
}
// Under --listen the initial tab is attached to the serving manager too;
// detach it when the tab is closed, like tabs made by createSessionSpawner.
tuiCleanup := detachOnCleanup(f.listenSM, sess.ID, cleanup)

applyTheme(f.theme)
opts, err := f.buildAppOpts(args)
Expand All @@ -602,7 +605,7 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s
}
runErr := func() error {
if f.lean {
return f.runLeanTUI(ctx, rt, sess, cleanup, args, opts...)
return f.runLeanTUI(ctx, rt, sess, tuiCleanup, args, opts...)
}
if cassettePath != "" {
// Record keystrokes and clicks alongside the model traffic so a
Expand All @@ -611,9 +614,9 @@ func (f *runExecFlags) runOrExec(ctx context.Context, out *cli.Printer, args []s
rec = recorder.New(m)
return rec
}
return runTUIWrapped(ctx, rt, sess, b.Spawner(rt), cleanup, tuiOptions, wrap, opts...)
return runTUIWrapped(ctx, rt, sess, b.Spawner(rt), tuiCleanup, tuiOptions, wrap, opts...)
}
return runTUI(ctx, rt, sess, b.Spawner(rt), cleanup, tuiOptions, opts...)
return runTUI(ctx, rt, sess, b.Spawner(rt), tuiCleanup, tuiOptions, opts...)
}()
if rec != nil && rec.HasInput() {
writeGeneratedTUITest(ctx, out, rec, cassettePath, agentFileName)
Expand Down Expand Up @@ -1397,6 +1400,12 @@ func (f *runExecFlags) createSessionSpawner(agentSource config.Source, sessStore

// Create cleanup function
cleanup := func() {
// Under --listen the session was attached to the serving manager
// (see recallCoordinatorOpt); release it when the tab goes away so
// the runtime, event log and injector are not retained.
if f.listenSM != nil {
f.listenSM.DetachRuntime(newSess.ID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocking] This only detaches tabs created by createSessionSpawner. The initial tab is attached separately by startSessionCoordinator (run_listen.go:75–80), but runOrExec still passes the backend's cleanup directly to the TUI (run.go:559–616). Open a second tab under --listen and close the initial one: the supervisor removes the tab, but its runtime and follow-up injector remain registered and /api/sessions still lists it as active. Wire detachment into the initial tab's cleanup too, and cover both paths with a tab-close regression test.

}
stopToolSets(spawnCtx, t)
}

Expand Down
12 changes: 12 additions & 0 deletions cmd/root/run_listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,15 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri
sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage)
}, nil
}

// detachOnCleanup wraps cleanup so the session is also detached from the
// --listen session manager sm (nil when not listening) before it runs.
func detachOnCleanup(sm *server.SessionManager, sessionID string, cleanup func()) func() {
if sm == nil {
return cleanup
}
return func() {
sm.DetachRuntime(sessionID)
cleanup()
}
}
32 changes: 32 additions & 0 deletions cmd/root/run_listen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/docker/docker-agent/pkg/app"
"github.com/docker/docker-agent/pkg/config"
"github.com/docker/docker-agent/pkg/runtime"
"github.com/docker/docker-agent/pkg/server"
"github.com/docker/docker-agent/pkg/session"
msgtypes "github.com/docker/docker-agent/pkg/tui/messages"
)
Expand Down Expand Up @@ -83,3 +84,34 @@ func TestStartSessionCoordinatorRejectsNonLocalListener(t *testing.T) {
require.ErrorContains(t, err, "require --auth-token")
assert.Nil(t, opt)
}

func TestDetachOnCleanupReleasesListenSession(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := session.NewInMemorySessionStore()
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))
rt := &recallRuntime{store: store}

sm := server.NewSessionManager(ctx, nil, store, 0, &config.RuntimeConfig{})
flags := &runExecFlags{listenSM: sm}
_ = flags.recallCoordinatorOpt(ctx, rt, sess)
require.Len(t, sm.GetActiveSessions(), 1)
require.NotNil(t, rt.recallHandler)

cleaned := false
detachOnCleanup(sm, sess.ID, func() { cleaned = true })()

assert.True(t, cleaned, "wrapped cleanup must still run")
assert.Empty(t, sm.GetActiveSessions(), "closed initial tab must leave the active session list")
assert.Nil(t, rt.recallHandler, "recall handler must be cleared")
}

func TestDetachOnCleanupWithoutListenKeepsCleanup(t *testing.T) {
t.Parallel()

cleaned := false
detachOnCleanup(nil, "id", func() { cleaned = true })()
assert.True(t, cleaned)
}
77 changes: 77 additions & 0 deletions pkg/server/server_attached_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -761,3 +761,80 @@ func TestAttachedServer_StatusWaitTimesOut(t *testing.T) {
defer resp.Body.Close()
assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
}

func TestSessionManager_DetachRuntimeReleasesAttachedSession(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := session.NewInMemorySessionStore()
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))

sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)
sm.RegisterFollowUpInjector(sess.ID, func(context.Context, string) {})
require.Len(t, sm.GetActiveSessions(), 1)

sm.DetachRuntime(sess.ID)

assert.Empty(t, sm.GetActiveSessions())
_, injected := sm.followUpInjectors.Load(sess.ID)
assert.False(t, injected, "follow-up injector must be released")

// The persisted session survives the detach.
_, err := store.GetSession(ctx, sess.ID)
require.NoError(t, err)

// Detaching an unknown or already detached session is a no-op.
sm.DetachRuntime(sess.ID)
}

// recallFakeRuntime records the handler set through SetRecallHandler.
type recallFakeRuntime struct {
fakeRuntime

handler runtime.RecallHandler
}

func (r *recallFakeRuntime) SetRecallHandler(h runtime.RecallHandler) { r.handler = h }

func TestSessionManager_DetachRuntimeClearsRecallHandler(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := session.NewInMemorySessionStore()
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))

rt := &recallFakeRuntime{}
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
sm.AttachRuntime(ctx, sess.ID, rt, sess)
require.NotNil(t, rt.handler)

sm.DetachRuntime(sess.ID)

assert.Nil(t, rt.handler, "recall handler installed by AttachRuntime must be cleared")
}

func TestSessionManager_DetachRuntimeAllowsReattach(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := session.NewInMemorySessionStore()
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))

sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
src := func(ctx context.Context, send func(any)) { <-ctx.Done() }

sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)
sm.RegisterEventSource(sess.ID, src)
require.True(t, sm.HasEventSource(sess.ID))

sm.DetachRuntime(sess.ID)
assert.False(t, sm.HasEventSource(sess.ID), "detach must tear down the event log")

sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)
sm.RegisterEventSource(sess.ID, src)
assert.True(t, sm.HasEventSource(sess.ID), "same ID must be able to register a new event source after reattach")
}
44 changes: 44 additions & 0 deletions pkg/server/session_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,19 @@ func (sm *SessionManager) dropEventLog(sessionID string) {
}
}

// releaseEventLog tears down sessionID's event log, if any, without
// tombstoning the ID: unlike dropEventLog it is for a session that merely
// stops being attached (see DetachRuntime), so the same ID can be attached
// again and register a fresh event source.
func (sm *SessionManager) releaseEventLog(sessionID string) {
sm.eventLogsMu.Lock()
defer sm.eventLogsMu.Unlock()
if pe, ok := sm.eventLogs.Load(sessionID); ok {
pe.cancel()
sm.eventLogs.Delete(sessionID)
}
}

// appendSessionEvent appends event to sessionID's event log, creating the
// log on demand (see ensureEventLog) if this is the first out-of-band event
// the session has ever produced. Events for a deleted session are dropped.
Expand Down Expand Up @@ -462,6 +475,37 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r
return &rs.streaming
}

// DetachRuntime is the inverse of [SessionManager.AttachRuntime]: it releases
// the manager's in-memory state for an attached session (runtime registration,
// cancellation signal, event log, follow-up injector) without touching the
// persisted session. An embedder calls it when it stops owning the session,
// e.g. when a TUI tab is closed under --listen; otherwise the runtime and its
// session would stay reachable (and listed as active) until the process exits.
// Unlike [SessionManager.DeleteSession], the stored session is kept and the
// session ID is not tombstoned, so it can be attached again (e.g. a reopened tab). It is a no-op for unknown sessions.
func (sm *SessionManager) DetachRuntime(sessionID string) {
sm.mux.Lock()
defer sm.mux.Unlock()
rs, ok := sm.runtimeSessions.Load(sessionID)
if !ok {
return
}
if rs.cancel != nil {
rs.cancel()
}
sm.runtimeSessions.Delete(sessionID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocking] Removing the runtime from the manager does not undo the recall handler installed by AttachRuntime (session_manager.go:459–460). An embedder that keeps the detached runtime still holds a callback into this manager; an idle recall is routed back to the detached session and rejected instead of falling back to the runtime's steer queue (runtime.go:1492–1514). A focused test with a runtime that implements SetRecallHandler confirmed the handler remains set after detach. Clear the handler installed for that attachment.

// Undo the recall handler installed by AttachRuntime so a runtime kept by
// the embedder falls back to its own steer queue instead of routing idle
// recalls to a session this manager no longer owns.
if setter, ok := rs.runtime.(recallHandlerSetter); ok {
setter.SetRecallHandler(nil)
}
sm.releaseEventLog(sessionID)
sm.followUpInjectors.Delete(sessionID)
sm.followUpKeys.Delete(sessionID)
sm.pendingSafetyDefaults.Delete(sessionID)
}

// GetSession retrieves a session by ID.
func (sm *SessionManager) GetSession(ctx context.Context, id string) (*session.Session, error) {
if rs, ok := sm.runtimeSessions.Load(id); ok && rs.session != nil {
Expand Down
Loading