diff --git a/cmd/root/run_listen.go b/cmd/root/run_listen.go index 158d12efca..bb711f24b1 100644 --- a/cmd/root/run_listen.go +++ b/cmd/root/run_listen.go @@ -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) @@ -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 diff --git a/pkg/server/session_detach_test.go b/pkg/server/session_detach_test.go index 4c789ef5ad..8cbe786c7e 100644 --- a/pkg/server/session_detach_test.go +++ b/pkg/server/session_detach_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "sync" "testing" "time" @@ -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() +} diff --git a/pkg/server/session_manager.go b/pkg/server/session_manager.go index 3d6e67fccf..3625680aa4 100644 --- a/pkg/server/session_manager.go +++ b/pkg/server/session_manager.go @@ -50,7 +50,38 @@ type activeRuntimes struct { streaming sync.Mutex // Held while a RunStream is in progress; serialises concurrent requests modelSwitch sync.Mutex // Serialises model changes with manager-owned session persistence deleting atomic.Bool // Set before deletion waits for an in-flight model transaction + deleted atomic.Bool // Set once DeleteSession removes the store row; never cleared closing atomic.Bool // Set when the owning view detached; the entry stays registered until the stream releases streaming (see RuntimeAttachment.Detach). + + // handoffMu serializes modelSwitch release with a same-ID replacement's + // TryLock so committed metadata updates are recorded iff a replacement is + // waiting to drain this attachment. + handoffMu sync.Mutex + handoffWaiting bool + handoffCommits []func(*session.Session) + + // Protected by SessionManager.mux: carry an in-flight DeleteSession outcome + // across a same-ID replacement chain. + deleteInFlight int + deleteDone chan struct{} + awaitingDelete <-chan struct{} + replacedBy *activeRuntimes +} + +// unlockModelSwitch releases modelSwitch and, if a same-ID replacement is +// waiting to drain this attachment, records committed metadata updates so the +// replacement's session inherits them before its own writes persist. +func (rs *activeRuntimes) unlockModelSwitch(commits ...func(*session.Session)) { + rs.handoffMu.Lock() + if rs.handoffWaiting { + for _, fn := range commits { + if fn != nil { + rs.handoffCommits = append(rs.handoffCommits, fn) + } + } + } + rs.modelSwitch.Unlock() + rs.handoffMu.Unlock() } // SessionManager manages sessions for the HTTP API server and the --listen @@ -481,17 +512,127 @@ func (sm *SessionManager) AttachRuntime(ctx context.Context, sessionID string, r cancel: cancel, session: sess, } - // Serialise the registration with Detach/finishDetach: a detach for a - // previous attachment must observe either the old entry or this one, never - // a half-swapped state where it clears the replacement's per-ID state. + // Serialise the registration with Detach/finishDetach and DeleteSession: a + // detach or delete for a previous attachment must observe either the old + // entry or this one, never a half-swapped state. + // + // A metadata write or DeleteSession that started on the previous attachment + // may still be in flight. This attachment's modelSwitch stays held until it + // finishes: if the previous attachment committed metadata, those fields are + // applied to this session before replacement writes persist; if it was + // deleted, this replacement is torn down and queued writes are rejected. + // Only this session ID waits, and AttachRuntime itself does not block. sm.mux.Lock() + prev, replaced := sm.runtimeSessions.Load(sessionID) + if replaced && prev.deleted.Load() { + rs.deleting.Store(true) + rs.deleted.Store(true) + cancel() + sm.mux.Unlock() + return &RuntimeAttachment{sm: sm, sessionID: sessionID, rs: rs} + } + rs.modelSwitch.Lock() sm.runtimeSessions.Store(sessionID, rs) - sm.mux.Unlock() sm.registerRecallHandler(sessionID, rt) + + var deleteWait <-chan struct{} + var waitModelSwitch bool + if replaced { + if prev.deleteDone != nil { + deleteWait = prev.deleteDone + } else if prev.awaitingDelete != nil { + deleteWait = prev.awaitingDelete + } + if deleteWait != nil { + prev.replacedBy = rs + rs.awaitingDelete = deleteWait + } + prev.handoffMu.Lock() + if prev.modelSwitch.TryLock() { + prev.modelSwitch.Unlock() + } else { + prev.handoffWaiting = true + waitModelSwitch = true + } + prev.handoffMu.Unlock() + } + + if deleteWait == nil && !waitModelSwitch { + rs.modelSwitch.Unlock() + } else { + go sm.drainReplacedAttachment(sessionID, prev, rs, deleteWait, waitModelSwitch) + } + sm.mux.Unlock() sm.markReady() return &RuntimeAttachment{sm: sm, sessionID: sessionID, rs: rs} } +// drainReplacedAttachment waits for any in-flight DeleteSession or metadata +// write on prev before releasing rs.modelSwitch. If prev was deleted, rs is +// torn down so queued writes fail with ErrSessionNotRunning instead of +// upserting the deleted row back. Otherwise, committed metadata mutations from +// prev are applied to rs.session and forwarded in case another replacement is +// already chained behind rs. +func (sm *SessionManager) drainReplacedAttachment(sessionID string, prev, rs *activeRuntimes, deleteWait <-chan struct{}, waitModelSwitch bool) { + if deleteWait != nil { + <-deleteWait + if prev.deleted.Load() || rs.deleted.Load() { + sm.tearDownDeletedReplacement(sessionID, rs) + rs.unlockModelSwitch() + return + } + } + + var commits []func(*session.Session) + if waitModelSwitch { + prev.modelSwitch.Lock() + prev.handoffMu.Lock() + commits = prev.handoffCommits + prev.handoffCommits = nil + prev.handoffMu.Unlock() + prevDeleted := prev.deleted.Load() + prev.modelSwitch.Unlock() + + if prevDeleted || rs.deleted.Load() { + sm.tearDownDeletedReplacement(sessionID, rs) + rs.unlockModelSwitch() + return + } + } + + if len(commits) > 0 && rs.session != nil && rs.session != prev.session { + for _, apply := range commits { + apply(rs.session) + } + } + rs.unlockModelSwitch(commits...) +} + +func (sm *SessionManager) tearDownDeletedReplacement(sessionID string, rs *activeRuntimes) { + sm.mux.Lock() + defer sm.mux.Unlock() + sm.clearDeletedReplacementLocked(sessionID, rs) +} + +// clearDeletedReplacementLocked marks a same-ID replacement deleted and drops +// its manager registrations if it is still current. Caller holds sm.mux. +func (sm *SessionManager) clearDeletedReplacementLocked(sessionID string, rs *activeRuntimes) { + rs.deleting.Store(true) + rs.deleted.Store(true) + if rs.cancel != nil { + rs.cancel() + } + if setter, ok := rs.runtime.(recallHandlerSetter); ok { + setter.SetRecallHandler(nil) + } + if current, ok := sm.runtimeSessions.Load(sessionID); ok && current == rs { + sm.runtimeSessions.Delete(sessionID) + sm.dropEventLog(sessionID) + sm.followUpInjectors.Delete(sessionID) + sm.followUpKeys.Delete(sessionID) + } +} + // RuntimeAttachment is the handle returned by [SessionManager.AttachRuntime]. It // is the [sync.Locker] callers hold for the duration of every direct RunStream // call (#3590), and it identifies the attachment for @@ -559,6 +700,38 @@ func (a *RuntimeAttachment) Detach() { sm.finishDetach(a.sessionID, a.rs) } +// RegisterEventSource is [SessionManager.RegisterEventSource] scoped to this +// attachment: it is a no-op once the attachment has been detached or replaced +// by a same-ID [SessionManager.AttachRuntime], so a late registration from a +// closed view can neither recreate state for a detached session nor overwrite +// the registration of its replacement. +func (a *RuntimeAttachment) RegisterEventSource(src EventSource) { + a.sm.mux.Lock() + defer a.sm.mux.Unlock() + if a.ownsSessionLocked() { + a.sm.RegisterEventSource(a.sessionID, src) + } +} + +// RegisterFollowUpInjector is [SessionManager.RegisterFollowUpInjector] scoped +// to this attachment, like [RuntimeAttachment.RegisterEventSource]. +func (a *RuntimeAttachment) RegisterFollowUpInjector(fn FollowUpInjector) { + a.sm.mux.Lock() + defer a.sm.mux.Unlock() + if a.ownsSessionLocked() { + a.sm.RegisterFollowUpInjector(a.sessionID, fn) + } +} + +// ownsSessionLocked reports whether this attachment is still the live one for +// its session ID. Detach clears the per-ID registrations under sm.mux, so +// checking and registering under it too cannot interleave with a detach. The +// caller holds sm.mux. +func (a *RuntimeAttachment) ownsSessionLocked() bool { + current, ok := a.sm.runtimeSessions.Load(a.sessionID) + return ok && current == a.rs && !a.rs.closing.Load() && !a.rs.deleting.Load() +} + // finishDetach drops a closing attachment's runtimeSessions entry once its // streaming guard is released. The identity check keeps a late finish for a // replaced attachment from deleting its replacement. @@ -581,7 +754,25 @@ func (sm *SessionManager) finishDetach(sessionID string, rs *activeRuntimes) { if !rs.streaming.TryLock() { return // a stream is still running; its release calls finishDetach again. } + // Nor while a metadata write (title, model override...) that passed its + // runtimeActive check before the detach is still persisting: once the entry + // is gone a later update takes the stored-session path, and the in-flight + // write would overwrite it. closing rejects new writes, so waiting for + // modelSwitch drains them; the wait runs in its own goroutine so that + // finishDetach still never blocks. The streaming guard is released before + // the retry is started: if the retry then finds it held, that holder took + // it afterwards and its release calls finishDetach again. + if !rs.modelSwitch.TryLock() { + rs.streaming.Unlock() + go func() { + rs.modelSwitch.Lock() + rs.modelSwitch.Unlock() //nolint:gocritic,staticcheck // empty critical section: drain only + sm.finishDetach(sessionID, rs) + }() + return + } defer rs.streaming.Unlock() + defer rs.modelSwitch.Unlock() sm.mux.Lock() defer sm.mux.Unlock() if current, ok := sm.runtimeSessions.Load(sessionID); ok && current == rs { @@ -1093,19 +1284,50 @@ func (sm *SessionManager) deleteSession(ctx context.Context, sessionID string, t return nil } sessionRuntime.deleting.Store(true) + sessionRuntime.deleteInFlight++ + if sessionRuntime.deleteDone == nil { + sessionRuntime.deleteDone = make(chan struct{}) + } sm.mux.Unlock() sessionRuntime.modelSwitch.Lock() if err := sm.sessionStore.DeleteSession(ctx, sessionID); err != nil { - sessionRuntime.deleting.Store(false) sessionRuntime.modelSwitch.Unlock() + sm.mux.Lock() + sessionRuntime.deleteInFlight-- + if sessionRuntime.deleteInFlight == 0 { + if !sessionRuntime.deleted.Load() { + sessionRuntime.deleting.Store(false) + ch := sessionRuntime.deleteDone + for r := sessionRuntime; r != nil; { + next := r.replacedBy + if next == nil || next.awaitingDelete != ch { + break + } + r.replacedBy = nil + next.awaitingDelete = nil + r = next + } + } + if sessionRuntime.deleteDone != nil { + close(sessionRuntime.deleteDone) + sessionRuntime.deleteDone = nil + } + } + sm.mux.Unlock() return err } + sessionRuntime.deleted.Store(true) sessionRuntime.modelSwitch.Unlock() sm.mux.Lock() defer sm.mux.Unlock() sm.finishSessionDeletion(ctx, sess.ID, sessionRuntime, trackStopped) + sessionRuntime.deleteInFlight-- + if sessionRuntime.deleteDone != nil { + close(sessionRuntime.deleteDone) + sessionRuntime.deleteDone = nil + } return nil } @@ -1113,6 +1335,15 @@ func (sm *SessionManager) deleteSession(ctx context.Context, sessionID string, t // The caller holds sm.mux. func (sm *SessionManager) finishSessionDeletion(ctx context.Context, sessionID string, sessionRuntime *activeRuntimes, trackStopped bool) { if sessionRuntime != nil { + for r := sessionRuntime.replacedBy; r != nil; { + next := r.replacedBy + r.replacedBy = nil + r.awaitingDelete = nil + sm.clearDeletedReplacementLocked(sessionID, r) + r = next + } + sessionRuntime.replacedBy = nil + sessionRuntime.awaitingDelete = nil // Server-owned runtimes (done == nil) carry the manager's own // elicitation sink (see runtimeForSession); clear it so a detached // background job that elicits after this point hits the runtime's @@ -1277,7 +1508,10 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena sm.beforeRunModelSwitch() } runtimeSession.modelSwitch.Lock() - defer runtimeSession.modelSwitch.Unlock() + var committed func(*session.Session) + defer func() { + runtimeSession.unlockModelSwitch(committed) + }() if !sm.runtimeActive(sessionID, runtimeSession) { runtimeSession.unlockStream(sm, sessionID) @@ -1293,6 +1527,10 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena // messages so that an invalid ref does not leave an orphaned user // message in the history. The streaming and modelSwitch locks keep the // runtime, persisted snapshot, live session, and rollback in one transaction. + var overrideAgent string + if modelOverride != "" { + overrideAgent = runtimeSession.runtime.CurrentAgentName(ctx) + } undoModelOverride, err := sm.applyRunModelOverride(ctx, runtimeSession, modelOverride) if err != nil { runtimeSession.unlockStream(sm, sessionID) @@ -1331,6 +1569,9 @@ func (sm *SessionManager) RunSession(ctx context.Context, sessionID, agentFilena cancel() return nil, err } + if modelOverride != "" { + committed = func(s *session.Session) { s.SetAgentModelOverride(overrideAgent, modelOverride) } + } // Update the session pointer so the runtime sees the latest messages. runtimeSession.session = sess @@ -1437,7 +1678,10 @@ func (sm *SessionManager) ResumeSession(ctx context.Context, sessionID, confirma } rt.modelSwitch.Lock() - defer rt.modelSwitch.Unlock() + var committed func(*session.Session) + defer func() { + rt.unlockModelSwitch(committed) + }() if !sm.runtimeActive(sessionID, rt) { return ErrSessionNotRunning } @@ -1448,26 +1692,28 @@ func (sm *SessionManager) ResumeSession(ctx context.Context, sessionID, confirma // so old clients keep working. resumeType := runtime.NormalizeResumeType(runtime.ResumeType(confirmation)) if rt.session != nil { - mutated := false + var applyCommit func(*session.Session) switch resumeType { case runtime.ResumeTypeApproveBalanced: rt.session.SetSafetyPolicy(session.SafetyPolicyBalanced) - mutated = true + applyCommit = func(s *session.Session) { s.SetSafetyPolicy(session.SafetyPolicyBalanced) } case runtime.ResumeTypeApproveAutonomous: rt.session.SetSafetyPolicy(session.SafetyPolicyAutonomous) - mutated = true + applyCommit = func(s *session.Session) { s.SetSafetyPolicy(session.SafetyPolicyAutonomous) } case runtime.ResumeTypeApproveTool: // Skip when toolName is empty — the dispatcher's own // fallback (pending tool call name) isn't reachable here. if toolName != "" { rt.session.AppendPermissionAllow(toolName) - mutated = true + applyCommit = func(s *session.Session) { s.AppendPermissionAllow(toolName) } } } - if mutated { + if applyCommit != nil { if err := sm.sessionStore.UpdateSession(ctx, rt.session); err != nil { slog.WarnContext(ctx, "failed to persist mid-turn session state", "session_id", sessionID, "confirmation", confirmation, "err", err) + } else { + committed = applyCommit } } } @@ -1678,6 +1924,9 @@ func (sm *SessionManager) ToggleToolApproval(ctx context.Context, sessionID stri sess.ToggleYolo() }, func() { sess.ToggleYolo() + }, func() func(*session.Session) { + policy, prior := sess.GetSafetyPolicy(), sess.GetPriorSafetyPolicy() + return func(s *session.Session) { s.RestoreSafetyState(policy, prior) } }) } defer sm.mux.Unlock() @@ -1702,7 +1951,9 @@ func (sm *SessionManager) SetSessionSafetyPolicy(ctx context.Context, sessionID sm.mux.Unlock() return sm.updateActiveSession(ctx, sessionID, rt, sess, func() { sess.SetSafetyPolicy(policy) - }, nil) + }, nil, func() func(*session.Session) { + return func(s *session.Session) { s.SetSafetyPolicy(policy) } + }) } defer sm.mux.Unlock() @@ -1723,7 +1974,10 @@ func (sm *SessionManager) UpdateSessionPermissions(ctx context.Context, sessionI sm.mux.Unlock() return sm.updateActiveSession(ctx, sessionID, rt, sess, func() { sess.SetPermissions(perms) - }, nil) + }, nil, func() func(*session.Session) { + cloned := perms.Clone() + return func(s *session.Session) { s.SetPermissions(cloned) } + }) } defer sm.mux.Unlock() @@ -1736,15 +1990,18 @@ func (sm *SessionManager) UpdateSessionPermissions(ctx context.Context, sessionI } func (sm *SessionManager) persistActiveSession(ctx context.Context, sessionID string, rt *activeRuntimes, sess *session.Session) error { - return sm.updateActiveSession(ctx, sessionID, rt, sess, nil, nil) + return sm.updateActiveSession(ctx, sessionID, rt, sess, nil, nil, nil) } -func (sm *SessionManager) updateActiveSession(ctx context.Context, sessionID string, rt *activeRuntimes, sess *session.Session, update, rollback func()) error { +func (sm *SessionManager) updateActiveSession(ctx context.Context, sessionID string, rt *activeRuntimes, sess *session.Session, update, rollback func(), commit func() func(*session.Session)) error { if sm.beforePersistActiveSession != nil { sm.beforePersistActiveSession() } rt.modelSwitch.Lock() - defer rt.modelSwitch.Unlock() + var committed func(*session.Session) + defer func() { + rt.unlockModelSwitch(committed) + }() if !sm.runtimeActive(sessionID, rt) || rt.session != sess { return ErrSessionNotRunning } @@ -1757,6 +2014,9 @@ func (sm *SessionManager) updateActiveSession(ctx context.Context, sessionID str } return err } + if commit != nil { + committed = commit() + } return nil } @@ -1772,7 +2032,9 @@ func (sm *SessionManager) UpdateSessionTitle(ctx context.Context, sessionID, tit slog.DebugContext(ctx, "Updated title for active session", "session_id", sessionID, "title", title) return sm.updateActiveSession(ctx, sessionID, rt, sess, func() { sess.SetTitle(title) - }, nil) + }, nil, func() func(*session.Session) { + return func(s *session.Session) { s.SetTitle(title) } + }) } defer sm.mux.Unlock() @@ -1808,7 +2070,9 @@ func (sm *SessionManager) generateTitle(ctx context.Context, sess *session.Sessi rs, ok := sm.runtimeSessions.Load(sess.ID) if !ok || sm.updateActiveSession(ctx, sess.ID, rs, sess, func() { sess.SetTitle(title) - }, nil) != nil { + }, nil, func() func(*session.Session) { + return func(s *session.Session) { s.SetTitle(title) } + }) != nil { return } @@ -2395,7 +2659,10 @@ func (sm *SessionManager) SetSessionAgentModel(ctx context.Context, sessionID, m } rs.modelSwitch.Lock() - defer rs.modelSwitch.Unlock() + var committed func(*session.Session) + defer func() { + rs.unlockModelSwitch(committed) + }() if err := ctx.Err(); err != nil { return "", "", err @@ -2459,6 +2726,7 @@ func (sm *SessionManager) SetSessionAgentModel(ctx context.Context, sessionID, m } sess.SetAgentModelOverride(agentName, modelRef) + committed = func(s *session.Session) { s.SetAgentModelOverride(agentName, modelRef) } slog.DebugContext(ctx, "Updated session model override", "session_id", sessionID, "agent", agentName, "model", modelRef) return agentName, modelRef, nil diff --git a/pkg/session/session.go b/pkg/session/session.go index 05a9f43ab1..b60cb7e024 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -2172,6 +2172,16 @@ func (s *Session) GetPriorSafetyPolicy() SafetyPolicy { return s.PriorSafetyPolicy } +// RestoreSafetyState sets the safety policy and yolo-toggle memory atomically, +// keeping ToolsApproved in sync. +func (s *Session) RestoreSafetyState(policy, prior SafetyPolicy) { + s.mu.Lock() + defer s.mu.Unlock() + s.SafetyPolicy = policy.Normalize() + s.PriorSafetyPolicy = prior.Normalize() + s.ToolsApproved = s.SafetyPolicy == SafetyPolicyAutonomous +} + // ToggleYolo flips the session between Autonomous and the mode that was // active before the escalation, so an explicit Balanced/Strict choice // survives a toggle round-trip. A session that was never escalated from