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
14 changes: 7 additions & 7 deletions cmd/root/run_listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,23 @@ func (f *runExecFlags) recallCoordinatorOpt(ctx context.Context, rt runtime.Runt
sm = server.NewSessionManager(ctx, nil, rt.SessionStore(), 0, &f.runConfig, server.WithSessionWorkingDirRoot(f.sessionWorkingDirRoot))
}
attachment := sm.AttachRuntime(ctx, sess.ID, rt, sess)
return withCoordinator(sm, attachment, sess, exposed), attachment.Detach
return withCoordinator(attachment, exposed), attachment.Detach
}

func withCoordinator(sm *server.SessionManager, attachment *server.RuntimeAttachment, sess *session.Session, exposed bool) app.Opt {
func withCoordinator(attachment *server.RuntimeAttachment, exposed bool) app.Opt {
return func(a *app.App) {
app.WithStreamGuard(attachment)(a)
if exposed {
registerAppEventSource(sm, sess.ID, a)
registerAppEventSource(attachment, a)
}
sm.RegisterFollowUpInjector(sess.ID, a.InjectUserMessage)
attachment.RegisterFollowUpInjector(a.InjectUserMessage)
}
}

// registerAppEventSource exposes an App's runtime events on the control
// plane's per-session event log (GET /api/sessions/:id/events).
func registerAppEventSource(sm *server.SessionManager, sessionID string, a *app.App) {
sm.RegisterEventSource(sessionID, func(ctx context.Context, send func(any)) {
func registerAppEventSource(attachment *server.RuntimeAttachment, a *app.App) {
attachment.RegisterEventSource(func(ctx context.Context, send func(any)) {
a.SubscribeReliable(ctx, func(msg tea.Msg) {
if ev, ok := msg.(runtime.Event); ok {
send(ev)
Expand Down Expand Up @@ -117,7 +117,7 @@ func (f *runExecFlags) startSessionCoordinator(ctx context.Context, out *cli.Pri
}
}()

return withCoordinator(sm, attachment, sess, true), attachment.Detach, nil
return withCoordinator(attachment, true), attachment.Detach, nil
}

// detachOnClose runs detach before cleanup, once, so a closed tab stops being
Expand Down
306 changes: 306 additions & 0 deletions pkg/server/session_detach_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package server

import (
"context"
"errors"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -301,3 +302,308 @@ func TestDetachRuntime_ReattachContinuesSSECursor(t *testing.T) {
require.Equal(t, []uint64{cursor + 1}, seqs)
second.Detach()
}

// gatedUpdateStore holds the first UpdateSession open until release is closed;
// later writes go straight through.
type gatedUpdateStore struct {
session.Store

once sync.Once
entered chan struct{}
release chan struct{}
}

func (s *gatedUpdateStore) UpdateSession(ctx context.Context, sess *session.Session) error {
gated := false
s.once.Do(func() { gated = true })
if gated {
close(s.entered)
<-s.release
}
return s.Store.UpdateSession(ctx, sess)
}

// TestDetachRuntime_WaitsForInFlightMetadataWrite checks that a detach does not
// make the session look inactive while a metadata write that started before it
// is still persisting: a later update would then take the stored-session path
// and be overwritten by the in-flight one.
func TestDetachRuntime_WaitsForInFlightMetadataWrite(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := &gatedUpdateStore{
Store: session.NewInMemorySessionStore(),
entered: make(chan struct{}),
release: make(chan struct{}),
}
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
attachment := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)

updated := make(chan error, 1)
go func() { updated <- sm.UpdateSessionTitle(ctx, sess.ID, "old") }()
<-store.entered

detached := make(chan struct{})
go func() {
attachment.Detach()
close(detached)
}()

assert.Never(t, func() bool {
_, ok := sm.runtimeSessions.Load(sess.ID)
return !ok
}, 100*time.Millisecond, 10*time.Millisecond, "the session must stay registered until the write is persisted")

close(store.release)
require.NoError(t, <-updated)
<-detached
require.Eventually(t, func() bool {
_, ok := sm.runtimeSessions.Load(sess.ID)
return !ok
}, 10*time.Second, time.Millisecond, "the teardown must finish once the write is persisted")
}

// TestDetachRuntime_ReattachWaitsForInFlightMetadataWrite checks that a same-ID
// reattachment does not let a newer write persist before a write that started
// on the detached attachment: the older write would then overwrite it.
func TestDetachRuntime_ReattachWaitsForInFlightMetadataWrite(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := &gatedUpdateStore{
Store: session.NewInMemorySessionStore(),
entered: make(chan struct{}),
release: make(chan struct{}),
}
sess := session.New()
require.NoError(t, store.AddSession(ctx, sess))
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
attachment := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)

oldWrite := make(chan error, 1)
go func() { oldWrite <- sm.UpdateSessionTitle(ctx, sess.ID, "old") }()
<-store.entered

attachment.Detach()
replacement := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess.Clone())

newWrite := make(chan error, 1)
go func() { newWrite <- sm.UpdateSessionTitle(ctx, sess.ID, "new") }()
assert.Never(t, func() bool { return len(newWrite) > 0 }, 100*time.Millisecond, 10*time.Millisecond,
"a write on the replacement must wait for the detached attachment's write")

// Other session IDs are not held behind the drain.
other := session.New()
require.NoError(t, store.AddSession(ctx, other))
otherAttachment := sm.AttachRuntime(ctx, other.ID, &fakeRuntime{}, other)
require.NoError(t, sm.UpdateSessionTitle(ctx, other.ID, "other"))
otherAttachment.Detach()

close(store.release)
require.NoError(t, <-oldWrite)
require.NoError(t, <-newWrite)

stored, err := store.GetSession(ctx, sess.ID)
require.NoError(t, err)
assert.Equal(t, "new", stored.Title, "the newer title must survive")

replacement.Detach()
}

// TestDetachRuntime_ReattachPreservesDrainedMetadataFields checks that a
// replacement whose session was cloned while an in-flight write on the old
// attachment was still persisting inherits the drained write's committed
// fields before persisting its own update on a different field.
func TestDetachRuntime_ReattachPreservesDrainedMetadataFields(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := &gatedUpdateStore{
Store: session.NewInMemorySessionStore(),
entered: make(chan struct{}),
release: make(chan struct{}),
}
sess := session.New()
sess.Title = "initial"
require.NoError(t, store.AddSession(ctx, sess))
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
oldRT := newModelSwitchingRuntime(nil)
attachment := sm.AttachRuntime(ctx, sess.ID, oldRT, sess)

modelWrite := make(chan error, 1)
go func() {
_, _, err := sm.SetSessionAgentModel(ctx, sess.ID, "openai/gpt-5")
modelWrite <- err
}()
<-store.entered

attachment.Detach()
replacementSess := sess.Clone()
replacement := sm.AttachRuntime(ctx, sess.ID, newModelSwitchingRuntime(nil), replacementSess)

titleWrite := make(chan error, 1)
go func() { titleWrite <- sm.UpdateSessionTitle(ctx, sess.ID, "renamed") }()
assert.Never(t, func() bool { return len(titleWrite) > 0 }, 100*time.Millisecond, 10*time.Millisecond,
"the replacement write must wait for the drained model write")

close(store.release)
require.NoError(t, <-modelWrite)
require.NoError(t, <-titleWrite)

stored, err := store.GetSession(ctx, sess.ID)
require.NoError(t, err)
assert.Equal(t, "renamed", stored.Title, "the replacement's title update must survive")
override, ok := stored.AgentModelOverride("root")
assert.True(t, ok, "the drained model override must survive in the store")
assert.Equal(t, "openai/gpt-5", override)
liveOverride, liveOK := replacementSess.AgentModelOverride("root")
assert.True(t, liveOK, "the replacement's live session must also carry the drained override")
assert.Equal(t, "openai/gpt-5", liveOverride)

replacement.Detach()
}

// gatedDeleteStore holds the first DeleteSession open until release is closed.
type gatedDeleteStore struct {
session.Store

once sync.Once
entered chan struct{}
release chan struct{}
err error
}

func (s *gatedDeleteStore) DeleteSession(ctx context.Context, id string) error {
gated := false
s.once.Do(func() { gated = true })
if gated {
close(s.entered)
<-s.release
if s.err != nil {
return s.err
}
}
return s.Store.DeleteSession(ctx, id)
}

// TestDetachRuntime_ReattachDuringDeleteRejectsQueuedUpdate checks that a
// same-ID reattach racing an in-flight DeleteSession carries the deletion
// result through the handoff: once DELETE removes the row, queued updates on
// the replacement are rejected and the row stays deleted.
func TestDetachRuntime_ReattachDuringDeleteRejectsQueuedUpdate(t *testing.T) {
t.Parallel()

ctx := t.Context()
store := &gatedDeleteStore{
Store: session.NewInMemorySessionStore(),
entered: make(chan struct{}),
release: make(chan struct{}),
}
sess := session.New()
sess.Title = "original"
require.NoError(t, store.AddSession(ctx, sess))
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)

deleted := make(chan error, 1)
go func() { deleted <- sm.DeleteSession(ctx, sess.ID) }()
<-store.entered

replacement := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess.Clone())

titleWrite := make(chan error, 1)
go func() { titleWrite <- sm.UpdateSessionTitle(ctx, sess.ID, "resurrected") }()
assert.Never(t, func() bool { return len(titleWrite) > 0 }, 100*time.Millisecond, 10*time.Millisecond,
"a write on the replacement must wait for the in-flight delete")

close(store.release)
require.NoError(t, <-deleted)
require.ErrorIs(t, <-titleWrite, ErrSessionNotRunning, "a successful delete must reject queued updates on the replacement")

_, stillRegistered := sm.runtimeSessions.Load(sess.ID)
assert.False(t, stillRegistered, "a deleted session's replacement must not stay registered")
_, err := store.GetSession(ctx, sess.ID)
require.Error(t, err, "the deleted session row must stay deleted")

replacement.Detach()
}

// TestDetachRuntime_ReattachDuringFailedDeleteAllowsQueuedUpdate checks that
// when a racing DeleteSession fails to delete the store row, a same-ID
// replacement still becomes writable and commits queued updates.
func TestDetachRuntime_ReattachDuringFailedDeleteAllowsQueuedUpdate(t *testing.T) {
t.Parallel()

ctx := t.Context()
deleteErr := errors.New("store delete failed")
store := &gatedDeleteStore{
Store: session.NewInMemorySessionStore(),
entered: make(chan struct{}),
release: make(chan struct{}),
err: deleteErr,
}
sess := session.New()
sess.Title = "original"
require.NoError(t, store.AddSession(ctx, sess))
sm := NewSessionManager(ctx, config.Sources{}, store, 0, &config.RuntimeConfig{})
sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)

deleted := make(chan error, 1)
go func() { deleted <- sm.DeleteSession(ctx, sess.ID) }()
<-store.entered

replacement := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess.Clone())

titleWrite := make(chan error, 1)
go func() { titleWrite <- sm.UpdateSessionTitle(ctx, sess.ID, "kept") }()
assert.Never(t, func() bool { return len(titleWrite) > 0 }, 100*time.Millisecond, 10*time.Millisecond)

close(store.release)
require.ErrorIs(t, <-deleted, deleteErr)
require.NoError(t, <-titleWrite)

stored, err := store.GetSession(ctx, sess.ID)
require.NoError(t, err)
assert.Equal(t, "kept", stored.Title)

replacement.Detach()
}

// TestRuntimeAttachment_RegistrationsAreScopedToTheAttachment checks that a late
// registration from a detached view is dropped, and that a stale attachment
// cannot overwrite the registrations of a same-ID replacement.
func TestRuntimeAttachment_RegistrationsAreScopedToTheAttachment(t *testing.T) {
t.Parallel()

ctx := t.Context()
sm, sess := newDetachTestManager(t)

old := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)
old.Detach()
old.RegisterEventSource(blockUntilCancelled)
old.RegisterFollowUpInjector(func(context.Context, string) {})
assert.False(t, sm.HasEventSource(sess.ID), "a detached attachment must not register an event source")
_, ok := sm.followUpInjectors.Load(sess.ID)
assert.False(t, ok, "a detached attachment must not register a follow-up injector")

replacement := sm.AttachRuntime(ctx, sess.ID, &fakeRuntime{}, sess)
var delivered []string
replacement.RegisterEventSource(blockUntilCancelled)
replacement.RegisterFollowUpInjector(func(context.Context, string) { delivered = append(delivered, "replacement") })
want, ok := sm.eventLogs.Load(sess.ID)
require.True(t, ok)

old.RegisterEventSource(blockUntilCancelled)
old.RegisterFollowUpInjector(func(context.Context, string) { delivered = append(delivered, "old") })

got, ok := sm.eventLogs.Load(sess.ID)
require.True(t, ok)
assert.Same(t, want, got, "a stale attachment must not replace the event source")
inject, ok := sm.followUpInjectors.Load(sess.ID)
require.True(t, ok)
inject(ctx, "hi")
assert.Equal(t, []string{"replacement"}, delivered)
replacement.Detach()
}
Loading