Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471)
Leo Dawn56d075e213da
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex 9639ec310..a1dc8aae3 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -568,7 +568,7 @@ func (s *agentService) initializeSkillsManager(toolRegistry *tools.ToolRegistry,) (*skills.Manager, error) {tenantID, _ := types.TenantIDFromContext(ctx)- sandboxMgr, configID, err := resolveSandboxForExecution(+ sandboxMgr, pin, err := resolveSandboxForExecution(ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,tenantID, sessionID, config.SandboxConfigID, s.sandboxPolicy,)@@ -579,7 +579,8 @@ func (s *agentService) initializeSkillsManager(sandboxMgr = sandbox.NewDisabledManager()}- logger.Infof(ctx, "Workspace sandbox in use: config=%s type=%s", configID, sandboxMgr.GetType())+ logger.Infof(ctx, "Workspace sandbox in use: config=%s workspace=%d type=%s",+ pin.ConfigID, pin.TenantOr(tenantID), sandboxMgr.GetType())// Create skills managerskillsConfig := &skills.ManagerConfig{diff --git a/internal/application/service/artifact_collector.go b/internal/application/service/artifact_collector.goindex 69b737a75..cb5b3ab62 100644--- a/internal/application/service/artifact_collector.go+++ b/internal/application/service/artifact_collector.go@@ -178,17 +178,17 @@ func (c *ArtifactCollector) sessionSource(ctx context.Context, sessionID string)if c.resolver == nil {return c.source}- tenantID, _ := types.TenantIDFromContext(ctx)- configID, err := sandboxConfigForExistingSandbox(ctx, c.pinner, sessionID)+ sessionTenantID, _ := types.TenantIDFromContext(ctx)+ pin, err := sandboxConfigForExistingSandbox(ctx, c.pinner, sessionID)if err != nil {logger.Warnf(ctx, "[ArtifactCollector] read sandbox pin failed: %v", err)return nil}- if configID == "" {+ if pin.IsZero() {return nil}mgr, err := resolveTenantSandboxForConfig(- ctx, c.resolver, c.fallbackMgr, tenantID, configID, nil,+ ctx, c.resolver, c.fallbackMgr, pin.TenantOr(sessionTenantID), pin.ConfigID, nil,)if err != nil {// Refusing to read is the safe failure: substituting another backend@@ -204,7 +204,7 @@ func (c *ArtifactCollector) sessionSource(ctx context.Context, sessionID string)if source, ok := mgr.(SandboxArtifactSource); ok {return source}- if configID == types.SandboxConfigIDGlobalDefault {+ if pin.ConfigID == types.SandboxConfigIDGlobalDefault {return c.source}return nildiff --git a/internal/application/service/fork_snapshot_reaper.go b/internal/application/service/fork_snapshot_reaper.goindex fed988b07..ce394fc22 100644--- a/internal/application/service/fork_snapshot_reaper.go+++ b/internal/application/service/fork_snapshot_reaper.go@@ -207,8 +207,10 @@ func leaseForkSnapshotOnDelete(return}lease := &types.ForkSnapshotLease{- SnapshotID: snapshotID,- TenantID: session.TenantID,+ SnapshotID: snapshotID,+ // Pairs with SandboxConfigID: the workspace that owns the config, not+ // necessarily the one that owns the session (shared agents).+ TenantID: session.SandboxConfigOwner(),SandboxConfigID: session.SandboxConfigID,CreatedAt: time.Now().UTC(),}@@ -297,7 +299,8 @@ func deleteForkSnapshot(var err errorif session != nil {if scoped, ok := snapshots.(forkSessionSnapshotDeleter); ok {- err = scoped.DeleteForkSnapshot(ctx, session.TenantID, session.SandboxConfigID, snapshotID)+ err = scoped.DeleteForkSnapshot(+ ctx, session.SandboxConfigOwner(), session.SandboxConfigID, snapshotID)} else {err = snapshots.DeleteSnapshot(ctx, snapshotID)}diff --git a/internal/application/service/pinned_session_sandbox.go b/internal/application/service/pinned_session_sandbox.goindex fa2ac3778..ca85197a0 100644--- a/internal/application/service/pinned_session_sandbox.go+++ b/internal/application/service/pinned_session_sandbox.go@@ -14,7 +14,7 @@ import (// owns a session's binding. *SessionSandboxPinner is the production// implementation; tests use a stub so this does not need a database.type sessionSandboxPinReader interface {- Read(ctx context.Context, sessionID string) (string, error)+ Read(ctx context.Context, sessionID string) (SandboxPin, error)}// PinnedSessionSandbox resolves the session's pinned sandbox manager at@@ -49,13 +49,17 @@ func (a *PinnedSessionSandbox) manager(ctx context.Context, sessionID string) saif a.pinner == nil {return nil}- configID, err := a.pinner.Read(ctx, sessionID)- if err != nil || strings.TrimSpace(configID) == "" {+ pin, err := a.pinner.Read(ctx, sessionID)+ if err != nil || pin.IsZero() {return nil}- tenantID, _ := types.TenantIDFromContext(ctx)+ // The workspace comes from the pin, not the request. Fork runs from a plain+ // POST as the session owner, while a shared agent's sandbox lives on the+ // lending workspace's config — reading it as the session owner found+ // nothing and silently degraded the fork to SNAPSHOT_UNSUPPORTED.+ sessionTenantID, _ := types.TenantIDFromContext(ctx)mgr, err := resolveTenantSandboxForConfig(- ctx, a.resolver, a.fallback, tenantID, configID, nil,+ ctx, a.resolver, a.fallback, pin.TenantOr(sessionTenantID), pin.ConfigID, nil,)if err != nil {return nildiff --git a/internal/application/service/pinned_session_sandbox_test.go b/internal/application/service/pinned_session_sandbox_test.goindex 1ba622a58..aeabb6611 100644--- a/internal/application/service/pinned_session_sandbox_test.go+++ b/internal/application/service/pinned_session_sandbox_test.go@@ -12,11 +12,14 @@ import (type stubPinReader struct {configID string+ // tenantID is the workspace owning configID; zero keeps the "the session's+ // own workspace" fallback that every non-borrowed pin uses.+ tenantID uint64err error}-func (s stubPinReader) Read(context.Context, string) (string, error) {- return s.configID, s.err+func (s stubPinReader) Read(context.Context, string) (SandboxPin, error) {+ return SandboxPin{ConfigID: s.configID, TenantID: s.tenantID}, s.err}type stubTenantSandboxResolver struct {diff --git a/internal/application/service/sandbox_desktop_service.go b/internal/application/service/sandbox_desktop_service.goindex 6a70f15ac..63e1e2f10 100644--- a/internal/application/service/sandbox_desktop_service.go+++ b/internal/application/service/sandbox_desktop_service.go@@ -75,15 +75,15 @@ func NewSandboxDesktopService(terminals *SandboxTerminalService) *SandboxDesktop// EnsureSessionDesktop starts the desktop listeners and dials websockify.//-// An empty sandboxConfigID is lookup-only: a running session sandbox is+// A zero provision pin is lookup-only: a running session sandbox is// attached (and XFCE is lazily started if needed), a paused one returns// sandbox.ErrSandboxPaused, and a missing one returns-// sandbox.ErrNoLiveSessionSandbox. A non-empty ID is the confirmed-click+// sandbox.ErrNoLiveSessionSandbox. A non-zero pin is the confirmed-click// path and may create or resume, the same contract as EnsureSessionTerminal.func (s *SandboxDesktopService) EnsureSessionDesktop(ctx context.Context,sessionID string,- sandboxConfigID string,+ provision SandboxPin,) (*SessionDesktop, error) {if s == nil || s.terminals == nil {return nil, sandbox.ErrNoLiveSessionSandbox@@ -93,7 +93,7 @@ func (s *SandboxDesktopService) EnsureSessionDesktop(// provisions through the same path a chat turn uses. Either way the// inbound token is registered on THIS replica, which is what keeps// the gateway from answering 401.- mgr, err := s.resolveRunningManager(ctx, sessionID, sandboxConfigID)+ mgr, err := s.resolveRunningManager(ctx, sessionID, provision)if err != nil {return nil, err}@@ -139,17 +139,17 @@ func (s *SandboxDesktopService) EnsureSessionDesktop(}// resolveRunningManager returns a manager whose session sandbox is live.-// With no sandboxConfigID it will not create or resume: a paused binding+// With a zero provision pin it will not create or resume: a paused binding// is ErrSandboxPaused so the overlay can ask first. DesktopEnabled is// checked before provision (and before Exec in EnsureSessionDesktop) so a// CLI image cannot be created or woken only to miss start-desktop.sh.func (s *SandboxDesktopService) resolveRunningManager(ctx context.Context,sessionID string,- sandboxConfigID string,+ provision SandboxPin,) (sandbox.Manager, error) {t := s.terminals- lookupOnly := strings.TrimSpace(sandboxConfigID) == ""+ lookupOnly := provision.IsZero()mgr, _, err := t.resolveSessionManager(ctx, sessionID)if err == nil {if err := requireDesktopCapable(mgr); err != nil {@@ -165,10 +165,12 @@ func (s *SandboxDesktopService) resolveRunningManager(if !errors.Is(err, sandbox.ErrNoLiveSessionSandbox) || lookupOnly {return nil, err}- tenantID, _ := types.TenantIDFromContext(ctx)+ // provision.TenantID owns provision.ConfigID — the lending workspace for a+ // shared agent, which is where its config actually exists.+ sessionTenantID, _ := types.TenantIDFromContext(ctx)mgr, _, err = resolveSandboxForExecution(- ctx, t.resolver, t.fallback, t.pinner, tenantID, sessionID,- strings.TrimSpace(sandboxConfigID), t.policy,+ ctx, t.resolver, t.fallback, t.pinner,+ provision.TenantOr(sessionTenantID), sessionID, provision.ConfigID, t.policy,)if err != nil {return nil, errdiff --git a/internal/application/service/sandbox_terminal_service.go b/internal/application/service/sandbox_terminal_service.goindex 45065be47..0107969db 100644--- a/internal/application/service/sandbox_terminal_service.go+++ b/internal/application/service/sandbox_terminal_service.go@@ -10,7 +10,6 @@ package serviceimport ("context""errors"- "strings""time""github.com/Tencent/WeKnora/internal/logger"@@ -90,28 +89,31 @@ func (s *SandboxTerminalService) OpenSessionTerminal(func (s *SandboxTerminalService) resolveSessionManager(ctx context.Context,sessionID string,-) (sandbox.Manager, string, error) {+) (sandbox.Manager, SandboxPin, error) {if s.pinner == nil {- return nil, "", sandbox.ErrNoLiveSessionSandbox+ return nil, SandboxPin{}, sandbox.ErrNoLiveSessionSandbox}- configID, err := s.pinner.Read(ctx, sessionID)+ pin, err := s.pinner.Read(ctx, sessionID)if err != nil {- return nil, "", err+ return nil, SandboxPin{}, err}- if configID == "" {- return nil, "", sandbox.ErrNoLiveSessionSandbox+ if pin.IsZero() {+ return nil, SandboxPin{}, sandbox.ErrNoLiveSessionSandbox}- tenantID, _ := types.TenantIDFromContext(ctx)+ // The workspace comes from the pin, not from the request: a shared agent's+ // sandbox lives on its owner's config, and this call runs from a panel+ // open, where the request tenant is the session owner.+ sessionTenantID, _ := types.TenantIDFromContext(ctx)mgr, err := resolveTenantSandboxForConfig(- ctx, s.resolver, s.fallback, tenantID, configID, s.policy,+ ctx, s.resolver, s.fallback, pin.TenantOr(sessionTenantID), pin.ConfigID, s.policy,)if err != nil {- return nil, configID, err+ return nil, pin, err}if mgr == nil {- return nil, configID, sandbox.ErrNoLiveSessionSandbox+ return nil, pin, sandbox.ErrNoLiveSessionSandbox}- return mgr, configID, nil+ return mgr, pin, nil}// EnsureSessionTerminal opens a PTY on the session's sandbox, provisioning@@ -126,17 +128,19 @@ func (s *SandboxTerminalService) resolveSessionManager(// resolveSandboxForExecution — so a terminal-created sandbox is// indistinguishable from one created by a conversation turn. The WebSocket// handler must resolve the agent the same way a chat turn does (own agent-// or shared agent from another workspace) and pass that config ID here.+// or shared agent from another workspace) and pass that agent's config AND+// the workspace that owns it here: a shared agent's config does not exist in+// the caller's own workspace.// A no-op shell command drives the lazy creation, which also seeds the// workspace layout.//-// With no sandboxConfigID the call stays lookup-only and reports+// With a zero provision pin the call stays lookup-only and reports// sandbox.ErrNoLiveSessionSandbox, which the WebSocket handler maps onto// the SANDBOX_NOT_BOUND guidance frame.func (s *SandboxTerminalService) EnsureSessionTerminal(ctx context.Context,sessionID string,- sandboxConfigID string,+ provision SandboxPin,opts sandbox.RemoteTerminalOptions,) (*SessionTerminal, error) {opts.AllowResume = true@@ -161,13 +165,18 @@ func (s *SandboxTerminalService) EnsureSessionTerminal(}return nil, terr}- if !errors.Is(err, sandbox.ErrNoLiveSessionSandbox) || strings.TrimSpace(sandboxConfigID) == "" {+ if !errors.Is(err, sandbox.ErrNoLiveSessionSandbox) || provision.IsZero() {return nil, err}- tenantID, _ := types.TenantIDFromContext(ctx)+ // provision.TenantID owns provision.ConfigID; for a shared agent that is+ // the lending workspace, which the WebSocket handler resolved alongside the+ // config. Falling back to the request tenant keeps own-agent callers (and+ // any caller that has no agent context) on their own workspace.+ sessionTenantID, _ := types.TenantIDFromContext(ctx)mgr, _, err = resolveSandboxForExecution(- ctx, s.resolver, s.fallback, s.pinner, tenantID, sessionID, strings.TrimSpace(sandboxConfigID), s.policy,+ ctx, s.resolver, s.fallback, s.pinner,+ provision.TenantOr(sessionTenantID), sessionID, provision.ConfigID, s.policy,)if err != nil {return nil, errdiff --git a/internal/application/service/sandbox_terminal_service_test.go b/internal/application/service/sandbox_terminal_service_test.goindex 6c67715ba..95c9c9f69 100644--- a/internal/application/service/sandbox_terminal_service_test.go+++ b/internal/application/service/sandbox_terminal_service_test.go@@ -21,6 +21,6 @@ func TestOpenSessionTerminalNeverReachesProvisioning(t *testing.T) {_, err := svc.OpenSessionTerminal(ctx, "sess-1", sandbox.RemoteTerminalOptions{})require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)- _, err = svc.EnsureSessionTerminal(ctx, "sess-1", "", sandbox.RemoteTerminalOptions{})+ _, err = svc.EnsureSessionTerminal(ctx, "sess-1", SandboxPin{}, sandbox.RemoteTerminalOptions{})require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)}diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex c59a7d5ef..44bca7e2d 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -699,8 +699,8 @@ func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID stri// Resolve the workspace's own manager: the sandbox to release lives on// whichever backend that workspace is configured for, not necessarily the// process-wide default.- tenantID, _ := types.TenantIDFromContext(ctx)- configID, err := sandboxConfigForExistingSandbox(ctx, s.sandboxPinner, sessionID)+ sessionTenantID, _ := types.TenantIDFromContext(ctx)+ pin, err := sandboxConfigForExistingSandbox(ctx, s.sandboxPinner, sessionID)if err != nil {logger.Warnf(ctx, "Failed to read sandbox pin for session %s cleanup: %v", sessionID, err)return@@ -711,9 +711,18 @@ func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID stri// binding lookup that no-ops when the session truly has no sandbox, whereas// skipping would abandon a paused instance that keeps billing.//+ // The workspace comes from the pin. This runs from a plain DELETE whose+ // only tenant is the session's own, but a shared agent's sandbox was+ // created on the LENDING workspace's config: resolving that here as the+ // session owner finds nothing and abandons a paused MicroVM that keeps+ // billing with nobody holding its id.+ //// Pass nil policy so the workspace kill switch cannot strand an already// created sandbox: disabling script execution must still allow teardown.- mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, nil)+ mgr, err := resolveTenantSandboxForConfig(+ ctx, s.sandboxResolver, s.sandboxMgr,+ pin.TenantOr(sessionTenantID), pin.ConfigID, nil,+ )if err != nil {logger.Warnf(ctx, "Failed to resolve sandbox for session %s cleanup: %v", sessionID, err)returndiff --git a/internal/application/service/session_fork.go b/internal/application/service/session_fork.goindex 22718b5b2..bc718b88b 100644--- a/internal/application/service/session_fork.go+++ b/internal/application/service/session_fork.go@@ -240,16 +240,19 @@ func (s *SessionForkService) Fork(}newSession := &types.Session{- ID: uuid.New().String(),- TenantID: source.TenantID,- UserID: source.UserID,- Title: forkTitle(title, source.Title),- Description: source.Description,- LastRequestState: source.LastRequestState,- SandboxConfigID: source.SandboxConfigID,- ParentSessionID: source.ID,- ForkedFromMessageID: forkPoint.ID,- ForkBootstrap: bootstrap,+ ID: uuid.New().String(),+ TenantID: source.TenantID,+ UserID: source.UserID,+ Title: forkTitle(title, source.Title),+ Description: source.Description,+ LastRequestState: source.LastRequestState,+ SandboxConfigID: source.SandboxConfigID,+ // The owner travels with the config id, or the branch would inherit a+ // pin that resolves nowhere the moment the source ran a shared agent.+ SandboxConfigTenantID: source.SandboxConfigTenantID,+ ParentSessionID: source.ID,+ ForkedFromMessageID: forkPoint.ID,+ ForkBootstrap: bootstrap,}copied := copyMessagesInto(newSession.ID, history)@@ -352,8 +355,11 @@ func (s *SessionForkService) recordSnapshotLease(return nil}lease := &types.ForkSnapshotLease{- SnapshotID: bootstrap.SnapshotID,- TenantID: source.TenantID,+ SnapshotID: bootstrap.SnapshotID,+ // The reaper resolves (TenantID, SandboxConfigID) as a pair, so this+ // must be the workspace that owns the config — the lending one when+ // the snapshot was taken on a shared agent's sandbox.+ TenantID: source.SandboxConfigOwner(),SandboxConfigID: source.SandboxConfigID,CreatedAt: time.Now().UTC(),}diff --git a/internal/application/service/session_sandbox_entry_test.go b/internal/application/service/session_sandbox_entry_test.goindex 1b6091ce3..ff369cdfe 100644--- a/internal/application/service/session_sandbox_entry_test.go+++ b/internal/application/service/session_sandbox_entry_test.go@@ -56,7 +56,7 @@ func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {func TestArtifactSessionSourceKeepsDefaultBackendForSentinelPin(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- _, err := pinner.Pin(ctx, "s-1", types.SandboxConfigIDGlobalDefault)+ _, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: types.SandboxConfigIDGlobalDefault})require.NoError(t, err)source := &fakeSandboxSource{}@@ -103,7 +103,7 @@ func TestArtifactSessionSourceSkipsUnpinnedSession(t *testing.T) {func TestArtifactSessionSourceResolvesNamedPin(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))- _, err := pinner.Pin(ctx, "s-1", "cfg-docker")+ _, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-docker"})require.NoError(t, err)named := &artifactFallbackManager{source: &fakeSandboxSource{}}diff --git a/internal/application/service/session_sandbox_pin.go b/internal/application/service/session_sandbox_pin.goindex 0d3cb5b96..7279595c6 100644--- a/internal/application/service/session_sandbox_pin.go+++ b/internal/application/service/session_sandbox_pin.go@@ -10,9 +10,11 @@// query the wrong account (artifacts silently vanish) and teardown fail// (a paused sandbox nobody knows the ID of, billing forever).//-// The pin records which config the session's CURRENT sandbox lives on. It is-// deliberately ephemeral: sessions outlive sandboxes by months, so a permanent-// pin would make "nothing references this config" never become true.+// The pin records which config the session's CURRENT sandbox lives on, and+// which workspace owns that config. Both halves are needed: configs are keyed+// by (tenant, id), so an id alone does not name a backend. It is deliberately+// ephemeral: sessions outlive sandboxes by months, so a permanent pin would+// make "nothing references this config" never become true.package serviceimport (@@ -23,10 +25,46 @@ import ("gorm.io/gorm"+ "github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/types")+// SandboxPin addresses the backend a session's live sandbox runs on.+//+// ConfigID alone is not an address. tenant_sandbox_configs is keyed by+// (tenant_id, id), so the same id resolves in exactly one workspace - and a+// shared agent runs on ITS OWNER's config while the session belongs to the+// borrower. Reading the workspace from the ambient request context instead is+// what used to strand those MicroVMs: teardown, the terminal and desktop+// panels and fork snapshots all run outside the chat turn, where the ambient+// tenant is the borrower.+//+// Keeping the pair in one value is the point of the type: an API that can hand+// out a bare config id is an API where the two can drift apart again.+type SandboxPin struct {+ // ConfigID is the sandbox config, or "" when the session has no live+ // sandbox. types.SandboxConfigIDGlobalDefault means the deployment default.+ ConfigID string++ // TenantID owns ConfigID. Zero means the session's own workspace, which+ // covers every sandbox created by an agent that workspace owns as well as+ // pins written before the column existed.+ TenantID uint64+}++// IsZero reports whether the pin names no sandbox.+func (p SandboxPin) IsZero() bool { return strings.TrimSpace(p.ConfigID) == "" }++// TenantOr resolves the workspace to look ConfigID up in, falling back to the+// session's own tenant for pins that carry no owner.+func (p SandboxPin) TenantOr(sessionTenantID uint64) uint64 {+ if p.TenantID != 0 {+ return p.TenantID+ }+ return sessionTenantID+}+// SessionSandboxPinner is the only place session sandbox pins are read or// written. Centralising it is what keeps the four entry points consistent.type SessionSandboxPinner struct {@@ -38,10 +76,10 @@ func NewSessionSandboxPinner(db *gorm.DB) *SessionSandboxPinner {return &SessionSandboxPinner{db: db}}-// Read returns the pinned config ID, or "" when the session has no live-// sandbox. Note the pin is an optimistic hint: the sandbox may have been+// Read returns the pinned backend, or the zero pin when the session has no+// live sandbox. Note the pin is an optimistic hint: the sandbox may have been// reclaimed out of band (see Clear).-func (p *SessionSandboxPinner) Read(ctx context.Context, sessionID string) (string, error) {+func (p *SessionSandboxPinner) Read(ctx context.Context, sessionID string) (SandboxPin, error) {pinned, _, err := p.read(ctx, sessionID)return pinned, err}@@ -53,43 +91,53 @@ func (p *SessionSandboxPinner) Read(ctx context.Context, sessionID string) (stri//// Soft-deleted sessions count as absent — GORM scopes them out — which is what// we want, since deleting a session also destroys its sandbox.-func (p *SessionSandboxPinner) read(ctx context.Context, sessionID string) (string, bool, error) {- var pinned sql.NullString+func (p *SessionSandboxPinner) read(ctx context.Context, sessionID string) (SandboxPin, bool, error) {+ var row struct {+ SandboxConfigID sql.NullString+ SandboxConfigTenantID sql.NullInt64+ }result := p.db.WithContext(ctx).Model(&types.Session{}).Where("id = ?", sessionID).- Select("sandbox_config_id").- Scan(&pinned)+ Select("sandbox_config_id", "sandbox_config_tenant_id").+ Scan(&row)if result.Error != nil {- return "", false, result.Error+ return SandboxPin{}, false, result.Error}if result.RowsAffected == 0 {- return "", false, nil+ return SandboxPin{}, false, nil+ }+ pin := SandboxPin{}+ if row.SandboxConfigID.Valid {+ pin.ConfigID = row.SandboxConfigID.String}- if !pinned.Valid {- return "", true, nil+ // A negative value can only come from a hand-edited row; treat it the same+ // as an absent owner rather than wrapping it into a huge tenant id.+ if row.SandboxConfigTenantID.Valid && row.SandboxConfigTenantID.Int64 > 0 {+ pin.TenantID = uint64(row.SandboxConfigTenantID.Int64)}- return pinned.String, true, nil+ return pin, true, nil}-// Pin claims the session for configID and returns the winning value.+// Pin claims the session for pin and returns the winning value.//// The conditional update is what makes concurrent first-sandbox creations-// safe: losers adopt the winner's config instead of building a second sandbox+// safe: losers adopt the winner's backend instead of building a second sandbox// on a second backend.//// A missing or soft-deleted session is an error rather than an empty result.-// Pin is called just after a sandbox was created, so answering "" — which-// means "no live sandbox" everywhere else — would hide a real sandbox whose-// backend nobody recorded, leaving the orphan reaper as the only way back.+// Pin is called just after a sandbox was created, so answering the zero pin —+// which means "no live sandbox" everywhere else — would hide a real sandbox+// whose backend nobody recorded, leaving the orphan reaper as the only way+// back.func (p *SessionSandboxPinner) Pin(- ctx context.Context, sessionID, configID string,-) (string, error) {- configID = strings.TrimSpace(configID)- if configID == "" {+ ctx context.Context, sessionID string, pin SandboxPin,+) (SandboxPin, error) {+ pin.ConfigID = strings.TrimSpace(pin.ConfigID)+ if pin.ConfigID == "" {// No workspace config means sandbox execution is disabled, so there is// no remote resource whose backend needs pinning.- return "", nil+ return SandboxPin{}, nil}// Two attempts: a concurrent Clear can hand the row back unpinned between// our update and our read, and returning that empty value would be the@@ -99,30 +147,33 @@ func (p *SessionSandboxPinner) Pin(Model(&types.Session{}).Where("id = ? AND (sandbox_config_id IS NULL OR sandbox_config_id = ?)",sessionID, "").- Update("sandbox_config_id", configID)+ Updates(map[string]any{+ "sandbox_config_id": pin.ConfigID,+ "sandbox_config_tenant_id": pin.TenantID,+ })if result.Error != nil {- return "", result.Error+ return SandboxPin{}, result.Error}if result.RowsAffected > 0 {- return configID, nil+ return pin, nil}pinned, found, err := p.read(ctx, sessionID)if err != nil {- return "", err+ return SandboxPin{}, err}if !found {- return "", fmt.Errorf(+ return SandboxPin{}, fmt.Errorf("sandbox: pin session %s to config %s: %w",- sessionID, configID, gorm.ErrRecordNotFound)+ sessionID, pin.ConfigID, gorm.ErrRecordNotFound)}- if pinned != "" {+ if !pinned.IsZero() {// Someone else pinned first; adopt their choice.return pinned, nil}}- return "", fmt.Errorf(+ return SandboxPin{}, fmt.Errorf("sandbox: pin session %s to config %s: lost the claim race twice",- sessionID, configID)+ sessionID, pin.ConfigID)}// Clear releases the pin once the sandbox is gone, so the session's next@@ -130,19 +181,44 @@ func (p *SessionSandboxPinner) Pin(//// Best effort by nature: when the reaper reclaims an orphan from the provider// side the binding is already gone, so there is nothing to map back to a-// session and the pin is left stale. Readers must therefore treat a non-empty+// session and the pin is left stale. Readers must therefore treat a non-zero// pin as a hint, not a guarantee that the sandbox still exists.func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) error {return p.db.WithContext(ctx).Model(&types.Session{}).Where("id = ?", sessionID).- Update("sandbox_config_id", nil).Error+ Updates(map[string]any{+ "sandbox_config_id": nil,+ "sandbox_config_tenant_id": 0,+ }).Error+}++// recordOwner fills sandbox_config_tenant_id on a pin written before the+// column existed (value 0). It must not overwrite a recorded owner: the pin+// is sticky, and a later shared agent from a different workspace is not the+// owner of this config.+func (p *SessionSandboxPinner) recordOwner(+ ctx context.Context, sessionID string, tenantID uint64,+) error {+ if p == nil || p.db == nil || tenantID == 0 || strings.TrimSpace(sessionID) == "" {+ return nil+ }+ return p.db.WithContext(ctx).+ Model(&types.Session{}).+ Where("id = ? AND sandbox_config_tenant_id = 0 AND sandbox_config_id IS NOT NULL AND sandbox_config_id <> ?",+ sessionID, "").+ Update("sandbox_config_tenant_id", tenantID).Error}// resolveSandboxForExecution resolves before pinning so non-remote workspace// backends never leave a permanent session pin. Remote backends// pin before their first Create; concurrent callers adopt and re-resolve the// winning config before executing anything.+//+// tenantID is the workspace that owns agentConfigID, which for a shared agent+// is its owner rather than the session's. An existing pin carries its own+// owner and is resolved under that; tenantID only fills in for pins written+// before the owner was recorded.func resolveSandboxForExecution(ctx context.Context,resolver sandbox.TenantSandboxResolver,@@ -152,52 +228,76 @@ func resolveSandboxForExecution(sessionID string,agentConfigID string,policy WorkspaceSandboxPolicy,-) (sandbox.Manager, string, error) {+) (sandbox.Manager, SandboxPin, error) {if pinner != nil && strings.TrimSpace(sessionID) != "" {pinned, err := pinner.Read(ctx, sessionID)if err != nil {- return nil, "", err+ return nil, SandboxPin{}, err}- if pinned != "" {+ if !pinned.IsZero() {+ owner := pinned.TenantOr(tenantID)mgr, err := resolveTenantSandboxForConfig(- ctx, resolver, fallback, tenantID, pinned, policy,+ ctx, resolver, fallback, owner, pinned.ConfigID, policy,)+ // Only persist an owner that actually resolved this config. Writing+ // the caller's tenant on a failed lookup would stamp the wrong+ // workspace onto a sticky pin left by a previous shared agent.+ //+ // A nil error is not that proof on its own. resolveTenantSandboxForConfig+ // returns a disabled manager with no error before it ever reads the+ // config row: once for the workspace kill switch, once for an empty+ // or deployment-default config id. A named backend is the proof,+ // and it is the same condition that is allowed to CREATE a pin+ // below — what may write a pin may update whose it is.+ //+ // A config that exists but resolves to type "disabled" is skipped+ // too. Ownership is genuine there, but such a config never creates+ // a sandbox, so there is nothing whose teardown could go missing.+ proven := err == nil && mgr != nil &&+ sandbox.IsNamedSandboxBackendType(string(mgr.GetType()))+ if proven && pinned.TenantID == 0 && owner != 0 {+ if recErr := pinner.recordOwner(ctx, sessionID, owner); recErr != nil {+ logger.Warnf(ctx, "Failed to record sandbox pin owner for session %s: %v",+ sessionID, recErr)+ }+ pinned.TenantID = owner+ }return mgr, pinned, err}}- configID := strings.TrimSpace(agentConfigID)+ pin := SandboxPin{ConfigID: strings.TrimSpace(agentConfigID), TenantID: tenantID}mgr, err := resolveTenantSandboxForConfig(- ctx, resolver, fallback, tenantID, configID, policy,+ ctx, resolver, fallback, tenantID, pin.ConfigID, policy,)if err != nil || mgr == nil {- return mgr, configID, err+ return mgr, pin, err}// Named backends (Cube, E2B, Docker) all keep a session-scoped sandbox.// Artifact collection and teardown resolve that sandbox from this pin, so// skipping Docker here leaves /workspace/output files uncollected.if !sandbox.IsNamedSandboxBackendType(string(mgr.GetType())) {- return mgr, configID, nil+ return mgr, pin, nil}if pinner == nil || strings.TrimSpace(sessionID) == "" {- return mgr, configID, nil+ return mgr, pin, nil}- winner, err := pinner.Pin(ctx, sessionID, configID)+ winner, err := pinner.Pin(ctx, sessionID, pin)if err != nil {- return nil, "", err+ return nil, SandboxPin{}, err}- if winner == configID {+ if winner == pin {return mgr, winner, nil}mgr, err = resolveTenantSandboxForConfig(- ctx, resolver, fallback, tenantID, winner, policy,+ ctx, resolver, fallback, winner.TenantOr(tenantID), winner.ConfigID, policy,)return mgr, winner, err}-// sandboxConfigForExistingSandbox returns the config an already-created-// sandbox lives on, or "" when the session has none.+// sandboxConfigForExistingSandbox returns the backend an already-created+// sandbox lives on, or the zero pin when the session has none.//// Artifact collection and teardown deliberately never consult the agent: the// agent's current choice may no longer describe the long-lived sandbox they are@@ -206,9 +306,9 @@ func sandboxConfigForExistingSandbox(ctx context.Context,pinner *SessionSandboxPinner,sessionID string,-) (string, error) {+) (SandboxPin, error) {if pinner == nil || strings.TrimSpace(sessionID) == "" {- return "", nil+ return SandboxPin{}, nil}return pinner.Read(ctx, sessionID)}diff --git a/internal/application/service/session_sandbox_pin_test.go b/internal/application/service/session_sandbox_pin_test.goindex ca5d809d8..917283d01 100644--- a/internal/application/service/session_sandbox_pin_test.go+++ b/internal/application/service/session_sandbox_pin_test.go@@ -40,13 +40,13 @@ func TestPinWritesWhenUnset(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- got, err := pinner.Pin(ctx, "s-1", "cfg-a")+ got, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.NoError(t, err)- require.Equal(t, "cfg-a", got)+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, got)read, err := pinner.Read(ctx, "s-1")require.NoError(t, err)- require.Equal(t, "cfg-a", read)+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, read)}// Two concurrent first-sandbox creations must converge on one config, or the@@ -55,20 +55,20 @@ func TestPinIsIdempotentAndReturnsExistingWinner(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- first, err := pinner.Pin(ctx, "s-1", "cfg-a")+ first, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.NoError(t, err)- require.Equal(t, "cfg-a", first)+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, first)- second, err := pinner.Pin(ctx, "s-1", "cfg-b")+ second, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-b"})require.NoError(t, err)- require.Equal(t, "cfg-a", second, "the first writer wins; later callers adopt it")+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, second, "the first writer wins; later callers adopt it")}func TestPinLeavesEmptyConfigUnpinned(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- got, err := pinner.Pin(ctx, "s-1", "")+ got, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: ""})require.NoError(t, err)require.Empty(t, got)}@@ -79,13 +79,13 @@ func TestPinTrimsConfigIDBeforeStoring(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- got, err := pinner.Pin(ctx, "s-1", " cfg-a ")+ got, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: " cfg-a "})require.NoError(t, err)- require.Equal(t, "cfg-a", got)+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, got)read, err := pinner.Read(ctx, "s-1")require.NoError(t, err)- require.Equal(t, "cfg-a", read)+ require.Equal(t, SandboxPin{ConfigID: "cfg-a"}, read)}// Pin runs right after a sandbox was created, so a vanished session must be an@@ -95,11 +95,11 @@ func TestPinFailsWhenSessionIsGone(t *testing.T) {pinner := NewSessionSandboxPinner(db)ctx := context.Background()- _, err := pinner.Pin(ctx, "missing", "cfg-a")+ _, err := pinner.Pin(ctx, "missing", SandboxPin{ConfigID: "cfg-a"})require.ErrorIs(t, err, gorm.ErrRecordNotFound)require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)- _, err = pinner.Pin(ctx, "s-1", "cfg-a")+ _, err = pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.ErrorIs(t, err, gorm.ErrRecordNotFound,"a soft-deleted session already had its sandbox destroyed")}@@ -120,7 +120,7 @@ func TestClearReleasesPin(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- _, err := pinner.Pin(ctx, "s-1", "cfg-a")+ _, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.NoError(t, err)require.NoError(t, pinner.Clear(ctx, "s-1"))@@ -137,7 +137,7 @@ func TestSoftDeleteHidesSandboxPin(t *testing.T) {pinner := NewSessionSandboxPinner(db)ctx := context.Background()- _, err := pinner.Pin(ctx, "s-1", "cfg-a")+ _, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.NoError(t, err)require.NoError(t, db.Delete(&types.Session{}, "id = ?", "s-1").Error)@@ -151,14 +151,14 @@ func TestResolveSandboxForExecutionDoesNotPinStatelessBackend(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))want := &pinTestManager{typ: sandbox.SandboxTypeDisabled}- got, configID, err := resolveSandboxForExecution(+ got, pin, err := resolveSandboxForExecution(context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,7, "s-1", "cfg-local", nil,)require.NoError(t, err)require.Same(t, want, got)- require.Equal(t, "cfg-local", configID)+ require.Equal(t, SandboxPin{ConfigID: "cfg-local", TenantID: 7}, pin)pinned, err := pinner.Read(context.Background(), "s-1")require.NoError(t, err)require.Empty(t, pinned, "disabled backends must not leave a session binding")@@ -168,17 +168,17 @@ func TestResolveSandboxForExecutionPinsRemoteBackend(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))want := &pinTestManager{typ: sandbox.SandboxTypeCube}- got, configID, err := resolveSandboxForExecution(+ got, pin, err := resolveSandboxForExecution(context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,7, "s-1", "cfg-cube", nil,)require.NoError(t, err)require.Same(t, want, got)- require.Equal(t, "cfg-cube", configID)+ require.Equal(t, SandboxPin{ConfigID: "cfg-cube", TenantID: 7}, pin)pinned, err := pinner.Read(context.Background(), "s-1")require.NoError(t, err)- require.Equal(t, "cfg-cube", pinned)+ require.Equal(t, SandboxPin{ConfigID: "cfg-cube", TenantID: 7}, pinned)}// Docker is a session-persistent remote backend, same as Cube/E2B. Skipping@@ -188,32 +188,220 @@ func TestResolveSandboxForExecutionPinsDockerBackend(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))want := &pinTestManager{typ: sandbox.SandboxTypeDocker}- got, configID, err := resolveSandboxForExecution(+ got, pin, err := resolveSandboxForExecution(context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,7, "s-1", "cfg-docker", nil,)require.NoError(t, err)require.Same(t, want, got)- require.Equal(t, "cfg-docker", configID)+ require.Equal(t, SandboxPin{ConfigID: "cfg-docker", TenantID: 7}, pin)pinned, err := pinner.Read(context.Background(), "s-1")require.NoError(t, err)- require.Equal(t, "cfg-docker", pinned)+ require.Equal(t, SandboxPin{ConfigID: "cfg-docker", TenantID: 7}, pinned)}func TestResolveSandboxForExecutionKeepsExistingRemotePin(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))- _, err := pinner.Pin(context.Background(), "s-1", "cfg-existing")+ _, err := pinner.Pin(context.Background(), "s-1", SandboxPin{ConfigID: "cfg-existing"})require.NoError(t, err)want := &pinTestManager{typ: sandbox.SandboxTypeE2B}- got, configID, err := resolveSandboxForExecution(+ got, pin, err := resolveSandboxForExecution(context.Background(), stubSandboxResolver{mgr: want}, nil, pinner,7, "s-1", "cfg-new-agent-choice", nil,)require.NoError(t, err)require.Same(t, want, got)- require.Equal(t, "cfg-existing", configID,+ require.Equal(t, SandboxPin{ConfigID: "cfg-existing", TenantID: 7}, pin,"re-pointing an agent must not move an existing remote session")}++// A shared agent runs on ITS OWNER's sandbox config, so the pin has to record+// that workspace: everything outside the chat turn (teardown, the terminal and+// desktop panels, fork snapshots) runs as the session owner and would+// otherwise look the config up in a workspace that does not have it.+func TestResolveSandboxForExecutionPinsTheConfigOwningWorkspace(t *testing.T) {+ const sessionOwner, agentOwner = uint64(7), uint64(99)+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ resolver := &tenantRecordingResolver{mgr: &pinTestManager{typ: sandbox.SandboxTypeCube}}++ _, pin, err := resolveSandboxForExecution(+ context.Background(), resolver, nil, pinner,+ agentOwner, "s-1", "cfg-owned-by-99", nil,+ )+ require.NoError(t, err)+ require.Equal(t, SandboxPin{ConfigID: "cfg-owned-by-99", TenantID: agentOwner}, pin)++ stored, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Equal(t, agentOwner, stored.TenantID, "the lending workspace is durable")+ require.Equal(t, agentOwner, stored.TenantOr(sessionOwner),+ "a borrowed pin ignores the session's own workspace")+}++// An own agent's config already lives in the session's workspace, so the pin+// stays owner-less and TenantOr keeps resolving it exactly as before. This is+// what makes the new column a no-op for every existing session.+func TestSandboxPinTenantOrFallsBackToTheSessionWorkspace(t *testing.T) {+ require.Equal(t, uint64(7), SandboxPin{ConfigID: "cfg-a"}.TenantOr(7))+ require.Equal(t, uint64(99), SandboxPin{ConfigID: "cfg-a", TenantID: 99}.TenantOr(7))+ require.True(t, SandboxPin{}.IsZero())+ require.False(t, SandboxPin{ConfigID: "cfg-a"}.IsZero())+}++// Pre-migration pins (and any row the SQL backfill missed) store TenantID=0.+// The next chat turn already knows the workspace that can resolve the config;+// persisting it is what lets DELETE / the panel / fork find that sandbox later+// instead of looking it up as the session owner and leaking a paused MicroVM.+func TestResolveSandboxForExecutionPersistsOwnerOnLegacyPin(t *testing.T) {+ const agentOwner = uint64(99)+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: "cfg-owned-by-99"})+ require.NoError(t, err)++ resolver := &tenantRecordingResolver{mgr: &pinTestManager{typ: sandbox.SandboxTypeCube}}+ _, pin, err := resolveSandboxForExecution(+ context.Background(), resolver, nil, pinner,+ agentOwner, "s-1", "", nil,+ )+ require.NoError(t, err)+ require.Equal(t, SandboxPin{ConfigID: "cfg-owned-by-99", TenantID: agentOwner}, pin)++ stored, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Equal(t, agentOwner, stored.TenantID,+ "a successful resolve must record the workspace that owns the pin")+}++// A pin resolves in the workspace it recorded, not the one on the context.+func TestResolveSandboxForExecutionResolvesPinnedConfigInItsOwnWorkspace(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: "cfg-owned-by-99", TenantID: 99})+ require.NoError(t, err)+ resolver := &tenantRecordingResolver{mgr: &pinTestManager{typ: sandbox.SandboxTypeCube}}++ _, pin, err := resolveSandboxForExecution(+ context.Background(), resolver, nil, pinner,+ 7 /* the borrower, e.g. a teardown or panel-open caller */, "s-1", "", nil,+ )++ require.NoError(t, err)+ require.Equal(t, uint64(99), resolver.lastTenant)+ require.Equal(t, "cfg-owned-by-99", resolver.lastConfig)+ require.Equal(t, SandboxPin{ConfigID: "cfg-owned-by-99", TenantID: 99}, pin)+}++// A failed lookup must not stamp the caller's workspace onto a legacy pin:+// the config may belong to a previous shared agent, and the pin is sticky.+func TestResolveSandboxForExecutionDoesNotPersistOwnerWhenResolveFails(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: "cfg-owned-by-99"})+ require.NoError(t, err)++ resolver := failingSandboxResolver{}+ _, pin, err := resolveSandboxForExecution(+ context.Background(), resolver, nil, pinner,+ 7, "s-1", "", nil,+ )+ require.ErrorIs(t, err, sandbox.ErrSandboxConfigNotFound)+ require.Equal(t, uint64(0), pin.TenantID)++ stored, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Zero(t, stored.TenantID, "a failed lookup must leave the owner unset")+}++// resolveTenantSandboxForConfig answers the workspace kill switch with a+// disabled manager and NO error, before it ever reads the config row. A nil+// error is therefore not proof that this workspace owns the pinned config, and+// stamping it would brand a legacy pin with a workspace that cannot resolve it+// — recreating the stranded MicroVM this column exists to prevent.+//+// The end-to-end shape: a session of workspace 7 pinned to a config workspace 7+// owns (left at 0 by the backfill, correctly), then one turn of a shared agent+// lent by workspace 99 whose admin has script execution turned off.+func TestResolveSandboxForExecutionDoesNotPersistOwnerBehindTheKillSwitch(t *testing.T) {+ const sessionOwner, lender = uint64(7), uint64(99)+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1", SandboxPin{ConfigID: "cfg-owned-by-7"})+ require.NoError(t, err)++ // The resolver must never be reached: the kill switch short-circuits first.+ _, pin, err := resolveSandboxForExecution(+ context.Background(), failingSandboxResolver{}, nil, pinner,+ lender, "s-1", "", scriptsDisabledPolicy{},+ )+ require.NoError(t, err, "the kill switch returns a disabled manager, not an error")+ require.Zero(t, pin.TenantID)++ stored, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Zero(t, stored.TenantID,+ "workspace 99 never proved it owns this config, so it must not be recorded")++ // The pin is still resolvable as the session's own workspace, which is what+ // keeps DELETE able to reclaim the MicroVM.+ mgr := &pinTestManager{typ: sandbox.SandboxTypeCube}+ recorder := &tenantRecordingResolver{mgr: mgr}+ _, _, err = resolveSandboxForExecution(+ context.Background(), recorder, nil, pinner, sessionOwner, "s-1", "", nil,+ )+ require.NoError(t, err)+ require.Equal(t, sessionOwner, recorder.lastTenant)+ require.Equal(t, "cfg-owned-by-7", recorder.lastConfig)+}++// The deployment-default pin short-circuits on the config id before the tenant+// is used at all, so nothing is recorded for it either. Pinning this down keeps+// a later relaxation of the proof from quietly reopening the case above.+func TestResolveSandboxForExecutionDoesNotPersistOwnerForTheDefaultConfig(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: types.SandboxConfigIDGlobalDefault})+ require.NoError(t, err)++ mgr, pin, err := resolveSandboxForExecution(+ context.Background(), failingSandboxResolver{}, nil, pinner, 99, "s-1", "", nil,+ )+ require.NoError(t, err)+ require.Equal(t, sandbox.SandboxTypeDisabled, mgr.GetType())+ require.Zero(t, pin.TenantID)++ stored, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Zero(t, stored.TenantID, "the deployment default has no owning workspace")+}++type failingSandboxResolver struct{}++func (failingSandboxResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {+ return nil, sandbox.ErrSandboxConfigNotFound+}++// scriptsDisabledPolicy is the workspace kill switch an admin turns on.+type scriptsDisabledPolicy struct{}++func (scriptsDisabledPolicy) WorkspaceScriptsDisabled(+ context.Context, uint64,+) (bool, error) {+ return true, nil+}++// tenantRecordingResolver reports which workspace a config was looked up in.+type tenantRecordingResolver struct {+ mgr sandbox.Manager+ lastTenant uint64+ lastConfig string+}++func (r *tenantRecordingResolver) Resolve(+ _ context.Context, tenantID uint64, configID string,+) (sandbox.Manager, error) {+ r.lastTenant, r.lastConfig = tenantID, configID+ return r.mgr, nil+}diff --git a/internal/application/service/shared_agent_sandbox_tenant_test.go b/internal/application/service/shared_agent_sandbox_tenant_test.gonew file mode 100644index 000000000..3ee81632e--- /dev/null+++ b/internal/application/service/shared_agent_sandbox_tenant_test.go@@ -0,0 +1,216 @@+package service++import (+ "context"+ "fmt"+ "testing"++ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++// A shared agent runs in ITS OWNER's workspace, so its sandbox is created on+// that workspace's config. Everything that touches the sandbox outside the+// chat turn — session teardown, the terminal and desktop panels, fork+// snapshots — runs from a plain request whose only tenant is the session+// owner's. Resolving a lent config there finds nothing, because+// tenant_sandbox_configs is keyed by (tenant_id, id).+//+// These tests pin the fix: the workspace travels with the config id.+const (+ borrowerTenant = uint64(7) // owns the session+ lenderTenant = uint64(99) // owns the shared agent and its sandbox config+ lentSandboxConfig = "cfg-owned-by-lender"+)++// lendingResolver mirrors tenantSandboxResolver.Resolve: a config resolves in+// exactly one workspace and is "not found" anywhere else.+type lendingResolver struct {+ mgr sandbox.Manager+ lastTenant uint64+ lastConfig string+}++func (r *lendingResolver) Resolve(+ _ context.Context, tenantID uint64, configID string,+) (sandbox.Manager, error) {+ r.lastTenant, r.lastConfig = tenantID, configID+ if tenantID != lenderTenant || configID != lentSandboxConfig {+ return nil, fmt.Errorf("%w: %s", sandbox.ErrSandboxConfigNotFound, configID)+ }+ return r.mgr, nil+}++// destroyRecordingManager records the sessions it was asked to tear down.+type destroyRecordingManager struct {+ destroyed []string+ bound string+}++func (m *destroyRecordingManager) Execute(+ context.Context, *sandbox.ExecuteConfig,+) (*sandbox.ExecuteResult, error) {+ return nil, nil+}+func (m *destroyRecordingManager) Cleanup(context.Context) error { return nil }+func (m *destroyRecordingManager) GetSandbox() sandbox.Sandbox { return nil }+func (m *destroyRecordingManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }++func (m *destroyRecordingManager) DestroySession(_ context.Context, sessionID string) error {+ m.destroyed = append(m.destroyed, sessionID)+ return nil+}++func (m *destroyRecordingManager) BoundSandboxID(context.Context, string) (string, bool) {+ return m.bound, m.bound != ""+}++func borrowedSessionDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})+ require.NoError(t, err)+ _ = db.Migrator().DropTable(&types.Session{})+ require.NoError(t, db.AutoMigrate(&types.Session{}))+ require.NoError(t, db.Model(&types.Session{}).Create(map[string]any{+ "id": "s-1", "tenant_id": borrowerTenant,+ }).Error)+ return db+}++// borrowerCtx is what a DELETE /sessions/:id or a panel-open handshake carries:+// the session owner, with no trace of the workspace that lent the agent.+func borrowerCtx() context.Context {+ return context.WithValue(context.Background(), types.TenantIDContextKey, borrowerTenant)+}++// Session sandboxes are created with onTimeout=pause on Cube and E2B, so a+// teardown that resolves nothing does not merely log a warning: it abandons a+// paused MicroVM that keeps billing with nobody holding its id.+func TestDestroyBoundSandboxTearsDownALentWorkspacesSandbox(t *testing.T) {+ pinner := NewSessionSandboxPinner(borrowedSessionDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: lentSandboxConfig, TenantID: lenderTenant})+ require.NoError(t, err)++ mgr := &destroyRecordingManager{}+ resolver := &lendingResolver{mgr: mgr}+ svc := &sessionService{sandboxPinner: pinner, sandboxResolver: resolver}++ svc.destroyBoundSandbox(borrowerCtx(), "s-1")++ require.Equal(t, []string{"s-1"}, mgr.destroyed)+ require.Equal(t, lenderTenant, resolver.lastTenant,+ "teardown must look the config up where it exists")++ pin, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.True(t, pin.IsZero(), "a destroyed sandbox releases its pin")+}++// An own agent's pin carries no workspace, so teardown keeps resolving it in+// the session's own — unchanged behaviour, and what every pre-existing row+// falls back to after the migration.+func TestDestroyBoundSandboxStillUsesTheSessionWorkspaceForOwnAgents(t *testing.T) {+ pinner := NewSessionSandboxPinner(borrowedSessionDB(t))+ _, err := pinner.Pin(context.Background(), "s-1", SandboxPin{ConfigID: "cfg-local"})+ require.NoError(t, err)++ mgr := &destroyRecordingManager{}+ resolver := &tenantRecordingResolver{mgr: mgr}+ svc := &sessionService{sandboxPinner: pinner, sandboxResolver: resolver}++ svc.destroyBoundSandbox(borrowerCtx(), "s-1")++ require.Equal(t, []string{"s-1"}, mgr.destroyed)+ require.Equal(t, borrowerTenant, resolver.lastTenant)+ require.Equal(t, "cfg-local", resolver.lastConfig)+}++// Attaching to an existing sandbox: the panel open is a GET as the session+// owner, and the pin is the only thing that knows where the sandbox lives.+func TestTerminalAttachResolvesTheLentWorkspace(t *testing.T) {+ pinner := NewSessionSandboxPinner(borrowedSessionDB(t))+ _, err := pinner.Pin(context.Background(), "s-1",+ SandboxPin{ConfigID: lentSandboxConfig, TenantID: lenderTenant})+ require.NoError(t, err)++ mgr := &destroyRecordingManager{}+ resolver := &lendingResolver{mgr: mgr}+ svc := NewSandboxTerminalService(pinner, resolver, nil, nil)++ got, pin, err := svc.resolveSessionManager(borrowerCtx(), "s-1")++ require.NoError(t, err)+ require.Same(t, mgr, got)+ require.Equal(t, SandboxPin{ConfigID: lentSandboxConfig, TenantID: lenderTenant}, pin)+ require.Equal(t, lenderTenant, resolver.lastTenant)+}++// Creating the first sandbox from the panel: there is no pin yet, so the+// workspace has to arrive with the agent's config from the WebSocket handler.+func TestTerminalProvisionUsesTheAgentsWorkspace(t *testing.T) {+ pinner := NewSessionSandboxPinner(borrowedSessionDB(t))+ resolver := &lendingResolver{mgr: &destroyRecordingManager{}}+ svc := NewSandboxTerminalService(pinner, resolver, nil, nil)++ // The PTY open that follows fails for this fake manager; what matters here+ // is that resolution and the pin claim happened in the lending workspace.+ _, _ = svc.EnsureSessionTerminal(borrowerCtx(), "s-1",+ SandboxPin{ConfigID: lentSandboxConfig, TenantID: lenderTenant},+ sandbox.RemoteTerminalOptions{})++ require.Equal(t, lenderTenant, resolver.lastTenant)+ require.Equal(t, lentSandboxConfig, resolver.lastConfig)++ pin, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Equal(t, SandboxPin{ConfigID: lentSandboxConfig, TenantID: lenderTenant}, pin,+ "a panel-created sandbox records its workspace like a chat turn does")+}++// A zero provision pin stays lookup-only: opening a panel must never create+// infrastructure on its own.+func TestTerminalProvisionStaysLookupOnlyWithoutAPin(t *testing.T) {+ pinner := NewSessionSandboxPinner(borrowedSessionDB(t))+ resolver := &lendingResolver{mgr: &destroyRecordingManager{}}+ svc := NewSandboxTerminalService(pinner, resolver, nil, nil)++ _, err := svc.EnsureSessionTerminal(+ borrowerCtx(), "s-1", SandboxPin{}, sandbox.RemoteTerminalOptions{})++ require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox)+ require.Zero(t, resolver.lastTenant, "no config means nothing to resolve")+}++// Fork snapshots go through PinnedSessionSandbox, which runs from a plain POST+// as the session owner. Resolving the lent config there used to return nil,+// so BoundSandboxID failed and the fork degraded to SANDBOX_GONE.+func TestPinnedSessionSandboxResolvesTheLentWorkspace(t *testing.T) {+ mgr := &destroyRecordingManager{bound: "sbx-1"}+ resolver := &lendingResolver{mgr: mgr}+ access := NewPinnedSessionSandbox(+ stubPinReader{configID: lentSandboxConfig, tenantID: lenderTenant}, resolver, nil)++ id, ok := access.BoundSandboxID(borrowerCtx(), "s-1")++ require.True(t, ok)+ require.Equal(t, "sbx-1", id)+ require.Equal(t, lenderTenant, resolver.lastTenant)+}++// The fork snapshot lease is reaped by (tenant, config) as a pair, so the+// session has to report the workspace that owns its config, not its own.+func TestSessionSandboxConfigOwnerPrefersTheRecordedWorkspace(t *testing.T) {+ borrowed := &types.Session{TenantID: borrowerTenant, SandboxConfigTenantID: lenderTenant}+ require.Equal(t, lenderTenant, borrowed.SandboxConfigOwner())++ own := &types.Session{TenantID: borrowerTenant}+ require.Equal(t, borrowerTenant, own.SandboxConfigOwner(),+ "an own agent's config lives in the session's own workspace")++ require.Zero(t, (*types.Session)(nil).SandboxConfigOwner())+}diff --git a/internal/application/service/tenant_skill_effective.go b/internal/application/service/tenant_skill_effective.goindex 03d7d012c..83c3a2671 100644--- a/internal/application/service/tenant_skill_effective.go+++ b/internal/application/service/tenant_skill_effective.go@@ -48,8 +48,13 @@ func skillsForRun(sessionID, err)return "", nil}- if pinned != "" {- configID = pinned+ if !pinned.IsZero() {+ configID = pinned.ConfigID+ // A config is read in the workspace that owns it, which for a shared+ // agent is the lending one. tenantID is that same workspace on every+ // path today (the chat turn runs there); taking it from the pin is+ // what keeps the two from drifting apart again.+ tenantID = pinned.TenantOr(tenantID)}return configID, effectiveTenantSkills(ctx, configs, skills, tenantID, configID)}diff --git a/internal/application/service/tenant_skill_effective_test.go b/internal/application/service/tenant_skill_effective_test.goindex ecdba59c8..b36899b44 100644--- a/internal/application/service/tenant_skill_effective_test.go+++ b/internal/application/service/tenant_skill_effective_test.go@@ -231,7 +231,7 @@ func twoConfigFixture(t *testing.T) (*multiConfigRepo, *installSkillRepo) {func TestSkillsForRunPrefersThePinnedConfigOverTheAgents(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()- _, err := pinner.Pin(ctx, "s-1", "cfg-a")+ _, err := pinner.Pin(ctx, "s-1", SandboxPin{ConfigID: "cfg-a"})require.NoError(t, err)configs, skills := twoConfigFixture(t)diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.goindex 4c1a25877..62e52b92d 100644--- a/internal/database/migration_sqlite_versioned_schema_test.go+++ b/internal/database/migration_sqlite_versioned_schema_test.go@@ -34,22 +34,25 @@ var versionedSQLiteTables = []string{// versionedSQLiteColumns maps each existing table to the columns that the// versioned migrations add and the SQLite baseline was missing.var versionedSQLiteColumns = map[string][]string{- "memory_subjects": {"extraction_state"}, // 000094- "memory_items": {"replaces_id"}, // 000094- "tenants": {"api_principal_config"}, // 000064- "users": {"is_system_admin"}, // 000053- "knowledges": {"pending_subtasks_count", "profile"}, // 000056, 000101- "knowledge_bases": {"profile_config", "generated_profile"}, // 000101- "messages": {"attachments", "usage", "sandbox_checkpoint", "context_checkpoint"}, // 000034/085/097/105- "sessions": {"parent_session_id", "forked_from_message_id", "fork_bootstrap"}, // 000097- "tenant_invitations": {"token", "accepted_count"}, // 000054- "embed_channels": {"allow_memory"}, // 000060- "mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064- "mcp_tool_approvals": {"enabled"}, // 000091- "message_artifacts": {"deleted_at"}, // 000107+ "memory_subjects": {"extraction_state"}, // 000094+ "memory_items": {"replaces_id"}, // 000094+ "tenants": {"api_principal_config"}, // 000064+ "users": {"is_system_admin"}, // 000053+ "knowledges": {"pending_subtasks_count", "profile"}, // 000056, 000101+ "knowledge_bases": {"profile_config", "generated_profile"}, // 000101+ "messages": {"attachments", "usage", "sandbox_checkpoint", "context_checkpoint"}, // 000034/085/097/105+ "sessions": {+ "parent_session_id", "forked_from_message_id", "fork_bootstrap", // 000097+ "sandbox_config_tenant_id", // 000108+ },+ "tenant_invitations": {"token", "accepted_count"}, // 000054+ "embed_channels": {"allow_memory"}, // 000060+ "mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064+ "mcp_tool_approvals": {"enabled"}, // 000091+ "message_artifacts": {"deleted_at"}, // 000107}-const expectedSQLiteMigrationVersion = 26+const expectedSQLiteMigrationVersion = 27func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {repoRoot := sqliteRepoRoot(t)diff --git a/internal/handler/session/resolve_agent_test.go b/internal/handler/session/resolve_agent_test.goindex 0988cda92..6f01006a3 100644--- a/internal/handler/session/resolve_agent_test.go+++ b/internal/handler/session/resolve_agent_test.go@@ -7,6 +7,7 @@ import ("net/http/httptest""testing"+ "github.com/Tencent/WeKnora/internal/application/service""github.com/Tencent/WeKnora/internal/types""github.com/gin-gonic/gin""github.com/stretchr/testify/require"@@ -196,7 +197,7 @@ func TestResolveAgent_UsesShareWhenNoOwnAgentMatches(t *testing.T) {require.True(t, sharedReadOnly)}-func TestTerminalProvisionConfigID_UsesSharedAgentSandboxConfig(t *testing.T) {+func TestTerminalProvisionPin_UsesSharedAgentSandboxConfig(t *testing.T) {gin.SetMode(gin.TestMode)rec := httptest.NewRecorder()c, _ := gin.CreateTestContext(rec)@@ -224,7 +225,37 @@ func TestTerminalProvisionConfigID_UsesSharedAgentSandboxConfig(t *testing.T) {}},}- require.Equal(t, "", h.terminalProvisionConfigID(ctx, c, false),+ require.Equal(t, service.SandboxPin{}, h.terminalProvisionPin(ctx, c, false),"lookup-only connects must not resolve an agent config")- require.Equal(t, "shared-cfg", h.terminalProvisionConfigID(ctx, c, true))+ // The lending workspace travels with the config id: sandbox configs are+ // keyed by (tenant, id), so "shared-cfg" does not exist in workspace 7.+ require.Equal(t,+ service.SandboxPin{ConfigID: "shared-cfg", TenantID: 84},+ h.terminalProvisionPin(ctx, c, true))+}++// An own agent's config already lives in the caller's workspace, so the pin+// carries no owner and SandboxPin.TenantOr falls back to the request tenant.+func TestTerminalProvisionPin_OwnAgentCarriesNoWorkspace(t *testing.T) {+ gin.SetMode(gin.TestMode)+ rec := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(rec)+ c.Request = httptest.NewRequest(+ http.MethodGet, "/?agent_id=builtin-smart-reasoning", nil)+ c.Set(types.UserIDContextKey.String(), "user-1")+ c.Set(types.TenantIDContextKey.String(), uint64(7))+ ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))+ c.Request = c.Request.WithContext(ctx)++ h := &Handler{+ customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{+ ID: "builtin-smart-reasoning",+ TenantID: 7,+ Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},+ }},+ }++ pin := h.terminalProvisionPin(ctx, c, true)+ require.Equal(t, service.SandboxPin{ConfigID: "local-cfg"}, pin)+ require.Equal(t, uint64(7), pin.TenantOr(7))}diff --git a/internal/handler/session/sandbox_desktop_ws.go b/internal/handler/session/sandbox_desktop_ws.goindex b04bd9486..586d8aa89 100644--- a/internal/handler/session/sandbox_desktop_ws.go+++ b/internal/handler/session/sandbox_desktop_ws.go@@ -226,8 +226,8 @@ func (h *Handler) SandboxDesktopWS(c *gin.Context) {defer cancelEnsure()}allowProvision := terminalFlagParam(c.Query("provision"))- provisionID := h.terminalProvisionConfigID(ensureCtx, c, allowProvision)- desktop, err := h.desktopService.EnsureSessionDesktop(ensureCtx, sessionID, provisionID)+ provision := h.terminalProvisionPin(ensureCtx, c, allowProvision)+ desktop, err := h.desktopService.EnsureSessionDesktop(ensureCtx, sessionID, provision)if err != nil {if slotHold != nil && slotHold.Err() != nil {c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})diff --git a/internal/handler/session/sandbox_desktop_ws_test.go b/internal/handler/session/sandbox_desktop_ws_test.goindex 8217ab915..92fa58d4d 100644--- a/internal/handler/session/sandbox_desktop_ws_test.go+++ b/internal/handler/session/sandbox_desktop_ws_test.go@@ -259,8 +259,8 @@ func TestSandboxDesktopWSLookupIsOptInProvision(t *testing.T) {require.NoError(t, err)text := string(src)require.Contains(t, text, `allowProvision := terminalFlagParam(c.Query("provision"))`)- require.Contains(t, text, `h.terminalProvisionConfigID(ensureCtx, c, allowProvision)`)- require.NotContains(t, text, `terminalProvisionConfigID(ctx, c, true)`)+ require.Contains(t, text, `h.terminalProvisionPin(ensureCtx, c, allowProvision)`)+ require.NotContains(t, text, `terminalProvisionPin(ctx, c, true)`)// The JS WebSocket API never exposes a failed handshake's HTTP status.// Overlay states (not bound / paused) have to ride a close reason after// upgrade, or the panel shows a generic error instead of the confirm card.diff --git a/internal/handler/session/sandbox_terminal_ws.go b/internal/handler/session/sandbox_terminal_ws.goindex d5b1f5d59..a3458890f 100644--- a/internal/handler/session/sandbox_terminal_ws.go+++ b/internal/handler/session/sandbox_terminal_ws.go@@ -202,7 +202,7 @@ func (h *Handler) SandboxTerminalWS(c *gin.Context) {// missing one reports SANDBOX_NOT_BOUND. Only a confirmed click sets// provision=1, which may create or resume.allowProvision := terminalFlagParam(c.Query("provision"))- sandboxConfigID := h.terminalProvisionConfigID(ctx, c, allowProvision)+ provision := h.terminalProvisionPin(ctx, c, allowProvision)// Geometry from the query string; the frontend resizes right after// ready anyway, so defaults only shape the first paint.@@ -215,7 +215,7 @@ func (h *Handler) SandboxTerminalWS(c *gin.Context) {// The connection outlives the HTTP exchange, so the terminal lifetime is// governed by this derived context, cancelled in cleanup().termCtx, cancelTerm := context.WithCancel(context.WithoutCancel(ctx))- terminal, err := h.openTerminal(termCtx, sessionID, sandboxConfigID, allowProvision, opts)+ terminal, err := h.openTerminal(termCtx, sessionID, provision, allowProvision, opts)if err != nil {code, detail := terminalErrorFrame(err)logger.Warnf(ctx, "[sandbox-terminal] open failed session=%s provision=%t code=%s: %v",@@ -252,33 +252,47 @@ func (h *Handler) SandboxTerminalWS(c *gin.Context) {// action may create infrastructure.func (h *Handler) openTerminal(ctx context.Context,- sessionID, sandboxConfigID string,+ sessionID string,+ provision service.SandboxPin,allowProvision bool,opts sandbox.RemoteTerminalOptions,) (*service.SessionTerminal, error) {if allowProvision {- return h.terminalService.EnsureSessionTerminal(ctx, sessionID, sandboxConfigID, opts)+ return h.terminalService.EnsureSessionTerminal(ctx, sessionID, provision, opts)}return h.terminalService.OpenSessionTerminal(ctx, sessionID, opts)}-// terminalProvisionConfigID resolves the sandbox config a confirmed create-// should use. It goes through resolveAgent so a shared agent from another-// workspace provisions the same way a chat turn would, instead of looking the-// agent up only in the current tenant.-func (h *Handler) terminalProvisionConfigID(ctx context.Context, c *gin.Context, allowProvision bool) string {+// terminalProvisionPin resolves the sandbox backend a confirmed create should+// use. It goes through resolveAgent so a shared agent from another workspace+// provisions the same way a chat turn would, instead of looking the agent up+// only in the current tenant.+//+// The agent's workspace travels with its config id. Sandbox configs are keyed+// by (tenant, id), so a shared agent's config simply does not exist in the+// caller's own workspace — passing the id alone resolved to "config not found"+// and the panel died with a bare INTERNAL frame.+func (h *Handler) terminalProvisionPin(+ ctx context.Context, c *gin.Context, allowProvision bool,+) service.SandboxPin {if !allowProvision || h == nil || c == nil {- return ""+ return service.SandboxPin{}}agentID := strings.TrimSpace(c.Query("agent_id"))if agentID == "" {- return ""+ return service.SandboxPin{}}- agent, _, _ := h.resolveAgent(ctx, c, agentID, terminalTenantParam(c.Query("agent_source_tenant_id")))+ agent, agentTenantID, _ := h.resolveAgent(+ ctx, c, agentID, terminalTenantParam(c.Query("agent_source_tenant_id")))if agent == nil {- return ""+ return service.SandboxPin{}+ }+ // resolveAgent reports 0 for the caller's own agent, which is exactly the+ // "use the request workspace" fallback SandboxPin.TenantOr applies.+ return service.SandboxPin{+ ConfigID: strings.TrimSpace(agent.Config.SandboxConfigID),+ TenantID: agentTenantID,}- return strings.TrimSpace(agent.Config.SandboxConfigID)}func terminalTenantParam(raw string) uint64 {diff --git a/internal/types/session.go b/internal/types/session.goindex 1de44a147..4c1c72d1b 100644--- a/internal/types/session.go+++ b/internal/types/session.go@@ -109,6 +109,17 @@ type Session struct {// permanent would make "no session references this config" never true.SandboxConfigID string `json:"sandbox_config_id,omitempty" gorm:"type:varchar(36)"`+ // SandboxConfigTenantID names the workspace that owns SandboxConfigID.+ // Sandbox configs are keyed by (tenant, id), so the id above is not an+ // address on its own: a shared agent's sandbox lives on ITS OWNER's config+ // while this session belongs to the borrower, and resolving that config+ // under the borrower finds nothing.+ //+ // Zero means "this session's own tenant", which covers every sandbox+ // created by an agent the session's workspace owns, plus pins written+ // before the column existed.+ SandboxConfigTenantID uint64 `json:"-" gorm:"column:sandbox_config_tenant_id;type:bigint;default:0"`+// ParentSessionID names the session this one was forked from. Empty for// ordinary sessions. Deliberately not a foreign key: the parent may be// deleted while the branch lives on, and a branch must not cascade away@@ -162,6 +173,22 @@ func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {return nil}+// SandboxConfigOwner returns the workspace SandboxConfigID must be looked up+// in. Sandbox configs are keyed by (tenant, id), so the two always travel+// together; a shared agent's sandbox lives on the LENDING workspace's config+// while the session belongs to the borrower. Zero falls back to the session's+// own tenant, which is right for every sandbox an own agent created and for+// pins written before the owner was recorded.+func (s *Session) SandboxConfigOwner() uint64 {+ if s == nil {+ return 0+ }+ if s.SandboxConfigTenantID != 0 {+ return s.SandboxConfigTenantID+ }+ return s.TenantID+}+// SessionSourceAPI is the source filter that lists every session created via a// tenant API key across the whole tenant. It is an admin-only view: the service// layer requires Admin+ and drops the per-user owner scope so a tenantdiff --git a/migrations/sqlite/000027_session_sandbox_config_tenant.down.sql b/migrations/sqlite/000027_session_sandbox_config_tenant.down.sqlnew file mode 100644index 000000000..2c7d9c492--- /dev/null+++ b/migrations/sqlite/000027_session_sandbox_config_tenant.down.sql@@ -0,0 +1 @@+ALTER TABLE sessions DROP COLUMN sandbox_config_tenant_id;diff --git a/migrations/sqlite/000027_session_sandbox_config_tenant.up.sql b/migrations/sqlite/000027_session_sandbox_config_tenant.up.sqlnew file mode 100644index 000000000..b9da0bb3d--- /dev/null+++ b/migrations/sqlite/000027_session_sandbox_config_tenant.up.sql@@ -0,0 +1,8 @@+-- Mirrors versioned migration 000108_session_sandbox_config_tenant: the pinned+-- sandbox config resolves in exactly one workspace, so the pin records which.+--+-- No backfill here. Lite has no shared spaces (see docs/LITE.md), so a session+-- can never be pinned to another workspace's config; the column exists only so+-- the shared Session model maps on both engines. INTEGER on SQLite is 64-bit+-- and matches Postgres BIGINT used in 000108.+ALTER TABLE sessions ADD COLUMN sandbox_config_tenant_id INTEGER NOT NULL DEFAULT 0;diff --git a/migrations/versioned/000108_session_sandbox_config_tenant.down.sql b/migrations/versioned/000108_session_sandbox_config_tenant.down.sqlnew file mode 100644index 000000000..8ca9382dd--- /dev/null+++ b/migrations/versioned/000108_session_sandbox_config_tenant.down.sql@@ -0,0 +1,3 @@+DO $$ BEGIN RAISE NOTICE '[Migration 000108 down] Dropping sessions.sandbox_config_tenant_id'; END $$;++ALTER TABLE sessions DROP COLUMN IF EXISTS sandbox_config_tenant_id;diff --git a/migrations/versioned/000108_session_sandbox_config_tenant.up.sql b/migrations/versioned/000108_session_sandbox_config_tenant.up.sqlnew file mode 100644index 000000000..a95ce36fd--- /dev/null+++ b/migrations/versioned/000108_session_sandbox_config_tenant.up.sql@@ -0,0 +1,39 @@+-- Migration: 000108_session_sandbox_config_tenant+-- sessions.sandbox_config_id alone is not an address for a sandbox backend.+-- tenant_sandbox_configs is keyed by (tenant_id, id), so the same config id+-- resolves in exactly one workspace — and a shared agent runs on ITS OWNER's+-- config while the session belongs to the borrower.+--+-- Everything inside a chat turn happened to work because the turn already runs+-- under the agent owner (see WithExecutionTenant in the QA handler). Everything+-- outside it — session teardown, the terminal and desktop panels, fork+-- snapshots — reads the ambient request tenant, which is the borrower, and+-- finds nothing. Teardown then logs a warning and returns, leaving a paused+-- MicroVM nobody holds the id of (Cube/E2B create with onTimeout=pause).+--+-- Recording the owning workspace next to the pin makes the pair travel+-- together. 0 means "the session's own tenant", which is every sandbox created+-- by an agent the session's workspace owns.+DO $$ BEGIN RAISE NOTICE '[Migration 000108] Adding sessions.sandbox_config_tenant_id'; END $$;++ALTER TABLE sessions+ ADD COLUMN IF NOT EXISTS sandbox_config_tenant_id BIGINT NOT NULL DEFAULT 0;++COMMENT ON COLUMN sessions.sandbox_config_tenant_id IS 'Workspace owning sandbox_config_id; 0 = the session own tenant (never borrowed)';++-- Backfill from the config row itself, not from messages. The pin is sticky+-- to the first sandbox, while the newest shared-agent message may belong to a+-- later agent from a different workspace. tenant_sandbox_configs.id is the+-- primary key (a UUID), so the join names the workspace that actually owns+-- the pinned config.+--+-- Rows whose config still lives in the session's own workspace stay 0 and+-- fall back exactly as before, including sessions that mixed own agents with+-- shared ones.+UPDATE sessions s+SET sandbox_config_tenant_id = c.tenant_id+FROM tenant_sandbox_configs c+WHERE c.id = s.sandbox_config_id+ AND c.tenant_id IS DISTINCT FROM s.tenant_id+ AND COALESCE(s.sandbox_config_id, '') NOT IN ('', '-')+ AND c.deleted_at IS NULL;