Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix: preserve shared sandboxes across skill updates (#4729)

lyingbug46f1331a3380
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts b/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts
index 62d0ce4aa..57d616632 100644
--- a/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts
+++ b/frontend/src/components/SandboxConfigEditorDrawer.allocation.test.ts
@@ -1,6 +1,9 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
+import { parse } from '@vue/compiler-sfc'
+import { createSSRApp } from 'vue'
+import { renderToString } from 'vue/server-renderer'
const source = readFileSync(new URL('./SandboxConfigEditorDrawer.vue', import.meta.url), 'utf8')
@@ -17,6 +20,27 @@ test('payload always sends allocation_mode so switching back to session is expli
assert.match(source, /allocation_mode:\s*allocationMode\.value/)
})
+test('skill rollout controls render only for per-session allocation', async () => {
+ const { descriptor } = parse(source)
+ const section = descriptor.template!.content.match(
+ /<section[^>]*>\s*<h4[^>]*>\{\{ \$t\('settings\.sandbox\.skillRollout'\)[\s\S]*?<\/section>/,
+ )?.[0]
+ assert.ok(section, 'the editor must still offer rollout controls for per-session sandboxes')
+ for (const allocationMode of ['session', 'user', 'session']) {
+ const app = createSSRApp({
+ template: section,
+ data: () => ({ currentStepKey: 'runtime', allocationMode, skillRollout: 'next_turn' }),
+ })
+ app.config.globalProperties.$t = (key: string) => key
+ app.component('t-radio-group', { template: '<div><slot /></div>' })
+ app.component('t-radio', { template: '<label><slot /></label>' })
+ const html = await renderToString(app)
+ for (const choice of ['skillRolloutNextTurn', 'skillRolloutNewSession']) {
+ assert.equal(html.includes(choice), allocationMode === 'session')
+ }
+ }
+})
+
test('choosing shared allocation scrolls the retention field into view', () => {
assert.match(source, /ref="userAllocationPanelRef"/)
assert.match(source, /scrollIntoView\(\{ behavior: 'smooth', block: 'end', inline: 'nearest' \}\)/)
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue
index 2a0a8f51b..01fe4b2d4 100644
--- a/frontend/src/components/SandboxConfigEditorDrawer.vue
+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue
@@ -720,7 +720,7 @@
<div v-else class="env-empty">{{ $t('settings.sandbox.noEnvVars') }}</div>
</section>
- <section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">
+ <section v-if="currentStepKey === 'runtime' && allocationMode === 'session'" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillRollout') }}</h4>
<p class="section-help section-help--under-title">{{ $t('settings.sandbox.skillRolloutHint') }}</p>
<t-radio-group v-model="skillRollout" class="skill-rollout-group">
diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue
index b12af60d0..7b86e83e5 100644
--- a/frontend/src/components/SandboxSkillsPanel.vue
+++ b/frontend/src/components/SandboxSkillsPanel.vue
@@ -754,18 +754,21 @@ function normalizeSkillRollout(value?: string): 'next_turn' | 'new_session' {
}
const skillRollout = computed(() => normalizeSkillRollout(props.record?.config?.skill_rollout))
+const sharedSandbox = computed(() => props.record?.config?.allocation_mode === 'user')
-const uploadHint = computed(() =>
- skillRollout.value === 'new_session'
+const uploadHint = computed(() => {
+ if (sharedSandbox.value) return t('settings.sandbox.skillUploadHintShared')
+ return skillRollout.value === 'new_session'
? t('settings.sandbox.skillUploadHintNewSession')
- : t('settings.sandbox.skillUploadHint'),
-)
+ : t('settings.sandbox.skillUploadHint')
+})
const installBusy = computed(() => uploading.value || installingFromSource.value)
-const deleteHint = computed(() =>
- skillRollout.value === 'new_session'
+const deleteHint = computed(() => {
+ if (sharedSandbox.value) return t('settings.sandbox.skillDeleteHintShared')
+ return skillRollout.value === 'new_session'
? t('settings.sandbox.skillDeleteHintNewSession')
- : t('settings.sandbox.skillDeleteHint'),
-)
+ : t('settings.sandbox.skillDeleteHint')
+})
const STATUS_I18N: Record<string, string> = {
installing: 'settings.sandbox.skillStatusInstalling',
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index a84b17fd0..4c265277e 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -2035,6 +2035,7 @@ export default {
skillUploadDrag: 'or drop a file here',
skillUploadHint: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillUploadHintNewSession: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
+ skillUploadHintShared: 'Installing builds a new image and may take several minutes. Existing shared sandboxes stay unchanged; only newly created sandboxes use the new image.',
skillSourceSection: 'Install from a source',
skillSourceSectionHint: 'Paste a ClawHub, GitHub or SkillHub link, or {\'@\'}owner/slug. The bundle cannot exceed {size} MB.',
skillUploadSection: 'Upload a local bundle',
@@ -2057,6 +2058,7 @@ export default {
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: 'Delete removes the skill directory from the image and takes a new snapshot. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillDeleteHintNewSession: 'Delete removes the skill directory from the image and takes a new snapshot. Already-open sessions keep their current sandbox until they end; only newly started sessions lose this skill.',
+ skillDeleteHintShared: 'Deleting removes the skill from the image and builds a new image. Files in existing shared sandboxes stay unchanged; only newly created sandboxes use the new image.',
skillRemoveInProgress: 'Uninstalling',
skillRemoveWaiting: 'Uninstall from the image has started. Waiting for progress…',
skillRemoveDone: 'Uninstalled “{name}” from this sandbox. It remains in the catalog, so you can install it again later.',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index cbd323882..9486a41ca 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -2035,6 +2035,7 @@ export default {
skillUploadDrag: 'またはここにファイルをドロップ',
skillUploadHint: 'インストールすると、現在のイメージにスキルが書き込まれ、新しいスナップショットが作成されます。数分かかる場合があります。現在のやり取りは中断されません。開いているセッションは次のやり取りでサンドボックスを再構築するため、セッションのワークスペースの一時ファイルは消去されます。',
skillUploadHintNewSession: 'インストールすると、現在のイメージにスキルが書き込まれ、新しいスナップショットが作成されます。数分かかる場合があります。すでに開いているセッションは終了するまで現在のサンドボックスを使い続け、新しく開始したセッションのみがこのインストールを反映します。',
+ skillUploadHintShared: 'インストールで新しいイメージを作成します。数分かかる場合があります。既存の共有サンドボックスは変更されず、新しいイメージは今後作成するサンドボックスにのみ適用されます。',
skillSourceSection: 'ソースからインストール',
skillSourceSectionHint: 'ClawHub、GitHub、SkillHubのリンク、または{\'@\'}owner/slugを貼り付けてください。バンドルのサイズは{size} MB以下にしてください。',
skillUploadSection: 'ローカルのバンドルをアップロード',
@@ -2057,6 +2058,7 @@ export default {
skillDisableHint: '無効化すると、スキルはエージェントから見えなくなりますが、ファイルはイメージ内に残ります。変更はセッションの次回実行時に反映されます。',
skillDeleteHint: '削除すると、イメージからスキルのディレクトリが取り除かれ、新しいスナップショットが作成されます。現在のやり取りは中断されません。開いているセッションは次のやり取りでサンドボックスを再構築するため、セッションのワークスペースの一時ファイルは消去されます。',
skillDeleteHintNewSession: '削除すると、イメージからスキルのディレクトリが取り除かれ、新しいスナップショットが作成されます。すでに開いているセッションは終了するまで現在のサンドボックスを使い続け、新しく開始したセッションのみでこのスキルが使えなくなります。',
+ skillDeleteHintShared: '削除するとイメージからスキルを取り除き、新しいイメージを作成します。既存の共有サンドボックス内のファイルは変更されず、新しいイメージは今後作成するサンドボックスにのみ適用されます。',
skillRemoveInProgress: 'アンインストール中',
skillRemoveWaiting: 'イメージからのアンインストールを開始しました。進捗を待っています…',
skillRemoveDone: 'このサンドボックスから「{name}」をアンインストールしました。カタログには残っているため、後で再インストールできます。',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index b1c37c0e0..a0b1f6e90 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -7017,6 +7017,7 @@ export default {
skillUploadDrag: '또는 여기로 드래그',
skillUploadHint: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillUploadHintNewSession: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
+ skillUploadHintShared: '설치하면 새 이미지를 만들며 몇 분이 걸릴 수 있습니다. 기존 공유 샌드박스는 변경되지 않고, 이후 새로 만드는 샌드박스에만 새 이미지가 적용됩니다.',
skillSourceSection: '소스에서 설치',
skillSourceSectionHint: 'ClawHub, GitHub 또는 SkillHub 링크, 혹은 {\'@\'}owner/slug를 붙여넣으세요. 압축 파일은 {size} MB를 넘을 수 없습니다.',
skillUploadSection: '로컬 번들 업로드',
@@ -7039,6 +7040,7 @@ export default {
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: '삭제하면 이미지에서 스킬 디렉터리를 제거하고 새 스냅샷을 만듭니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillDeleteHintNewSession: '삭제하면 이미지에서 스킬 디렉터리를 제거하고 새 스냅샷을 만듭니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이 스킬은 새로 시작한 세션에서만 빠집니다.',
+ skillDeleteHintShared: '삭제하면 이미지에서 스킬을 제거하고 새 이미지를 만듭니다. 기존 공유 샌드박스의 파일은 변경되지 않고, 이후 새로 만드는 샌드박스에만 새 이미지가 적용됩니다.',
skillRemoveInProgress: '제거 중',
skillRemoveWaiting: '이미지에서 제거를 시작했습니다. 진행 상황을 기다리는 중…',
skillRemoveDone: '샌드박스에서 「{name}」을(를) 제거했습니다. 스킬은 카탈로그에 남아 있으니 나중에 다시 설치할 수 있습니다.',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index a0522c3e6..eb250e54b 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -7017,6 +7017,7 @@ export default {
skillUploadDrag: 'или перетащите файл сюда',
skillUploadHint: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillUploadHintNewSession: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
+ skillUploadHintShared: 'Установка создаёт новый образ и может занять несколько минут. Существующие общие песочницы не меняются; новый образ используется только при создании новых песочниц.',
skillSourceSection: 'Установить из источника',
skillSourceSectionHint: 'Вставьте ссылку ClawHub, GitHub или SkillHub, либо {\'@\'}owner/slug. Архив не может превышать {size} МБ.',
skillUploadSection: 'Загрузить локальный пакет',
@@ -7039,6 +7040,7 @@ export default {
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: 'Удаление убирает каталог навыка из образа и создаёт новый снимок. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillDeleteHintNewSession: 'Удаление убирает каталог навыка из образа и создаёт новый снимок. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык исчезнет только у новых сессий.',
+ skillDeleteHintShared: 'Удаление убирает навык из образа и создаёт новый образ. Файлы существующих общих песочниц не меняются; новый образ используется только при создании новых песочниц.',
skillRemoveInProgress: 'Удаление',
skillRemoveWaiting: 'Удаление из образа началось. Ожидание хода выполнения…',
skillRemoveDone: '«{name}» удалён из этой песочницы. Навык остаётся в каталоге, его можно установить снова.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index e24ad26e9..617d30f2a 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -7018,6 +7018,7 @@ export default {
skillUploadDrag: '或将文件拖到此处',
skillUploadHint: '安装会在当前镜像上生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
skillUploadHintNewSession: '安装会在当前镜像上生成新快照,可能需要数分钟。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
+ skillUploadHintShared: '安装会生成新镜像,可能需要数分钟。已有共用沙箱保持不变,新镜像只用于之后新建的沙箱。',
skillSourceSection: '从来源安装',
skillSourceSectionHint: '粘贴 ClawHub、GitHub 或 SkillHub 链接,或 {\'@\'}owner/slug。压缩包不超过 {size} MB。',
skillUploadSection: '上传本地压缩包',
@@ -7040,6 +7041,7 @@ export default {
skillDisableHint: '禁用后该技能对智能体不可见,文件仍保留在镜像中。变更将在会话下一次执行时生效。',
skillDeleteHint: '删除会从镜像中移除该技能目录并生成新快照。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
skillDeleteHintNewSession: '删除会从镜像中移除该技能目录并生成新快照。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会去掉该技能。',
+ skillDeleteHintShared: '删除会从镜像中移除技能并生成新镜像。已有共用沙箱中的文件保持不变,新镜像只用于之后新建的沙箱。',
skillRemoveInProgress: '正在卸载',
skillRemoveWaiting: '已开始从镜像卸载,正在等待进度…',
skillRemoveDone: '已从沙箱卸载「{name}」。技能仍在目录里,可以稍后再装回去。',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 4bf6cd5dc..0838485ef 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -7018,6 +7018,7 @@ export default {
skillUploadDrag: '或將檔案拖到此處',
skillUploadHint: '安裝會在當前映像上生成新快照,可能需要數分鐘。當前這一輪對話不會中斷;下一輪提問時才會按新映像重建沙箱,會話工作區草稿會在那時清空。',
skillUploadHintNewSession: '安裝會在當前映像上生成新快照,可能需要數分鐘。已打開的會話繼續使用原沙箱,直到該會話結束;只有新打開的會話才會帶上這次安裝的技能。',
+ skillUploadHintShared: '安裝會產生新映像,可能需要數分鐘。已有共用沙箱保持不變,新映像只用於之後新建的沙箱。',
skillSourceSection: '從來源安裝',
skillSourceSectionHint: '貼上 ClawHub、GitHub 或 SkillHub 連結,或 {\'@\'}owner/slug。壓縮包不超過 {size} MB。',
skillUploadSection: '上傳本地壓縮包',
@@ -7040,6 +7041,7 @@ export default {
skillDisableHint: '停用後該技能對智慧代理不可見,檔案仍保留在映像中。變更將在會話下一次執行時生效。',
skillDeleteHint: '刪除會從映像中移除該技能目錄並生成新快照。當前這一輪對話不會中斷;下一輪提問時才會按新映像重建沙箱,會話工作區草稿會在那時清空。',
skillDeleteHintNewSession: '刪除會從映像中移除該技能目錄並生成新快照。已打開的會話繼續使用原沙箱,直到該會話結束;只有新打開的會話才會去掉該技能。',
+ skillDeleteHintShared: '刪除會從映像中移除技能並產生新映像。已有共用沙箱中的檔案保持不變,新映像只用於之後新建的沙箱。',
skillRemoveInProgress: '正在解除安裝',
skillRemoveWaiting: '已開始從映像解除安裝,正在等待進度…',
skillRemoveDone: '已從沙箱解除安裝「{name}」。技能仍在目錄裡,可以稍後再裝回去。',
diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go
index a261f519c..827db2daa 100644
--- a/internal/application/service/tenant_skill_install.go
+++ b/internal/application/service/tenant_skill_install.go
@@ -2539,8 +2539,8 @@ func (s *TenantSkillService) markConfigSandboxesStale(
configID, err)
} else if entity != nil && !entity.Config.RebuildsExistingOnSkillChange() {
logger.Infof(markCtx,
- "[skill] config %s skill_rollout=%s; leaving live sandboxes on the previous image",
- configID, types.SkillRolloutNewSession)
+ "[skill] config %s keeps existing sandboxes on the previous image after skill changes",
+ configID)
return
}
}
diff --git a/internal/application/service/tenant_skill_stale_sandbox_test.go b/internal/application/service/tenant_skill_stale_sandbox_test.go
index 7d09dff33..e8e86675e 100644
--- a/internal/application/service/tenant_skill_stale_sandbox_test.go
+++ b/internal/application/service/tenant_skill_stale_sandbox_test.go
@@ -128,3 +128,30 @@ func TestRunRemoveSkipsStaleMarkWhenRolloutIsNewSession(t *testing.T) {
require.Empty(t, fx.staleMarks)
require.NotEmpty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID)
}
+
+func TestSharedSandboxSkillChangesKeepExistingMachines(t *testing.T) {
+ for _, operation := range []string{"install", "remove", "remove-last"} {
+ t.Run(operation, func(t *testing.T) {
+ fx := newInstallFixture(t)
+ fx.configRepo.entity.Config.AllocationMode = types.SandboxAllocationUser
+ // Existing rows may still contain the old default, even though the UI hides it.
+ fx.configRepo.entity.Config.SkillRollout = types.SkillRolloutNextTurn
+ if operation == "install" {
+ require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
+ } else {
+ fx.seedInstalledSkill("sk-1", "snap-old", 3)
+ if operation == "remove" {
+ fx.seedInstalledSkill("sk-2", "snap-old", 3)
+ }
+ require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
+ }
+ require.Empty(t, fx.staleMarks, "skill changes must not schedule a shared machine for replacement")
+ if operation == "remove-last" {
+ require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID)
+ } else {
+ require.Equal(t, "snap-1", fx.configRepo.saved.Config.SkillImage.SnapshotID,
+ "future machines still use the updated image")
+ }
+ })
+ }
+}
diff --git a/internal/sandbox/activity_registry_redis_test.go b/internal/sandbox/activity_registry_redis_test.go
index e89bce7f4..0101a37db 100644
--- a/internal/sandbox/activity_registry_redis_test.go
+++ b/internal/sandbox/activity_registry_redis_test.go
@@ -1,7 +1,6 @@
package sandbox
import (
- "context"
"testing"
"time"
@@ -71,7 +70,7 @@ func useActivityTestSandbox(t *testing.T, mgr *SessionBoundManager, sessionID st
return id
}
-func TestRedisActivityProtectsSharedMachineFromSiblingRebuild(t *testing.T) {
+func TestSharedMachineKeepsSandboxAfterBackgroundActivityEnds(t *testing.T) {
for _, release := range []string{"remove", "expire"} {
t.Run(release, func(t *testing.T) {
h1, h2, registry, mini := newSharedActivityManagers(t)
@@ -98,49 +97,13 @@ func TestRedisActivityProtectsSharedMachineFromSiblingRebuild(t *testing.T) {
mini.SetTime(now.Add(time.Minute))
mini.FastForward(time.Minute)
}
- require.NotEqual(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB))
- require.Equal(t, []string{first}, h1.client.deleteIDs)
+ require.Equal(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB),
+ "ending background work must not trigger a deferred rebuild")
+ require.Empty(t, h1.client.deleteIDs)
})
}
}
-type activityBeforeCloseRegistry struct {
- admission.Registry
- beforeClose func()
-}
-
-func (r *activityBeforeCloseRegistry) Close(
- ctx context.Context, scope admission.Scope, ttl time.Duration,
-) (admission.Barrier, error) {
- if r.beforeClose != nil {
- f := r.beforeClose
- r.beforeClose = nil
- f()
- }
- return r.Registry.Close(ctx, scope, ttl)
-}
-
-func TestSharedRebuildRechecksActivityAfterClosingAdmission(t *testing.T) {
- h1, h2, registry, _ := newSharedActivityManagers(t)
- ctx := ownerCtx()
- first := useActivityTestSandbox(t, h1.mgr, userSessionA)
- _, err := h1.mgr.InvalidateConfigSandboxesForMachines(ctx, "cfg-1",
- []allocation.UserMachine{userAssignmentFor(userSessionA).Machine})
- require.NoError(t, err)
- ref := interfaces.SessionRef{TenantID: 42, SessionID: userSessionA}
- raced := false
- h2.mgr.lifecycle.admission = &activityBeforeCloseRegistry{
- Registry: h2.mgr.admission,
- beforeClose: func() {
- raced = true
- require.NoError(t, registry.Add(ctx, ref, interfaces.BackgroundActivity{ID: "sj_1"}, time.Minute, 0))
- },
- }
- require.Equal(t, first, useActivityTestSandbox(t, h2.mgr, userSessionB))
- require.True(t, raced, "register between the optimistic check and the machine barrier")
- require.Empty(t, h1.client.deleteIDs)
-}
-
func TestRedisActivityCannotRegisterThroughClosedAdmission(t *testing.T) {
for _, scopeKind := range []string{"machine", "session", "rewind"} {
t.Run(scopeKind, func(t *testing.T) {
diff --git a/internal/sandbox/session_lifecycle.go b/internal/sandbox/session_lifecycle.go
index 53ea83f16..cb600657e 100644
--- a/internal/sandbox/session_lifecycle.go
+++ b/internal/sandbox/session_lifecycle.go
@@ -238,7 +238,9 @@ func (l *remoteSessionLifecycle) resolveLocked(
}
// A stale binding is one whose sandbox boots an image the config has since
- // replaced. Rebuild waits for a turn boundary: the first resolve of a new
+ // replaced. Shared user machines keep their image until explicitly released,
+ // including bindings marked stale before this policy was introduced.
+ // Per-session rebuilds wait for a turn boundary: the first resolve of a new
// chat turn may destroy and recreate, later resolves of that same turn
// keep the sandbox so /workspace scratch and in-flight execs survive an
// install that landed mid-turn. A resolve with no turn lease (no AgentQA
@@ -247,14 +249,11 @@ func (l *remoteSessionLifecycle) resolveLocked(
// Destroying before rebuilding is not optional: the recovery pass below
// adopts any live sandbox carrying this session's metadata, so a surviving
// one would simply be picked up again.
- if binding != nil && binding.StaleAt != nil {
- rebuilt, err := l.rebuildStale(ctx, key, *binding)
- if err != nil {
- return nil, err
- }
- if rebuilt {
- binding = nil
+ if binding != nil && binding.StaleAt != nil && l.shouldRebuildStaleBinding(ctx, key) {
+ if err := l.destroyBindingLocked(ctx, key, *binding); err != nil {
+ return nil, fmt.Errorf("release stale sandbox binding: %w", err)
}
+ binding = nil
}
// First resolve of a turn spends rebuildOnce even when nothing was stale,
// so a later install in the same turn cannot tear the sandbox down.
@@ -287,67 +286,11 @@ func (l *remoteSessionLifecycle) resolveLocked(
return l.createAndBind(ctx, machine)
}
-// rebuildStale replaces a sandbox booted from a superseded image. A
-// per-session machine rebuilds at its turn boundary. A shared machine also
-// needs every operation except this request's own to be gone, and holds the
-// machine barrier while it destroys so none can start in between; a closer
-// already at work wins. Losing the barrier stops before any further step.
-func (l *remoteSessionLifecycle) rebuildStale(
- ctx context.Context, key SessionSandboxKey, binding SessionSandboxBinding,
-) (bool, error) {
- if !l.shouldRebuildStaleBinding(ctx, key) {
- return false, nil
- }
- if !key.IsUserScoped() {
- if err := l.destroyBindingLocked(ctx, key, binding); err != nil {
- return false, fmt.Errorf("release stale sandbox binding: %w", err)
- }
- return true, nil
- }
- scope := admission.MachineScope(l.digest(key))
- barrier, err := l.admission.Close(ctx, scope, redisLifecycleLockLease)
- if err != nil {
- if !errors.Is(err, admission.ErrClosed) {
- log.Printf("[sandbox] close %s for rebuild failed (%v); keeping the current sandbox", key, err)
- }
- return false, nil
- }
- defer barrier.Release()
- // C3: a lost barrier also cancels the provider call in flight.
- guarded, stop := admission.Bind(ctx, barrier)
- defer stop()
- others, err := l.admission.ActiveExcept(guarded, scope, admissionExemptFrom(ctx)...)
- if err != nil || others > 0 {
- return false, nil
- }
- // A sibling may have registered background work after the first check
- // and ended its turn before we closed admission. Registration is now
- // blocked, so recheck the machine's leases before destroying it.
- if l.hasLiveMachineActivity(guarded, key) {
- return false, nil
- }
- if err := barrier.Check(); err != nil {
- return false, err
- }
- if err := l.destroyBindingLocked(guarded, key.Machine(), binding); err != nil {
- if cause := barrier.Check(); cause != nil {
- return false, cause
- }
- return false, fmt.Errorf("release stale sandbox binding: %w", err)
- }
- if err := barrier.Check(); err != nil {
- // The old machine is gone but admission may already be open again:
- // do not create a replacement under a lost barrier.
- return false, err
- }
- return true, nil
-}
-
// withAdmissionExempt records the admission members that belong to the
-// current request, so a rebuild it triggers does not wait for itself. The key
-// is a types.ContextKey that survives logger.CloneContext: the async QA run
-// (internal/handler/session/qa.go setupSSEStream) is built through it, and a
-// dropped exemption would make every turn block its own rebuild forever.
+// current request, so exclusive workspace operations do not wait for themselves.
+// The key is a types.ContextKey that survives logger.CloneContext: the async QA
+// run (internal/handler/session/qa.go setupSSEStream) is built through it, and a
+// dropped exemption would make a turn block its own exclusive operations.
func withAdmissionExempt(ctx context.Context, members ...string) context.Context {
prev := admissionExemptFrom(ctx)
all := make([]string, 0, len(prev)+len(members))
@@ -1144,13 +1087,17 @@ func (l *remoteSessionLifecycle) metadata(key SessionSandboxKey) map[string]stri
}
// shouldRebuildStaleBinding reports whether this resolve may tear down a
-// stale sandbox. No turn, or the first resolve of a new turn, rebuilds. A
+// stale per-session sandbox. Shared user machines never rebuild on image changes.
+// No turn, or the first resolve of a new turn, rebuilds a per-session sandbox. A
// turn that has already used the sandbox keeps it. A lease we cannot read is
// treated as an in-flight turn so a Redis blip cannot destroy /workspace.
func (l *remoteSessionLifecycle) shouldRebuildStaleBinding(
ctx context.Context,
key SessionSandboxKey,
) bool {
+ if key.IsUserScoped() {
+ return false
+ }
leaser, ok := l.bindings.(sessionTurnLeaseStore)
active, rebuildOnce := false, false
if ok && key.SessionID != "" {
@@ -1161,36 +1108,7 @@ func (l *remoteSessionLifecycle) shouldRebuildStaleBinding(
return false
}
}
- if active && !rebuildOnce {
- return false
- }
- if !key.IsUserScoped() {
- return true
- }
- if l.hasLiveMachineActivity(ctx, key) {
- return false
- }
- others, err := l.admission.ActiveExcept(ctx, admission.MachineScope(l.digest(key)), admissionExemptFrom(ctx)...)
- if err != nil {
- log.Printf("[sandbox] admission of %s unavailable (%v); keeping the current sandbox", key, err)
- return false
- }
- return others == 0
-}
-
-func (l *remoteSessionLifecycle) hasLiveMachineActivity(ctx context.Context, key SessionSandboxKey) bool {
- store, ok := l.bindings.(interface {
- hasBackgroundActivity(context.Context, SessionSandboxKey) (bool, error)
- })
- if !ok {
- return false
- }
- active, err := store.hasBackgroundActivity(ctx, key)
- if err != nil {
- log.Printf("[sandbox] background activity of %s unavailable (%v); keeping the current sandbox", key, err)
- return true
- }
- return active
+ return !active || rebuildOnce
}
func (l *remoteSessionLifecycle) consumeTurnRebuild(
diff --git a/internal/sandbox/session_lifecycle_test.go b/internal/sandbox/session_lifecycle_test.go
index 8042c9583..80643a456 100644
--- a/internal/sandbox/session_lifecycle_test.go
+++ b/internal/sandbox/session_lifecycle_test.go
@@ -1537,64 +1537,45 @@ func TestUserMachineRecoversFromLostBindingByDigest(t *testing.T) {
require.Equal(t, first.ID(), again.ID(), "metadata recovery must adopt the same machine, not create a second")
}
-func TestStaleUserMachineWaitsForOtherSessions(t *testing.T) {
+func TestStaleUserMachineKeepsSandboxAcrossSessionsAndTurns(t *testing.T) {
f := newUserLifecycleFixture(t)
ctx := context.Background()
first, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
require.NoError(t, err)
- // InvalidateByConfig's scan does not see user keys; mark the machine the
- // way the manager does (T10).
- n, err := markBindingKeysStale(ctx, f.bindings, []SessionSandboxKey{f.sessionKey(userSessionA).Machine()}, "cfg-1")
+ machine := f.sessionKey(userSessionA).Machine()
+ // Simulate a stale marker written before shared machines stopped rebuilding.
+ n, err := markBindingKeysStale(ctx, f.bindings, []SessionSandboxKey{machine}, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
+ f.lifecycle.createRequest.TemplateID = "template-new"
- machine := admission.MachineScope(f.machine.Digest("weknora"))
- self := admission.SessionMember(userSessionA, "shell", "self")
- selfLease, err := f.admission.Hold(ctx, machine, self, time.Minute)
- require.NoError(t, err)
- defer selfLease.Release()
- ownTurn := admission.SessionMember(userSessionA, "turn", "own")
- ownTurnLease, err := f.admission.Hold(ctx, machine, ownTurn, time.Minute)
- require.NoError(t, err)
- defer ownTurnLease.Release()
- ctxA := withAdmissionExempt(ctx, self, ownTurn)
-
- other, err := f.admission.Hold(ctx, machine, admission.SessionMember(userSessionB, "shell", "t"), time.Minute)
- require.NoError(t, err)
- kept, err := f.lifecycle.Resolve(ctxA, f.sessionKey(userSessionA))
- require.NoError(t, err)
- require.Equal(t, first.ID(), kept.ID(), "B is running a command; A's turn must not rebuild under it")
- other.Release()
-
- ownPTY, err := f.admission.Hold(ctx, machine, admission.SessionMember(userSessionA, "pty", "p"), time.Minute)
- require.NoError(t, err)
- kept, err = f.lifecycle.Resolve(ctxA, f.sessionKey(userSessionA))
- require.NoError(t, err)
- require.Equal(t, first.ID(), kept.ID(), "A's own terminal is not this request; it blocks the rebuild too")
- ownPTY.Release()
-
- rebuilt, err := f.lifecycle.Resolve(ctxA, f.sessionKey(userSessionA))
+ for _, sessionID := range []string{userSessionA, userSessionB} {
+ key := f.sessionKey(sessionID)
+ for turn := 0; turn < 2; turn++ {
+ require.NoError(t, f.bindings.BeginTurn(ctx, key))
+ kept, err := f.lifecycle.Resolve(ctx, key)
+ require.NoError(t, err)
+ require.Equal(t, first.ID(), kept.ID(), "even an idle machine stays across new turns and sessions")
+ require.NoError(t, f.bindings.EndTurn(ctx, key))
+ }
+ }
+ kept, err := f.lifecycle.Resolve(ctx, machine)
require.NoError(t, err)
- require.NotEqual(t, first.ID(), rebuilt.ID())
- creates, _, _, _, _ := f.client.counts()
- require.Equal(t, 2, creates)
-}
+ require.Equal(t, first.ID(), kept.ID(), "machine-level access must also preserve the sandbox")
+ creates, _, _, _, deletes := f.client.counts()
+ require.Equal(t, 1, creates)
+ require.Zero(t, deletes)
-func TestStaleRebuildStopsWhenTheBarrierIsLost(t *testing.T) {
- f := newUserLifecycleFixture(t)
- ctx := context.Background()
- first, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
+ // Explicit release is still available and the replacement uses the new image.
+ released, err := f.lifecycle.reclaimUserMachine(ctx, machine, func(context.Context) (bool, error) {
+ return true, nil
+ })
require.NoError(t, err)
- _, err = markBindingKeysStale(ctx, f.bindings, []SessionSandboxKey{f.sessionKey(userSessionA).Machine()}, "cfg-1")
+ require.True(t, released)
+ replacement, err := f.lifecycle.Resolve(ctx, f.sessionKey(userSessionB))
require.NoError(t, err)
-
- f.client.deleteHook = func(context.Context, string) error {
- f.admission.LoseBarrier(admission.MachineScope(f.machine.Digest("weknora")))
- return nil
- }
- _, err = f.lifecycle.Resolve(ctx, f.sessionKey(userSessionA))
- require.ErrorIs(t, err, admission.ErrLeaseLost, "after losing the barrier no further destructive step runs")
- _ = first
+ require.NotEqual(t, first.ID(), replacement.ID())
+ require.Equal(t, "template-new", f.client.lastCreateRequest.TemplateID)
}
func TestUserKeyWithoutAdmissionIsRefused(t *testing.T) {
diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go
index 9a6367f70..f687272ee 100644
--- a/internal/sandbox/session_manager_test.go
+++ b/internal/sandbox/session_manager_test.go
@@ -1409,7 +1409,7 @@ func TestSessionExclusiveWaitsAndOwnerKeepsWorking(t *testing.T) {
require.ErrorContains(t, err, "busy", "everyone else waits for the exclusive window")
}
-func TestExclusiveWindowIsAMachineMemberAndBlocksRebuild(t *testing.T) {
+func TestExclusiveWindowIsAMachineMemberAndKeepsSharedSandbox(t *testing.T) {
h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
ctx := ownerCtx()
_, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
@@ -1423,7 +1423,7 @@ func TestExclusiveWindowIsAMachineMemberAndBlocksRebuild(t *testing.T) {
scope := admission.MachineScope(machineDigest(t, userSessionA))
n, err := h.admission.ActiveExcept(ctx, scope)
require.NoError(t, err)
- require.Equal(t, 1, n, "rewind and directory delete must be visible to machine rebuild and reclaim")
+ require.Equal(t, 1, n, "rewind and directory delete must be visible to machine reclaim")
m, _ := userAssignmentFor(userSessionA).UserMachine()
_, err = h.mgr.InvalidateConfigSandboxesForMachines(ctx, "cfg-1", []allocation.UserMachine{m})
@@ -1431,7 +1431,7 @@ func TestExclusiveWindowIsAMachineMemberAndBlocksRebuild(t *testing.T) {
_, err = h.mgr.ExecShellCommand(ctx, userSessionB, "true", "", time.Second, nil)
require.NoError(t, err)
kept, _ := h.mgr.BoundSandboxID(ctx, userSessionB)
- require.Equal(t, first, kept, "a stale rebuild must not delete the machine during the exclusive window")
+ require.Equal(t, first, kept, "image changes must preserve the shared machine during the exclusive window")
_, _, _, _, deletesAfter := h.client.counts()
require.Equal(t, deletesBefore, deletesAfter)
@@ -1504,7 +1504,7 @@ func TestUploadedScriptsStayInTheSessionDirectory(t *testing.T) {
h.client.writeFiles[len(h.client.writeFiles)-1].path)
}
-func TestMultiReplicaAdmissionBlocksRebuildAcrossManagers(t *testing.T) {
+func TestMultiReplicaSharedMachineSurvivesDesktopDisconnect(t *testing.T) {
r1, r2, _ := multiReplicaPair(t, "",
userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
ctx := ownerCtx()
@@ -1522,13 +1522,13 @@ func TestMultiReplicaAdmissionBlocksRebuildAcrossManagers(t *testing.T) {
_, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.NoError(t, err)
kept, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
- require.Equal(t, first, kept, "a desktop on another replica blocks the rebuild")
+ require.Equal(t, first, kept, "a skill image change keeps the machine while another replica uses its desktop")
release()
_, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.NoError(t, err)
- rebuilt, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
- require.NotEqual(t, first, rebuilt)
+ kept, _ = r1.mgr.BoundSandboxID(ctx, userSessionA)
+ require.Equal(t, first, kept, "disconnecting must not trigger a deferred rebuild")
}
func TestDeleteSessionWorkspacesWaitsForTheSessionAndRemovesOnlyIt(t *testing.T) {
@@ -1766,7 +1766,7 @@ func TestMultiReplicaRealRedisFirstAllocationCreatesOneMachine(t *testing.T) {
require.Equal(t, a, b)
}
-func TestMultiReplicaRealRedisLeaseBlocksRebuildAndReclaim(t *testing.T) {
+func TestMultiReplicaRealRedisLeaseBlocksReclaimAndKeepsSharedSandbox(t *testing.T) {
r1, r2, _ := multiReplicaPair(t, integrationEnv(t, "WEKNORA_TEST_REDIS_ADDR"),
userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
ctx := ownerCtx()
@@ -1783,7 +1783,7 @@ func TestMultiReplicaRealRedisLeaseBlocksRebuildAndReclaim(t *testing.T) {
_, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.NoError(t, err)
kept, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
- require.Equal(t, first, kept, "replica 2's terminal blocks replica 1's rebuild")
+ require.Equal(t, first, kept, "image changes must preserve the shared machine across replicas")
ok, err := r1.mgr.ReclaimUserMachine(ctx, m, func(context.Context) (bool, error) { return true, nil })
require.NoError(t, err)
@@ -1792,8 +1792,8 @@ func TestMultiReplicaRealRedisLeaseBlocksRebuildAndReclaim(t *testing.T) {
closePTY()
_, err = r1.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.NoError(t, err)
- rebuilt, _ := r1.mgr.BoundSandboxID(ctx, userSessionA)
- require.NotEqual(t, first, rebuilt)
+ kept, _ = r1.mgr.BoundSandboxID(ctx, userSessionA)
+ require.Equal(t, first, kept, "disconnecting must not trigger a deferred rebuild")
}
func TestMultiReplicaRealRedisLostLeaseStopsTheHolderAndFreesTheMachine(t *testing.T) {
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index f83caf961..4512800e5 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -687,6 +687,7 @@ type TenantSandboxConfig struct {
// SkillRolloutNextTurn rebuild on the next chat turn. SkillRolloutNewSession
// leaves those sandboxes on the previous image; only sessions that start
// afterwards boot the new snapshot.
+ // User allocation always keeps existing shared machines, regardless of this setting.
SkillRollout string `json:"skill_rollout,omitempty"`
// AllocationMode decides how a session that has not yet used a sandbox
@@ -861,13 +862,14 @@ const (
)
// RebuildsExistingOnSkillChange reports whether an install or removal should
-// mark already-bound sandboxes stale. Unknown values fail toward rebuilding
-// so a corrupted row cannot pin every session on a retired image.
+// mark already-bound sandboxes stale. Shared user machines always keep their
+// current image. Unknown rollout values retain the per-session rebuild default.
func (c *TenantSandboxConfig) RebuildsExistingOnSkillChange() bool {
if c == nil {
return true
}
- return strings.TrimSpace(c.SkillRollout) != SkillRolloutNewSession
+ return strings.TrimSpace(c.AllocationMode) != SandboxAllocationUser &&
+ strings.TrimSpace(c.SkillRollout) != SkillRolloutNewSession
}
// SkillImageConfig is the pointer to the snapshot that carries the skills
diff --git a/website-docs/03-features/22-skills-sandbox.md b/website-docs/03-features/22-skills-sandbox.md
index 287acb20f..7eaf26495 100644
--- a/website-docs/03-features/22-skills-sandbox.md
+++ b/website-docs/03-features/22-skills-sandbox.md
@@ -39,7 +39,12 @@
升级或重试失败时,沙箱继续提供上一个就绪版本,智能体仍可使用;新版本安装成功后才替换。
-`skill_rollout` 控制镜像更新:默认 `next_turn` 在已有会话的下一轮重建沙箱;`new_session` 仅让之后创建沙箱的会话使用新镜像。沙箱重建会丢失旧实例临时运行状态,需交付的文件应写入 `/workspace/output` 并由系统收集。
+每会话一台沙箱时,`skill_rollout` 控制镜像更新:默认 `next_turn` 在已有会话的下一轮重建沙箱;`new_session` 仅让之后创建沙箱的会话使用新镜像。共用沙箱模式隐藏此选项,安装或删除技能不会自动重建已有的共用机器,新镜像只用于之后新建的沙箱。沙箱重建会丢失旧实例临时运行状态,需交付的文件应写入 `/workspace/output` 并由系统收集。
+
+<Screenshot
+ src="/screenshots/sandbox-session-skill-rollout.png"
+ alt="每会话一台沙箱时可以选择技能镜像更新策略"
+/>
### 支持的来源
@@ -138,7 +143,7 @@ macOS 桌面版可在「工具箱 → 技能管理」将技能安装到「本机
| 终端 | 连接本会话沙箱的交互式 Shell(xterm)。Cube、E2B 刷新页面后可重新接上仍在运行的终端;Docker 断开即结束 Shell(nohup 启动的后台任务保留),重连会打开新 Shell | Cube、E2B、Docker |
| 桌面 | 通过浏览器操作沙箱内的 XFCE 图形桌面,每个会话同时只允许一个连接 | Cube、E2B 的桌面模板,且配置开启 `desktop_enabled` |
-打开面板不会创建或唤醒沙箱:沙箱正在运行时终端和桌面会直接连上;沙箱已暂停或尚未创建时,需要点「启动终端」「连接桌面」或「创建并启动」,唤醒或新建的沙箱会按空间配置计费。终端或桌面长时间无操作会自动断开,沙箱随后按提供商 TTL 暂停;断开时间由沙箱配置的「终端 / 桌面空闲断开(秒)」控制,默认 900 秒,范围 60 秒到 24 小时。技能更新触发沙箱重建后,原终端和桌面上未保存的内容会丢失。
+打开面板不会创建或唤醒沙箱:沙箱正在运行时终端和桌面会直接连上;沙箱已暂停或尚未创建时,需要点「启动终端」「连接桌面」或「创建并启动」,唤醒或新建的沙箱会按空间配置计费。终端或桌面长时间无操作会自动断开,沙箱随后按提供商 TTL 暂停;断开时间由沙箱配置的「终端 / 桌面空闲断开(秒)」控制,默认 900 秒,范围 60 秒到 24 小时。每会话一台的沙箱若因技能更新而重建,原终端和桌面上未保存的内容会丢失;共用沙箱不会因技能更新而自动重建。
<Screenshot
src="/screenshots/sandbox-panel-terminal.png"
@@ -156,6 +161,13 @@ macOS 桌面版可在「工具箱 → 技能管理」将技能安装到「本机
切换只影响还没有用过沙箱的会话。已经钉住沙箱配置、已经有检查点,或分叉后还没完成首次准备的会话,继续用自己原来的那一台。
+共用机器不会因技能镜像更新自动更换,即使旧配置仍存着 `skill_rollout=next_turn`,或机器已被旧版本标记为待重建。之后新增的会话仍复用这台机器;需要使用新镜像时,由用户或管理员主动释放并重新创建沙箱。释放会删除该机器上的文件和运行状态,应先保存需要保留的数据。此策略不改变提供商 TTL、空置回收或机器确实不存在后的重新创建行为。
+
+<Screenshot
+ src="/screenshots/sandbox-user-skill-rollout.png"
+ alt="共用沙箱模式隐藏技能镜像更新策略,保留空置沙箱保留天数设置"
+/>
+
能进共用机器的只有两类身份:Web 登录账号,以及带外部用户标识的 API 调用。同一把 API Key、但不带外部用户的两个会话各用一台沙箱,分配行的 `machine_digest` 为空,分配日志的原因是 `SHARED_API_KEY`。
共用一台时,设计上的风险(设计文档 §5.2.1)是:
diff --git a/website-docs/04-api/02-api-sandbox-skills.md b/website-docs/04-api/02-api-sandbox-skills.md
index 1a6b839cf..4564231a3 100644
--- a/website-docs/04-api/02-api-sandbox-skills.md
+++ b/website-docs/04-api/02-api-sandbox-skills.md
@@ -40,7 +40,8 @@ ConfigResponse 为 `{id,name,description,sandbox_type,config,created_at,updated_
| `desktop_enabled` | bool | 声明所选模板是 Cube/E2B 桌面模板;已安装技能后不能切换 |
| `allow_private_endpoints` | bool | 允许私网集群地址,不放行 link-local/云元数据 |
| `env_vars` | map[string]string | 该沙箱配置的环境,值加密保存 |
-| `skill_rollout` | string | next_turn(默认)/new_session |
+| `skill_rollout` | string | next_turn(默认)/new_session;`allocation_mode=user` 时不生效,已有共用机器始终保留当前镜像 |
+| `allocation_mode` | string | session(默认,每会话一台)/user(同一用户共用);只影响首次分配,不迁移已有会话 |
| `network` | object | Cube/E2B 网络策略,见下 |
| `cube` / `e2b` / `docker` | object | 与 sandbox_type 对应的连接配置 |
| `volume_mount` | object | 可选卷配置;后端能力决定是否生效,不能仅凭字段存在认定支持 |
diff --git a/website-docs/public/screenshots/sandbox-session-skill-rollout.png b/website-docs/public/screenshots/sandbox-session-skill-rollout.png
new file mode 100644
index 000000000..c14703f0e
Binary files /dev/null and b/website-docs/public/screenshots/sandbox-session-skill-rollout.png differ
diff --git a/website-docs/public/screenshots/sandbox-user-skill-rollout.png b/website-docs/public/screenshots/sandbox-user-skill-rollout.png
new file mode 100644
index 000000000..7a8e7577f
Binary files /dev/null and b/website-docs/public/screenshots/sandbox-user-skill-rollout.png differ