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
feat(sandbox): 沙箱后端改为按空间配置,并补齐 E2B 模板与检测诊断
wizardchen738fe1ec5377
diff --git a/.env.example b/.env.exampleindex 582940154..da5f273ab 100644--- a/.env.example+++ b/.env.example@@ -569,68 +569,9 @@ SYSTEM_AES_KEY=weknora-system-aes-key-32bytes!!# ###################################################################### ========== G1. Agent Skills Sandbox ==========-# 以下 WEKNORA_SANDBOX_* 均为「部署级默认值」。工作区可在「设置 → 沙箱后端」中维护-# 多份具名配置(同一后端类型也可以有多份,例如两个 E2B 账号),智能体在编辑弹窗的-# 「能力扩展 → 沙箱后端」里各自选择其一;未选择的智能体回落到这里的默认值。-# 具名配置是自包含的:不会回退到这里的值,端点/密钥/域名/模板必须在配置里填全。-#-# Sandbox 模式:docker(默认)/ local / cube / e2b / disabled。-# docker - Docker 容器隔离(一次性容器)-# local - 本地进程 + 白名单(一次性执行)-# cube - Tencent CubeSandbox MicroVM(会话级持久,每 Session 独占一个沙箱)-# e2b - E2B 云端 MicroVM(会话级持久;依赖第三方 SDK go-e2b)-# disabled - 关闭本实例全部沙箱能力(含工作区具名配置;部署级总闸)-WEKNORA_SANDBOX_MODE=docker-# 脚本执行超时(秒,默认 60)。-WEKNORA_SANDBOX_TIMEOUT=60-# Sandbox Docker 镜像(默认 wechatopenai/weknora-sandbox:latest)。-# WEKNORA_SANDBOX_DOCKER_IMAGE=wechatopenai/weknora-sandbox:latest--# 是否允许租户沙箱配置使用 loopback / 私网地址(127.0.0.1、RFC1918)。-# 自建 Cube/E2B 必填 true;公网 SaaS _endpoint 保持 false(默认)。-# 无论何种取值,169.254.0.0/16(云 metadata)始终禁止。-# WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS=false--# ---------- 会话级沙箱通用配置(cube / e2b 生效) -----------# 工作区使用具名 Cube/E2B 配置,或部署默认 mode=cube/e2b 时,需要 REDIS_ADDR-# 以在多实例间共享 session→sandbox binding。仅单机 dev 可:-# WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true--# 会话→沙箱绑定的 Redis key 命名空间。不设置时复用 WEKNORA_REDIS_NAMESPACE,-# 再退回到 "weknora"。-# WEKNORA_SANDBOX_REDIS_NAMESPACE=weknora--# ---------- CubeSandbox 专用配置(仅当 WEKNORA_SANDBOX_MODE=cube 时生效) -----------# CubeAPI 端点,用于创建/销毁沙箱。参考 Cube 部署中的 CUBE_API_BIND。-WEKNORA_SANDBOX_CUBE_API_URL=http://127.0.0.1:33000-# CubeProxy 端点,用于通过 Host 头路由到 envd 执行脚本/上传文件。-# 参考 Cube 部署中的 CUBE_PROXY_HTTP_PORT(默认 80)。-WEKNORA_SANDBOX_CUBE_PROXY_URL=http://127.0.0.1:80-# CubeProxy 使用的沙箱路由域名(参考 CUBE_API_SANDBOX_DOMAIN)。-WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN=cube.app-# X-API-Key 认证头;本地部署一般无鉴权,保持为空即可。-# WEKNORA_SANDBOX_CUBE_API_KEY=-# 默认模板 ID(在 CubeMaster 中注册的模板)。-WEKNORA_SANDBOX_CUBE_TEMPLATE=tpl-54becd2c417742e6a190bd3e-# Cube 端沙箱 TTL(秒),到期后 Cube 侧 pause(非销毁)。默认 1800(30 分钟)。-WEKNORA_SANDBOX_CUBE_SANDBOX_TTL=1800-# 单次 HTTP 请求的超时(秒);不影响脚本执行本身的超时。默认 30。-# WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT=30--# ---------- E2B 专用配置(仅当 WEKNORA_SANDBOX_MODE=e2b 时生效) -----------# 说明:E2B 后端依赖第三方 SDK go-e2b。-# E2B API Key(必填),从 https://e2b.dev/dashboard 获取。-# WEKNORA_SANDBOX_E2B_API_KEY=-# E2B 控制面地址,默认 https://api.e2b.app(自建部署可覆盖)。-# WEKNORA_SANDBOX_E2B_API_URL=https://api.e2b.app-# envd 路由域名,默认 e2b.app(自建部署可覆盖)。-# WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=e2b.app-# 模板 ID / 别名(在 E2B 上先构建,见 https://e2b.dev/docs/template)。-# WEKNORA_SANDBOX_E2B_TEMPLATE=base-# E2B 端 idle timeout(秒),默认 300;超过后 E2B 自动paused。-# WEKNORA_SANDBOX_E2B_SANDBOX_TTL=300-# 单次 HTTP 请求的超时(秒),默认 30。-# WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=30+# Sandbox 后端、凭据、模板、超时和私网访问策略全部在「设置 → 沙箱后端」+# 按空间维护;部署环境不再提供 WEKNORA_SANDBOX_* 覆盖项。+# 多实例仍应配置通用 REDIS_ADDR,以共享 session→sandbox binding。# 自定义 Skills 目录(挂载后指定,免重建镜像)。# WEKNORA_SKILLS_DIR=diff --git a/.gitignore b/.gitignoreindex 1423ddab1..88998fb78 100644--- a/.gitignore+++ b/.gitignore@@ -57,3 +57,6 @@ fix-docker.sh# WeChat Mini Program local/private configurationminiprogram/project.private.config.json++# Staging dir for the Docker sandbox self-check probe (removed after each run)+.weknora-sandbox-check-*diff --git a/docker-compose.yml b/docker-compose.ymlindex c605e2962..669ceb43b 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -312,18 +312,6 @@ services:- WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC=${WEKNORA_CHAT_ATTACHMENT_WAIT_TIMEOUT_SEC:-60}- WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY=${WEKNORA_CHAT_ATTACHMENT_OCR_CONCURRENCY:-8}- WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=${WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES:-8}- # Agent Skills Sandbox- - WEKNORA_SANDBOX_MODE=${WEKNORA_SANDBOX_MODE:-docker}- - WEKNORA_SANDBOX_TIMEOUT=${WEKNORA_SANDBOX_TIMEOUT:-60}- - WEKNORA_SANDBOX_DOCKER_IMAGE=${WEKNORA_SANDBOX_DOCKER_IMAGE:-wechatopenai/weknora-sandbox:${WEKNORA_VERSION:-latest}}- - WEKNORA_SANDBOX_REDIS_NAMESPACE=${WEKNORA_SANDBOX_REDIS_NAMESPACE:-}- # E2B (experimental; leave empty unless WEKNORA_SANDBOX_MODE=e2b).- - WEKNORA_SANDBOX_E2B_API_KEY=${WEKNORA_SANDBOX_E2B_API_KEY:-}- - WEKNORA_SANDBOX_E2B_API_URL=${WEKNORA_SANDBOX_E2B_API_URL:-}- - WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN=${WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN:-}- - WEKNORA_SANDBOX_E2B_TEMPLATE=${WEKNORA_SANDBOX_E2B_TEMPLATE:-}- - WEKNORA_SANDBOX_E2B_SANDBOX_TTL=${WEKNORA_SANDBOX_E2B_SANDBOX_TTL:-}- - WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT=${WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT:-}# Agent LLM call timeout- WEKNORA_AGENT_LLM_TIMEOUT=${WEKNORA_AGENT_LLM_TIMEOUT:-}- WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=${WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT:-}diff --git a/docs/agent-skills.md b/docs/agent-skills.mdindex 2ba8baa1e..4348056c7 100644--- a/docs/agent-skills.md+++ b/docs/agent-skills.md@@ -122,43 +122,35 @@ type AgentConfig struct {}```-### Sandbox 配置(环境变量)+### Sandbox 配置入口-下表的环境变量是**部署级默认值**。工作区还可以维护多份具名沙箱后端配置,智能体各自选用其一;未选择的智能体回落到这里的默认值(见「工作区沙箱后端配置」)。--| 环境变量 | 说明 | 默认值 |-|---------|------|--------|-| `WEKNORA_SANDBOX_MODE` | sandbox 模式:`docker` / `local` / `cube` / `e2b` / `disabled` | `disabled` |-| `WEKNORA_SANDBOX_TIMEOUT` | 脚本执行超时(秒) | `60` |-| `WEKNORA_SANDBOX_DOCKER_IMAGE` | 自定义 Docker 镜像(docker 模式) | `wechatopenai/weknora-sandbox:latest` |-| `WEKNORA_SANDBOX_REDIS_NAMESPACE` | 会话→沙箱绑定的 Redis key 命名空间(cube / e2b 生效;未设置时复用 `WEKNORA_REDIS_NAMESPACE`) | `weknora` |-| `WEKNORA_SANDBOX_CUBE_*` | Cube 后端专用配置,见 `.env.example` | — |-| `WEKNORA_SANDBOX_E2B_*` | E2B 后端专用配置,见 `.env.example`(`WEKNORA_SANDBOX_E2B_API_KEY` 必填) | — |+Sandbox 不再读取 `WEKNORA_SANDBOX_*` 环境变量。后端、凭据、模板、执行超时、TTL 和私网访问策略均在「设置 → 沙箱后端」按空间保存;智能体没有选择空间配置时,脚本执行保持禁用。### Sandbox 模式+Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接检查和智能体选择接口管理。CubeSandbox / E2B 的集群搭建和设置页接入流程见 [WeKnora 沙箱集群与标准模板](sandbox-cluster.md)。设置页会通过当前连接拉取模板目录;若没有 WeKnora 标准模板,后端会从标准镜像发起创建,用户无需复制模板 ID。+| 模式 | 状态 | 说明 ||------|------|------|-| `docker` | 稳定 | 使用 Docker 容器隔离(推荐用于本地/单机部署) |-| `local` | 基础 | 本地进程执行(仅基础白名单,无 MicroVM 隔离) |+| `docker` | 稳定 | 每次执行启动短生命周期容器;镜像和环境变量按空间配置,不保留会话绑定 |+| `local` | 开发 | 直接在 WeKnora 服务主机执行;无容器/MicroVM 隔离,不保留会话绑定 || `cube` | 稳定 | Tencent CubeSandbox MicroVM;会话级持久,支持多机(需 Redis) || `e2b` | 稳定 | E2B 云端 MicroVM;会话级持久,支持多机(需 Redis);依赖第三方 SDK go-e2b |-| `disabled` | — | 关闭本实例全部沙箱能力,含工作区具名配置 |### 工作区沙箱后端配置-一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选就使用上表的部署级默认后端,行为与本特性上线前完全一致。+一个工作区可以维护**多份具名**沙箱后端配置(「设置 → 沙箱后端」),智能体在编辑弹窗的「能力扩展 → 沙箱后端」里各自选一份。不选表示禁用脚本执行。同一后端类型可以有多份配置:例如两份 E2B 分别指向不同账号或区域,让不同智能体的技能脚本落在不同配额上。-**具名配置是自包含的,不继承 `.env`。** 部署级 `WEKNORA_SANDBOX_*` 只服务「没有选择任何具名配置」的智能体;具名配置里留空的字段不会回退到那些值,必须自己填全:+**空间配置是唯一运行时来源。** 端点、凭据和运行参数不会从 `.env` 回退:| 后端 | 必填 | 可留空 ||---|---|---|-| Cube | API 端点、Proxy 端点、沙箱域名、模板 ID | API Key(自建部署通常无鉴权) |-| E2B | API Key、模板 ID | API 端点、沙箱域名(go-e2b 自行解析默认值) |+| Cube | API 端点、Proxy 端点、沙箱域名、从集群列表选择的模板 | API Key(自建部署通常无鉴权) |+| E2B | API Key、从账号列表选择的模板 | API 端点、沙箱域名(go-e2b 自行解析默认值) |-留空必填项在保存时就会被拒绝(HTTP 400,报文里列出缺哪些字段),而不是等到第一次执行技能才失败。HTTP 超时与沙箱 TTL 留空走**内置默认值**,同样不看 `.env`。唯一仍沿用部署值的是「执行超时」,因为它属于运维护栏而非后端身份。+留空必填项在保存时就会被拒绝(HTTP 400)。HTTP 超时、沙箱 TTL 和执行超时留空均使用程序内置默认值。这条规则换来的是:库里那一行就是沙箱位置的完整描述。因此身份比较不必再去解析 `.env`,改 `.env` 也不会在无人察觉的情况下把某份配置重新指向别的账号。@@ -180,16 +172,16 @@ type AgentConfig struct {| 值 | 含义 ||---|---|| `NULL` | 当前无活沙箱(删会话 / 销毁后会 Clear) |-| `"-"` | 活沙箱建在**部署默认**(`.env` `WEKNORA_SANDBOX_*`)上 |+| `"-"` | 旧版本部署默认沙箱的历史兼容标记;新会话不再写入 || UUID | 活沙箱建在工作区某份**具名配置**上 |### 会话级 sandbox 部署要点-- **binding store 自动选择**:无需专门的开关,进程根据 `REDIS_ADDR` 是否配置自动决定绑定存储——配置了 `REDIS_ADDR`(Redis 可用)时使用 Redis binding store,否则退回进程内内存 binding store。命名空间用 `WEKNORA_SANDBOX_REDIS_NAMESPACE`,未设置时依次回退到 `WEKNORA_REDIS_NAMESPACE`、`weknora`。+- **binding store 自动选择**:进程根据通用 `REDIS_ADDR` 是否配置自动决定绑定存储;Redis key 命名空间复用 `WEKNORA_REDIS_NAMESPACE`,未设置时为 `weknora`。- **多机部署(生产推荐)**:配置 `REDIS_ADDR`。多副本共享同一 session 的沙箱绑定,通过 Redis SET NX + 可续租分布式锁串行化 create / recover / delete。- **单机部署**:不配置 `REDIS_ADDR`(或 Lite 模式)时使用进程内内存 binding,仅限单实例。进程重启会丢失 session→sandbox 映射,remote 侧沙箱成为孤儿(注意:**TTL 到期只会暂停、不会销毁**,见下)。-- **切换 provider**:不同 provider 的 sandbox ID 不通用。切换 `WEKNORA_SANDBOX_MODE` 后,旧 session 的 binding 会因 provider 不匹配被 CAS 替换成新 provider 的新沙箱;WeKnora 不做跨 provider 删除。+- **切换 provider**:不同 provider 的 sandbox ID 不通用。智能体改选配置只影响之后新建的沙箱,已有沙箱继续按 session pin 回收。- **⚠️ 孤儿沙箱不会被 TTL 自动回收**:会话沙箱创建时使用 `onTimeout=pause` + `autoResume=true`(见 `buildSessionCreateRequest`),因此 **TTL 到期是"暂停"而非"销毁"**——保留状态本就是 pause 的目的。加上 CAS 换绑会把旧 sandboxID 从 binding store 覆盖掉,被替换的沙箱会变成**无人知晓 ID 的 paused 孤儿**,持续占用快照存储与费用。删除会话(`session.go` 的 destroyer)与 lifecycle 的惰性 orphan cleanup 都覆盖不到这种情况。生产环境需依赖按 metadata 列举并与 binding 对账的清理任务来回收(`internal/sandbox/orphan_reaper.go`),且**必须显式包含 `paused` 状态**。对账维度是 `(tenant_id, config_id)` 而非仅 `tenant_id`:同一工作区的两份配置可能指向**同一个 provider 账号**(例如同一个 E2B Key 只差模板),只按 `tenant_id` 过滤会把另一份配置的沙箱一并误删。- **网络策略**:`cube` 与 `e2b` 默认开启公网出口和 public traffic,可在 create 时通过 provider-neutral `RemoteNetworkPolicy`(`AllowInternetAccess` / `AllowPublicTraffic` / `AllowOut` / `DenyOut`)精细化配置;两个 adapter 都实现了同一契约。@@ -698,4 +690,4 @@ go run ./cmd/skills-demo/main.go- `skill name too long`: 名称超过 50 字符- `skill name contains invalid characters`: 包含非法字符- `skill name is reserved`: 使用了保留词-- `skill description too long`: 描述超过 500 字符\ No newline at end of file+- `skill description too long`: 描述超过 500 字符diff --git a/docs/sandbox-cluster.md b/docs/sandbox-cluster.mdnew file mode 100644index 000000000..519312207--- /dev/null+++ b/docs/sandbox-cluster.md@@ -0,0 +1,58 @@+# WeKnora 沙箱集群与标准模板++本文面向部署和平台管理员,说明如何把 CubeSandbox 或 E2B 接入 WeKnora。Docker、Local、CubeSandbox、E2B 都在同一个空间设置页面通过同一套配置与检查接口管理;只有远端后端需要本文所述的集群和模板准备。普通智能体使用者不需要搭建模板,也不应该逐项猜测运行环境。++## 谁负责什么++| 角色 | 职责 |+| --- | --- |+| WeKnora 发布流程 | 维护 `docker/Dockerfile.sandbox`,发布与 WeKnora 版本匹配的 `wechatopenai/weknora-sandbox` 镜像 |+| 集群管理员 | 部署 CubeSandbox 或开通 E2B,并保证控制面模板 API 可用 |+| 空间管理员 | 在“设置 → 沙箱后端”中填写集群地址和凭据,先完成连接验证,再选择接口返回的模板 |+| 智能体管理员 | 在智能体的 Skills 配置中选择已经验证过的沙箱后端 |++“WeKnora 标准模板”指模板内容由 WeKnora 维护,并不代表所有集群共享同一个模板 ID。CubeSandbox 的模板 ID、E2B 的模板 ID/别名都属于具体集群或账号;跨集群硬编码一个 ID 会指向不存在或内容不一致的模板。++## 标准模板包含什么++标准镜像定义在 `docker/Dockerfile.sandbox`,当前包含:++- Python 3.11;+- Node.js 20、npm 与 npx;+- jq 及基础 Shell 工具;+- `/workspace` 工作目录;+- UID 1000 的非 root `sandbox` 用户。++生产环境应使用与 WeKnora 相同的版本标签,不建议长期指向 `latest`。Skills 新增系统依赖时,应先更新标准镜像并重新注册模板,再切换集群的默认模板 ID。++## CubeSandbox++1. 按 [CubeSandbox Quick Start](https://github.com/TencentCloud/CubeSandbox/blob/master/docs/guide/quickstart.md) 完成控制面、计算节点、CubeProxy 和域名解析配置。生产环境还需要按官方文档完成鉴权、TLS、网络策略和多节点部署。+2. 在 WeKnora 的空间设置中填写 CubeAPI、CubeProxy、sandbox domain 和可选 API Key。若这些端点位于 RFC1918/loopback 网络,显式打开“允许访问私网集群地址”。+3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并调用集群模板列表;如果不存在名为 `weknora` 的标准模板,会从 `wechatopenai/weknora-sandbox:latest` 发起一次构建。+4. 模板构建状态会自动刷新。状态变为 `READY` 后才可选择并进入运行配置;界面显示模板名称、状态和版本,配置内部才保存该集群自己的 `template_id`。++多实例 WeKnora 必须配置 Redis,以共享 session 到 sandbox 的绑定。只有单实例开发环境才应使用内存绑定。++## E2B++E2B 官方托管服务和自建 E2B Infrastructure 都可接入。填写 API Key 后先执行“连接并继续”,流程与 Cube 相同:验证连接后列出账号可见模板,缺少 `weknora` 时通过 E2B Template API 从标准镜像启动后台构建。自建部署还需填写 API URL 和 sandbox domain;E2B 上游通过 Terraform 提供 AWS、GCP 等部署方式,具体以 [E2B self-hosting guide](https://github.com/e2b-dev/infra/blob/main/self-host.md) 和 [E2B Template 文档](https://e2b.dev/docs/template/quickstart) 为准。++## 在设置页面完成接入++1. 打开“设置 → 沙箱后端”,点击“添加沙箱后端”。+2. 填写该集群自己的 API、Proxy、sandbox domain 和凭据;这些值只保存在当前空间配置中,不读取 Sandbox 环境变量。+3. 点击“连接并继续”,验证控制面地址和凭据;连接通过后才加载模板列表。+4. 等待自动创建的标准模板就绪,或选择集群已有的兼容模板;构建中的模板不可选择,状态会自动刷新。+5. 配置运行参数;上线前可执行一次“完整验证”。完整验证会真实创建、执行并销毁一个沙箱。+6. 保存后,在智能体 Skills 配置中选择该后端。对配置的修改只影响之后新建的沙箱;已有会话仍固定使用创建时的配置。++## 上线检查++- 模板版本与 WeKnora 版本匹配,且不依赖浮动的 `latest`;+- WeKnora 到控制面、Proxy 和 sandbox domain 的 DNS、TLS 与防火墙均已打通;+- 多实例部署已配置 Redis;+- API Key 只通过密钥管理或加密配置保存;+- “连接验证”和“完整验证”均通过;+- 已配置运行中与 paused 沙箱的容量监控、费用监控和孤儿清理;+- 切换模板或集群前已确认旧会话和旧沙箱的回收策略。diff --git "a/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md" "b/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"index 6565d1e85..dac2717f4 100644--- "a/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"+++ "b/docs/wiki/\346\240\270\345\277\203\345\212\237\350\203\275/Agent\346\212\200\350\203\275\347\263\273\347\273\237.md"@@ -74,15 +74,9 @@ my-skill/执行前进行多层安全校验:危险命令检测、危险模式匹配、网络访问检测、反向 Shell 检测、参数注入检测等。-### Sandbox 模式+### Sandbox 配置-| 模式 | 说明 |-|------|------|-| `docker` | 使用 Docker 容器隔离(推荐) |-| `local` | 本地进程执行(基础安全限制) |-| `disabled` | 禁用脚本执行 |--通过环境变量 `WEKNORA_SANDBOX_MODE` 配置。+空间管理员在「设置 → 沙箱后端」中统一维护 Docker、Local、CubeSandbox 或 E2B 配置。远端模板从目标集群实时获取;缺少 WeKnora 标准模板时由系统自动创建。智能体在编辑页选择一份空间配置,没有选择时不执行技能脚本。Docker/Local 每次独立执行,CubeSandbox/E2B 则保留会话级沙箱。## 配置示例diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.tsindex 1370ebbb7..404da8d9e 100644--- a/frontend/src/api/system/index.ts+++ b/frontend/src/api/system/index.ts@@ -703,6 +703,7 @@ export interface SandboxE2BConfig {export interface SandboxConfig {sandbox_type?: stringdefault_timeout_sec?: number+ allow_private_endpoints?: booleanenv_vars?: Record<string, string>volume_mount?: SandboxVolumeMountConfigcube?: SandboxCubeConfig@@ -715,6 +716,8 @@ export interface SandboxCheckItem {name: stringok: boolean | nullmessage?: string+ /** Stable code for why a probe was skipped; localized by the caller. */+ reason?: stringlatency_ms?: number}@@ -725,23 +728,21 @@ export interface SandboxCheckResult {capabilities?: Record<string, boolean>}-/** Non-secret, inheritable defaults from the deployment's .env configuration. */-export interface SandboxProviderDefaults {- api_url?: string- proxy_url?: string- sandbox_domain?: string- template_id?: string- api_key_configured: boolean- http_timeout_sec?: number- sandbox_ttl_seconds?: number+export interface SandboxTemplate {+ id: string+ name: string+ status?: string+ version?: string+ image?: string+ created_at?: string+ updated_at?: string+ standard: boolean}-export interface SandboxConfigDefaults {- sandbox_type: string- default_timeout_sec?: number- docker_image?: string- cube?: SandboxProviderDefaults- e2b?: SandboxProviderDefaults+export interface SandboxTemplateCatalog {+ templates: SandboxTemplate[]+ standard_template_id?: string+ provisioned: boolean}/** One named sandbox backend config. Credentials arrive masked. */@@ -777,26 +778,20 @@ export interface SandboxInventory {unverifiable?: boolean}-/** Named sandbox backends that support per-config credentials (cube/e2b only). */-export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b'] as const+/** Sandbox backends managed as named workspace configurations. */+export const NAMED_SANDBOX_BACKEND_TYPES = ['cube', 'e2b', 'docker', 'local'] as constexport function isNamedSandboxBackend(type: string): boolean {return (NAMED_SANDBOX_BACKEND_TYPES as readonly string[]).includes(type)}-/**- * Returns every config of the workspace plus the deployment defaults an empty- * field inherits. An empty list means "no named config yet", in which case- * agents run on those defaults — which is NOT the same as disabled.- */+/** Returns every sandbox config of the workspace. No config means disabled. */export function listSandboxConfigs(): Promise<{data: SandboxConfigRecord[]- defaults?: SandboxConfigDefaultsworkspace_scripts_disabled?: boolean}> {return get('/api/v1/sandbox-configs') as unknown as Promise<{data: SandboxConfigRecord[]- defaults?: SandboxConfigDefaultsworkspace_scripts_disabled?: boolean}>}@@ -848,6 +843,21 @@ export function getSandboxConfigInventory(id: string): Promise<{ data: SandboxIn}>}+/**+ * Fetch templates using the connection currently entered in the drawer.+ * `ensure_standard` starts a provider-side build when no WeKnora template is+ * present; the returned building item can be polled through the same endpoint.+ */+export function querySandboxTemplates(payload: {+ config: SandboxConfig+ config_id?: string+ ensure_standard?: boolean+}): Promise<{ data: SandboxTemplateCatalog }> {+ return post('/api/v1/sandbox-configs/templates/query', payload) as unknown as Promise<{+ data: SandboxTemplateCatalog+ }>+}+/*** Probe a sandbox configuration without saving it. Redacted secrets are* resolved server-side, so pass `config_id` alongside an edited `config` todiff --git a/frontend/src/assets/img/providers/mono/sandbox/docker.svg b/frontend/src/assets/img/providers/mono/sandbox/docker.svgnew file mode 100644index 000000000..0021a8a7b--- /dev/null+++ b/frontend/src/assets/img/providers/mono/sandbox/docker.svg@@ -0,0 +1 @@+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Docker</title><path d="M13.983 11.078h2.119a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.119a.185.185 0 00-.185.185v1.888c0 .102.083.185.185.185m-2.954-5.43h2.118a.186.186 0 00.186-.186V3.574a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m0 2.716h2.118a.187.187 0 00.186-.186V6.29a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.887c0 .102.082.185.185.186m-2.93 0h2.12a.186.186 0 00.184-.186V6.29a.185.185 0 00-.185-.185H8.1a.185.185 0 00-.185.185v1.887c0 .102.083.185.185.186m-2.964 0h2.119a.186.186 0 00.185-.186V6.29a.185.185 0 00-.185-.185H5.136a.186.186 0 00-.186.185v1.887c0 .102.084.185.186.186m5.893 2.715h2.118a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m-2.93 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.083.185.185.185m-2.964 0h2.119a.185.185 0 00.185-.185V9.006a.185.185 0 00-.184-.186h-2.12a.186.186 0 00-.186.186v1.887c0 .102.084.185.186.185m-2.92 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.082.185.185.185M23.763 9.89c-.065-.051-.672-.51-1.954-.51-.338.001-.676.03-1.01.087-.248-1.7-1.653-2.53-1.716-2.566l-.344-.199-.226.327c-.284.438-.49.922-.612 1.43-.23.97-.09 1.882.403 2.661-.595.332-1.55.413-1.744.42H.751a.751.751 0 00-.75.748 11.376 11.376 0 00.692 4.062c.545 1.428 1.355 2.48 2.41 3.124 1.18.723 3.1 1.137 5.275 1.137.983.003 1.963-.086 2.93-.266a12.248 12.248 0 003.823-1.389c.98-.567 1.86-1.288 2.61-2.136 1.252-1.418 1.998-2.997 2.553-4.4h.221c1.372 0 2.215-.549 2.68-1.009.309-.293.55-.65.707-1.046l.098-.288Z"/></svg>\ No newline at end of filediff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vueindex 9e5bfaf86..1179b793e 100644--- a/frontend/src/components/SandboxConfigEditorDrawer.vue+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue@@ -1,19 +1,44 @@<template>- <t-drawer+ <SettingDrawer+ class="sandbox-config-drawer":visible="visible"- :header="record ? $t('settings.sandbox.editTitle') : $t('settings.sandbox.createTitle')"- size="620px"- :confirm-btn="{ content: $t('common.save'), loading: saving }"- :cancel-btn="{ content: $t('common.cancel') }"- @confirm="save"- @close="close"+ :title="record ? $t('settings.sandbox.editTitle') : $t('settings.sandbox.createTitle')"+ :description="stepDescription"+ icon="server"+ width="680px"+ :min-width="560"+ :max-width="920"+ storage-key="setting-drawer:width:sandbox-config-v2"+ :confirm-loading="saving || checking || templatesLoading"+ :confirm-disabled="primaryDisabled"+ :confirm-text="primaryText"+ @confirm="handlePrimaryAction"+ @cancel="close"@update:visible="(v: boolean) => emit('update:visible', v)">+ <template #footer-left>+ <t-button v-if="wizardStep > 0" variant="outline" @click="previousStep">+ {{ $t('settings.sandbox.back') }}+ </t-button>+ </template>++ <nav class="sandbox-steps" :aria-label="$t('settings.sandbox.setupProgress')">+ <div v-for="(item, index) in wizardSteps" :key="item.key"+ :class="['sandbox-step', { 'is-active': wizardStep === index, 'is-done': wizardStep > index }]">+ <span class="sandbox-step__marker">+ <t-icon v-if="wizardStep > index" name="check" />+ <template v-else>{{ index + 1 }}</template>+ </span>+ <span class="sandbox-step__title">{{ item.title }}</span>+ <span v-if="index < wizardSteps.length - 1" class="sandbox-step__line" aria-hidden="true" />+ </div>+ </nav>+<!--Identity-change refusals must sit at the top: the form is long and theadmin otherwise saves, sees nothing, and assumes the click did nothing.-->- <div v-if="conflict" ref="conflictAlertRef" class="blocked blocked-top">+ <div v-if="conflict && currentStepKey === 'runtime'" ref="conflictAlertRef" class="blocked blocked-top"><t-alert v-if="conflict.code === 'sandboxes_still_live'" theme="warning":message="$t('settings.sandbox.sandboxesStillLive', { count: conflict.inventory?.sandbox_count ?? 0 })"><template #description>@@ -31,167 +56,351 @@</t-alert></div>- <t-form label-align="top">- <t-form-item :label="$t('settings.sandbox.configName')" :status="nameError ? 'error' : undefined"- :tips="nameError || undefined">- <t-input v-model="name" :placeholder="$t('settings.sandbox.configNamePlaceholder')" />- </t-form-item>- <t-form-item :label="$t('settings.sandbox.configDescription')">- <t-input v-model="description" :placeholder="$t('settings.sandbox.configDescriptionPlaceholder')" />- </t-form-item>-- <!--- Only while editing: a config being created owns no sandboxes yet, so- warning that these fields are locked would describe a restriction that- does not apply.- -->- <t-alert v-if="record" theme="info" class="identity-hint"- :message="$t('settings.sandbox.identityFieldHint')" />-- <t-form-item :label="$t('settings.sandbox.backend')">- <t-select v-model="backend" @change="onBackendChange">- <t-option v-for="opt in backendOptions" :key="opt" :value="opt" :label="backendLabel(opt)" />- </t-select>- </t-form-item>-- <!--- Placeholders are format examples, never the deployment's own values: a- named config inherits nothing, so showing what .env holds would suggest- an empty field still works.- -->- <!-- Cube -->- <template v-if="backend === 'cube'">- <t-form-item :label="requiredLabel('apiUrl')" :status="fieldStatus('api_url')" :tips="fieldTip('api_url')">- <t-input v-model="cube.api_url" placeholder="http://cube.example.com:33000"- @input="onFieldInput('api_url')" />- </t-form-item>- <t-form-item :label="requiredLabel('proxyUrl')" :status="fieldStatus('proxy_url')"- :tips="fieldTip('proxy_url')">- <t-input v-model="cube.proxy_url" placeholder="http://cube.example.com:80"- @input="onFieldInput('proxy_url')" />- </t-form-item>- <t-form-item :label="requiredLabel('sandboxDomain')" :status="fieldStatus('sandbox_domain')"- :tips="fieldTip('sandbox_domain')">- <t-input v-model="cube.sandbox_domain" placeholder="cube.app" @input="onFieldInput('sandbox_domain')" />+ <t-form label-align="top" class="sandbox-editor-form">+ <section v-if="currentStepKey === 'connection'" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionBasic') }}</h4>+ <t-form-item :label="$t('settings.sandbox.backendType')">+ <t-select :value="backend" :placeholder="$t('settings.sandbox.backendTypePlaceholder')"+ class="backend-select" :popup-props="{ overlayClassName: 'sandbox-backend-popup' }"+ @change="(v: any) => selectBackend(String(v))">+ <t-option v-for="opt in backendOptions" :key="opt" :value="opt" :label="backendLabel(opt)">+ <span class="backend-choice">+ <SandboxBackendBadge :type="opt" size="sm" />+ <span class="backend-choice__text">+ <span class="backend-choice__name">{{ backendLabel(opt) }}</span>+ <span class="backend-choice__desc">+ {{ $t(`settings.sandbox.backendDescriptions.${opt}`) }}+ </span>+ </span>+ </span>+ </t-option>+ </t-select>+ <p v-if="backend" class="section-help section-help--field">+ {{ $t(`settings.sandbox.backendDescriptions.${backend}`) }}+ </p></t-form-item>- <t-form-item :label="$t('settings.sandbox.apiKey')" :help="$t('settings.sandbox.cubeApiKeyOptional')">- <t-input v-model="cube.api_key" type="password" :placeholder="secretPlaceholder" />+ <t-form-item :label="$t('settings.sandbox.configName')" :status="nameError ? 'error' : undefined"+ :tips="nameError || undefined">+ <t-input v-model="name" :placeholder="$t('settings.sandbox.configNamePlaceholder')" /></t-form-item>- <t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"- :tips="fieldTip('template_id')">- <t-input v-model="cube.template_id" placeholder="tpl-xxxxxxxx" @input="onFieldInput('template_id')" />+ <t-form-item :label="$t('settings.sandbox.configDescription')">+ <t-input v-model="description" :placeholder="$t('settings.sandbox.configDescriptionPlaceholder')" /></t-form-item>- <div class="timeout-row">- <t-form-item :label="$t('settings.sandbox.httpTimeout')">- <t-input-number v-model="cube.http_timeout_sec" :min="0" theme="column" placeholder="30" />+ </section>++ <section v-if="currentStepKey === 'connection' && isRemoteBackend" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionConnection') }}</h4>+ <t-alert v-if="record" theme="info" class="identity-hint compact-alert"+ :message="$t('settings.sandbox.identityFieldHint')" />++ <template v-if="backend === 'cube'">+ <t-form-item :label="requiredLabel('apiUrl')" :status="fieldStatus('api_url')" :tips="fieldTip('api_url')">+ <t-input v-model="cube.api_url" placeholder="http://cube.example.com:33000"+ @input="onConnectionInput('api_url')" /></t-form-item>- <t-form-item :label="$t('settings.sandbox.sandboxTtl')">- <t-input-number v-model="cube.cube_sandbox_ttl_seconds" :min="0" theme="column" placeholder="1800" />+ <div class="form-grid form-grid--two">+ <t-form-item :label="requiredLabel('proxyUrl')" :status="fieldStatus('proxy_url')"+ :tips="fieldTip('proxy_url')">+ <t-input v-model="cube.proxy_url" placeholder="http://cube.example.com:80"+ @input="onConnectionInput('proxy_url')" />+ </t-form-item>+ <t-form-item :label="requiredLabel('sandboxDomain')" :status="fieldStatus('sandbox_domain')"+ :tips="fieldTip('sandbox_domain')">+ <t-input v-model="cube.sandbox_domain" placeholder="cube.app"+ @input="onConnectionInput('sandbox_domain')" />+ </t-form-item>+ </div>+ <t-form-item :label="$t('settings.sandbox.apiKey')">+ <t-input v-model="cube.api_key" type="password" :placeholder="secretInputPlaceholder('cube')"+ @input="invalidateConnection" />+ <div class="field-hints">+ <p class="section-help">+ {{ storedSecrets.cube+ ? $t('settings.sandbox.secretConfigured')+ : $t('settings.sandbox.cubeApiKeyOptional') }}+ </p>+ <a class="inline-guide-link" :href="clusterGuideUrl" target="_blank" rel="noopener noreferrer">+ <t-icon name="link" />+ {{ $t('settings.sandbox.cubeApiKeyWhere') }}+ </a>+ </div></t-form-item>- <t-form-item :label="$t('settings.sandbox.defaultTimeout')">- <t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"- :placeholder="String(defaults?.default_timeout_sec || 60)" />+ </template>++ <template v-else-if="backend === 'e2b'">+ <t-form-item :label="requiredLabel('apiKey')" :status="fieldStatus('api_key')"+ :tips="fieldTip('api_key')">+ <t-input v-model="e2b.api_key" type="password" :placeholder="secretInputPlaceholder('e2b')"+ @input="onConnectionInput('api_key')" />+ <div class="field-hints">+ <p class="section-help">+ {{ storedSecrets.e2b+ ? $t('settings.sandbox.secretConfigured')+ : $t('settings.sandbox.e2bApiKeyHelp') }}+ </p>+ <a class="inline-guide-link" :href="e2bApiKeysUrl" target="_blank" rel="noopener noreferrer">+ <t-icon name="link" />+ {{ $t('settings.sandbox.e2bApiKeyWhere') }}+ </a>+ </div></t-form-item>+ <div class="form-grid form-grid--two">+ <t-form-item :label="$t('settings.sandbox.apiUrl')" :help="$t('settings.sandbox.e2bApiUrlOptional')">+ <t-input v-model="e2b.api_url" placeholder="https://api.e2b.app" @input="invalidateConnection" />+ </t-form-item>+ <t-form-item :label="$t('settings.sandbox.sandboxDomain')" :help="$t('settings.sandbox.e2bDomainOptional')">+ <t-input v-model="e2b.sandbox_domain" placeholder="e2b.app" @input="invalidateConnection" />+ </t-form-item>+ </div>+ </template>+ <div class="private-endpoint-row">+ <div>+ <p class="private-endpoint-row__title">{{ $t('settings.sandbox.allowPrivateEndpoints') }}</p>+ <p class="section-help">{{ $t('settings.sandbox.allowPrivateEndpointsHint') }}</p>+ </div>+ <t-switch v-model="allowPrivateEndpoints" @change="invalidateConnection" /></div>- </template>+ </section>- <!-- E2B -->- <template v-else-if="backend === 'e2b'">- <t-form-item :label="$t('settings.sandbox.apiUrl')" :help="$t('settings.sandbox.e2bApiUrlOptional')">- <t-input v-model="e2b.api_url" placeholder="https://api.e2b.app" @input="invalidateCheck" />- </t-form-item>- <t-form-item :label="$t('settings.sandbox.sandboxDomain')" :help="$t('settings.sandbox.e2bDomainOptional')">- <t-input v-model="e2b.sandbox_domain" placeholder="e2b.app" />- </t-form-item>- <t-form-item :label="requiredLabel('apiKey')" :status="fieldStatus('api_key')" :tips="fieldTip('api_key')">- <t-input v-model="e2b.api_key" type="password" :placeholder="secretPlaceholder"- @input="onFieldInput('api_key')" />- </t-form-item>- <t-form-item :label="requiredLabel('templateId')" :status="fieldStatus('template_id')"- :tips="fieldTip('template_id')">- <t-input v-model="e2b.template_id" placeholder="xxxxxxxxxxxxxxxx"- @input="onFieldInput('template_id')" />- </t-form-item>- <div class="timeout-row">- <t-form-item :label="$t('settings.sandbox.httpTimeout')">- <t-input-number v-model="e2b.http_timeout_sec" :min="0" theme="column" placeholder="30" />- </t-form-item>- <t-form-item :label="$t('settings.sandbox.sandboxTtl')">- <t-input-number v-model="e2b.e2b_sandbox_ttl_seconds" :min="0" theme="column" placeholder="300" />+ <section v-if="currentStepKey === 'connection' && !isRemoteBackend" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionRuntimeEnvironment') }}</h4>+ <template v-if="backend === 'docker'">+ <div class="weknora-template-card is-active">+ <SandboxBackendBadge type="docker" />+ <div class="weknora-template-card__content">+ <div class="weknora-template-card__title-row">+ <span class="weknora-template-card__title">{{ $t('settings.sandbox.weknoraDockerImage') }}</span>+ <t-tag theme="primary" variant="light" size="small">{{ $t('settings.sandbox.recommendedTag') }}</t-tag>+ </div>+ <p>{{ $t('settings.sandbox.weknoraDockerImageHint') }}</p>+ </div>+ </div>+ <t-form-item :label="requiredLabel('dockerImage')" :status="fieldStatus('image')"+ :tips="fieldTip('image')">+ <t-input v-model="docker.image" placeholder="wechatopenai/weknora-sandbox:latest"+ @input="onFieldInput('image')" /></t-form-item>+ </template>+ <t-alert v-else theme="warning" class="compact-alert" :message="$t('settings.sandbox.localRuntimeWarning')" />+ </section>++ <section v-if="currentStepKey === 'template'" class="setting-drawer__section">+ <div class="section-title-row">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionTemplate') }}</h4>+ <t-button variant="text" size="small" :loading="templatesLoading" @click="loadTemplates(true)">+ <template #icon><t-icon name="refresh" /></template>+ {{ $t('settings.sandbox.refreshTemplates') }}+ </t-button>+ </div>+ <div class="connection-summary" role="status">+ <span class="connection-summary__icon"><t-icon name="check" /></span>+ <div>+ <p class="connection-summary__title">{{ $t('settings.sandbox.connectionPassedTitle') }}</p>+ <p class="connection-summary__text">{{ $t('settings.sandbox.connectionPassed') }}</p>+ </div>+ </div>+ <p class="section-help">{{ $t('settings.sandbox.templateStepHint') }}</p>+ <div v-if="templatesLoading && !templatesLoaded" class="template-loading">+ <t-loading size="small" />+ <span>{{ $t('settings.sandbox.loadingTemplates') }}</span>+ </div>+ <div v-else-if="templates.length" class="template-list" role="radiogroup"+ :aria-label="$t('settings.sandbox.sectionTemplate')">+ <button v-for="item in templates" :key="item.id" type="button" class="template-card"+ :class="{ 'is-active': currentTemplateId === item.id, 'is-pending': isTemplatePending(item) }"+ :disabled="!isTemplateSelectable(item)" role="radio" :aria-checked="currentTemplateId === item.id"+ @click="selectTemplate(item.id)">+ <span class="template-card__badge">+ <t-icon :name="isTemplatePending(item) ? 'time' : 'code'" />+ </span>+ <span class="template-card__body">+ <span class="template-card__title-row">+ <span class="template-card__title">{{ item.name }}</span>+ <t-tag v-if="item.standard" theme="primary" variant="light" size="small">+ {{ $t('settings.sandbox.recommendedTag') }}+ </t-tag>+ </span>+ <span class="template-card__meta">{{ templateMeta(item) }}</span>+ <!--+ An untagged template is indistinguishable from a building one in+ the provider's list, so it needs its own line: waiting is futile+ and only a rebuild fixes it.+ -->+ <span v-if="isTemplateUntagged(item)" class="template-card__hint template-card__hint--error">+ {{ $t('settings.sandbox.templateUntaggedHint') }}+ </span>+ <span v-else-if="isTemplatePending(item) && item.standard" class="template-card__hint">+ {{ $t('settings.sandbox.templateBuildingHint') }}+ </span>+ </span>+ <span class="template-card__state">+ <t-tag :theme="templateStatusTheme(item)" variant="light" size="small">+ {{ templateStatusLabel(item) }}+ </t-tag>+ <t-icon v-if="currentTemplateId === item.id" name="check-circle-filled"+ class="template-card__selected" />+ </span>+ </button>+ </div>+ <div v-else-if="templatesLoaded && !templatesError" class="env-empty">+ {{ $t('settings.sandbox.noTemplates') }}+ </div>+ <div v-if="selectedTemplate" class="template-state-note template-state-note--ready" role="status">+ <t-icon name="check-circle-filled" />+ <span>{{ $t('settings.sandbox.templateReadyHint', { name: selectedTemplate.name }) }}</span>+ </div>+ <div v-else-if="hasPendingTemplates" class="template-state-note" role="status">+ <t-icon name="time" />+ <span>{{ $t('settings.sandbox.templateProvisioningHint') }}</span>+ </div>+ <t-alert v-if="templatesError" theme="warning" class="compact-alert" :message="templatesError" />+ <p v-else-if="!templatesLoaded" class="section-help">+ {{ $t('settings.sandbox.templateLoadHint') }}+ </p>+ <a class="inline-guide-link" :href="clusterGuideUrl" target="_blank" rel="noopener noreferrer">+ <t-icon name="link" />+ {{ $t('settings.sandbox.howToBuildTemplate') }}+ </a>+ </section>++ <section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionRuntime') }}</h4>+ <!--+ Three unlabelled numbers side by side shared one footnote, so nobody+ could tell which limit they were raising. Each gets its own row and+ its own sentence naming what it bounds and what happens on expiry.+ -->+ <div class="runtime-fields">+ <template v-if="isRemoteBackend">+ <t-form-item :label="$t('settings.sandbox.httpTimeout')">+ <t-input-number v-if="backend === 'cube'" v-model="cube.http_timeout_sec" :min="0" theme="column"+ placeholder="30" />+ <t-input-number v-else v-model="e2b.http_timeout_sec" :min="0" theme="column" placeholder="30" />+ </t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.httpTimeoutHelp') }}</p>+ <t-form-item :label="$t('settings.sandbox.sandboxTtl')">+ <t-input-number v-if="backend === 'cube'" v-model="cube.cube_sandbox_ttl_seconds" :min="0"+ theme="column" placeholder="1800" />+ <t-input-number v-else v-model="e2b.e2b_sandbox_ttl_seconds" :min="0" theme="column"+ placeholder="300" />+ </t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.sandboxTtlHelp') }}</p>+ </template><t-form-item :label="$t('settings.sandbox.defaultTimeout')">- <t-input-number v-model="defaultTimeoutSec" :min="0" theme="column"- :placeholder="String(defaults?.default_timeout_sec || 60)" />+ <t-input-number v-model="defaultTimeoutSec" :min="0" theme="column" placeholder="60" /></t-form-item>+ <p class="section-help section-help--field">{{ $t('settings.sandbox.defaultTimeoutHelp') }}</p></div>- </template>+ </section>- <!-- Environment variables: a map on the wire, editable rows in the UI. -->- <t-form-item :label="$t('settings.sandbox.envVars')"- :help="$t('settings.sandbox.envVarsHint')">- <div class="env-rows">- <div v-for="(row, index) in envRows" :key="index" class="env-row">- <t-input v-model="row.key" :placeholder="$t('settings.sandbox.envKey')" style="width: 200px" />- <t-input v-model="row.value" type="password" :placeholder="$t('settings.sandbox.envValue')"- style="width: 220px" />- <t-button variant="text" theme="danger" @click="envRows.splice(index, 1)">- {{ $t('settings.sandbox.removeRow') }}- </t-button>+ <section v-if="currentStepKey === 'runtime'" class="setting-drawer__section">+ <div class="section-title-row">+ <div>+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.sectionEnvironment') }}</h4>+ <p class="section-help section-help--under-title">{{ $t('settings.sandbox.envVarsHint') }}</p></div>- <t-button variant="outline" size="small" @click="envRows.push({ key: '', value: '' })">+ <t-button variant="text" size="small" @click="envRows.push({ key: '', value: '' })">+ <template #icon><t-icon name="add" /></template>{{ $t('settings.sandbox.addRow') }}</t-button></div>- </t-form-item>+ <div v-if="envRows.length" class="env-rows">+ <div v-for="(row, index) in envRows" :key="index" class="env-row">+ <t-input v-model="row.key" :placeholder="$t('settings.sandbox.envKey')" class="env-key" />+ <t-input v-model="row.value" type="password"+ :placeholder="row.stored ? $t('settings.sandbox.secretKeepHint') : $t('settings.sandbox.envValue')"+ class="env-value" />+ <t-button variant="text" shape="square" size="small" :aria-label="$t('common.delete')"+ @click="envRows.splice(index, 1)">+ <t-icon name="close" />+ </t-button>+ </div>+ </div>+ <div v-else class="env-empty">{{ $t('settings.sandbox.noEnvVars') }}</div>+ </section></t-form>- <div v-if="isRemoteBackend" class="check-actions">- <t-button variant="outline" :loading="checking" @click="runCheck(false)">- {{ $t('settings.sandbox.testConnection') }}- </t-button>- <t-popconfirm :content="$t('settings.sandbox.deepCheckConfirm')" @confirm="runCheck(true)">- <t-button variant="outline" :loading="checking">- {{ $t('settings.sandbox.deepCheck') }}- </t-button>- </t-popconfirm>- </div>-- <div v-if="checkResult" ref="checkResultRef" class="check-result">- <t-alert :theme="checkResult.ok ? 'success' : 'error'"- :message="checkResult.ok ? $t('settings.sandbox.checkPassed') : $t('settings.sandbox.checkFailed')" />+ <div v-if="checkResult && currentStepKey !== 'template'" ref="checkResultRef" class="check-result">+ <div :class="['check-result__summary', checkResult.ok ? 'is-success' : 'is-error']">+ <span class="check-result__summary-icon">+ <t-icon :name="checkResult.ok ? 'check-circle-filled' : 'close-circle-filled'" />+ </span>+ <div>+ <p class="check-result__title">+ {{ checkResult.ok ? $t('settings.sandbox.checkPassed') : $t('settings.sandbox.checkFailed') }}+ </p>+ <p class="check-result__subtitle">{{ checkScopeHint }}</p>+ </div>+ </div><ul class="check-list">- <li v-for="item in checkResult.checks" :key="item.name" class="check-item">+ <li v-for="item in reportedChecks" :key="item.name" class="check-item"><t-icon :name="item.ok === true ? 'check-circle-filled': item.ok === false ? 'close-circle-filled' : 'minus-circle'":class="item.ok === true ? 'ok' : item.ok === false ? 'err' : 'skip'" /><span class="check-name">{{ checkLabel(item.name) }}</span><span v-if="item.latency_ms" class="check-latency">{{ item.latency_ms }} ms</span>- <span v-if="item.message" class="check-message">{{ item.message }}</span>+ <span v-if="checkDetail(item)" class="check-message">{{ checkDetail(item) }}</span></li></ul>+ <!--+ Probes that need a live sandbox used to be listed as three grey "not+ checked" rows, which made a passing connection test read as half broken+ and never said how to run them. They are one sentence plus the action+ that performs them instead. The action stays put even once nothing is+ pending, because a failed run is precisely when it has to be repeatable.+ -->+ <div class="check-pending">+ <p v-if="pendingCheckNames.length" class="check-pending__text">+ {{ $t('settings.sandbox.checkPendingHint', { names: pendingCheckNames.join('、') }) }}+ </p>+ <t-popconfirm :content="$t('settings.sandbox.deepCheckConfirm')" @confirm="runCheck(true)">+ <t-button variant="outline" size="small" :loading="checking">+ {{ lastCheckWasDeep ? $t('settings.sandbox.recheck') : $t('settings.sandbox.deepCheck') }}+ </t-button>+ </t-popconfirm>+ </div><t-alert v-if="checkResult.capabilities && checkResult.capabilities.supports_volumes === false" theme="warning"+ class="compact-alert":message="$t('settings.sandbox.noVolumeSupport')" /></div>- </t-drawer>+ <!--+ Without a result on screen there is nothing for the pending row above to+ hang off, so the same offer stands alone. Editing a field discards the+ previous result, which is exactly when this reappears.+ -->+ <div v-else-if="currentStepKey === 'runtime'" class="check-pending check-pending--standalone">+ <p class="check-pending__text">{{ $t('settings.sandbox.deepCheckIntro') }}</p>+ <t-popconfirm :content="$t('settings.sandbox.deepCheckConfirm')" @confirm="runCheck(true)">+ <t-button variant="outline" size="small" :loading="checking">+ {{ $t('settings.sandbox.deepCheck') }}+ </t-button>+ </t-popconfirm>+ </div>++ </SettingDrawer></template><script setup lang="ts">-import { computed, nextTick, reactive, ref, watch } from 'vue'+import { computed, nextTick, onUnmounted, reactive, ref, watch } from 'vue'import { MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'+import SettingDrawer from '@/components/settings/SettingDrawer.vue'+import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'import {checkSandboxConfig,createSandboxConfig,parseSandboxConflict,updateSandboxConfigById,+ querySandboxTemplates,+ type SandboxCheckItem,type SandboxCheckResult,type SandboxConfig,- type SandboxConfigDefaults,type SandboxConfigRecord,type SandboxConflict,type SandboxCubeConfig,type SandboxE2BConfig,+ type SandboxTemplate,isNamedSandboxBackend,NAMED_SANDBOX_BACKEND_TYPES,} from '@/api/system'@@ -200,7 +409,6 @@ const props = defineProps<{visible: booleanrecord: SandboxConfigRecord | nullpresetType?: string- defaults: SandboxConfigDefaults | null}>()const emit = defineEmits<{@@ -210,15 +418,22 @@ const emit = defineEmits<{const { t } = useI18n()-// The backend echoes secrets as this placeholder; submitting it unchanged keeps-// the stored value, so the form never needs the real key.+// The backend echoes stored secrets as this placeholder. It never leaves the+// form as visible text: inputs stay empty and say "configured", and the+// placeholder is only re-attached on submit so the stored value survives.const secretPlaceholder = '***'+const isMaskedSecret = (value?: string) => value === secretPlaceholder++const clusterGuideUrl = 'https://github.com/Tencent/WeKnora/blob/main/docs/sandbox-cluster.md'+const e2bApiKeysUrl = 'https://e2b.dev/dashboard?tab=keys'const backendOptions = [...NAMED_SANDBOX_BACKEND_TYPES]const saving = ref(false)const checking = ref(false)const checkResult = ref<SandboxCheckResult | null>(null)+// Distinguishes "run the deep probes" from "run them again" on the panel button.+const lastCheckWasDeep = ref(false)const conflict = ref<SandboxConflict | null>(null)const conflictAlertRef = ref<HTMLElement | null>(null)const checkResultRef = ref<HTMLElement | null>(null)@@ -230,22 +445,90 @@ const backend = ref('')// undefined rather than 0 so the input renders empty and shows its placeholder,// matching the HTTP timeout / TTL fields. A literal 0 would read as a real value.const defaultTimeoutSec = ref<number | undefined>(undefined)+const allowPrivateEndpoints = ref(false)const cube = reactive<SandboxCubeConfig>({})const e2b = reactive<SandboxE2BConfig>({})-const envRows = ref<{ key: string; value: string }[]>([])+const docker = reactive<{ image?: string }>({})+// Tracks which secrets the tenant already has stored, so an empty input can+// mean "keep the saved key" instead of "no key configured".+const storedSecrets = reactive({ cube: false, e2b: false })+const envRows = ref<{ key: string; value: string; stored?: boolean }[]>([])+const templates = ref<SandboxTemplate[]>([])+const templatesLoading = ref(false)+const templatesLoaded = ref(false)+const templatesError = ref('')+const wizardStep = ref(0)+let templatePollTimer: ReturnType<typeof setTimeout> | undefined-// Only remote backends have a control plane worth probing.+// Remote backends additionally expose a template catalog and control-plane+// settings. All four backends still share the same save/check API.const isRemoteBackend = computed(() => backend.value === 'cube' || backend.value === 'e2b')+const currentTemplateId = computed(() => (+ backend.value === 'cube' ? cube.template_id : backend.value === 'e2b' ? e2b.template_id : ''+)?.trim() || '')+const selectedTemplate = computed(() => templates.value.find((item) => item.id === currentTemplateId.value))+type SandboxStepKey = 'connection' | 'template' | 'runtime'+const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() => {+ const steps: Array<{ key: SandboxStepKey; title: string }> = [+ { key: 'connection', title: t('settings.sandbox.stepConnection') },+ ]+ if (isRemoteBackend.value) {+ steps.push({ key: 'template', title: t('settings.sandbox.stepTemplate') })+ }+ steps.push({ key: 'runtime', title: t('settings.sandbox.stepRuntime') })+ return steps+})+const currentStepKey = computed<SandboxStepKey>(() => wizardSteps.value[wizardStep.value]?.key || 'connection')+const stepDescription = computed(() => t(`settings.sandbox.stepDescriptions.${currentStepKey.value}`))+const primaryText = computed(() => {+ if (currentStepKey.value === 'connection') return t('settings.sandbox.connectAndContinue')+ if (currentStepKey.value === 'template') return t('common.next')+ return t('common.save')+})+const primaryDisabled = computed(() => (+ currentStepKey.value === 'template'+ && (!selectedTemplate.value || !isTemplateSelectable(selectedTemplate.value))+))+const hasPendingTemplates = computed(() => templates.value.some(isTemplatePending))const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)const checkLabel = (probe: string) => t(`settings.sandbox.checks.${probe}`, probe)+// Probes deferred to the opt-in deep check are expected, not a problem, so they+// are pulled out of the result list and explained once.+const PENDING_SKIP_REASON = 'needs_deep_check'++const reportedChecks = computed(() => (checkResult.value?.checks || []).filter(+ (item) => item.ok !== null || item.reason !== PENDING_SKIP_REASON,+))++const pendingCheckNames = computed(() => (checkResult.value?.checks || [])+ .filter((item) => item.ok === null && item.reason === PENDING_SKIP_REASON)+ .map((item) => checkLabel(item.name)))++// Says which layer the verdict covers, so "检测通过" is not read as "everything+// works" after a connection-only probe.+const checkScopeHint = computed(() => (pendingCheckNames.value.length+ ? t('settings.sandbox.checkScopeConnection')+ : t('settings.sandbox.checkScopeFull')))++function checkDetail(item: SandboxCheckItem): string {+ if (item.message) return item.message+ if (!item.reason) return ''+ return t(`settings.sandbox.skipReasons.${item.reason}`, item.reason)+}+const secretInputPlaceholder = (target: 'cube' | 'e2b') => (+ storedSecrets[target] ? t('settings.sandbox.secretKeepHint') : t('settings.sandbox.apiKeyPlaceholder')+)+// Mirrors sandbox.MissingRequiredFields on the server. Duplicated on purpose:// the server stays the authority, this only spares the admin a round-trip and// points at the offending input instead of showing one combined message.const REQUIRED_FIELDS: Record<string, string[]> = {cube: ['api_url', 'proxy_url', 'sandbox_domain', 'template_id'],e2b: ['api_key', 'template_id'],+ docker: ['image'],+ local: [],}const fieldErrors = ref<Record<string, string>>({})@@ -262,9 +545,22 @@ function onFieldInput(field: string) {invalidateCheck()}-function validateRequiredFields(): boolean {- const required = REQUIRED_FIELDS[backend.value] || []- const values = (backend.value === 'cube' ? cube : e2b) as Record<string, unknown>+function onConnectionInput(field: string) {+ delete fieldErrors.value[field]+ invalidateConnection()+}++// Snapshot of the active backend block as it will be submitted, so a secret the+// admin left blank on purpose still counts as filled in.+function submittedBackendValues(): Record<string, unknown> {+ if (backend.value === 'cube') return withStoredSecret({ ...cube }, storedSecrets.cube)+ if (backend.value === 'e2b') return withStoredSecret({ ...e2b }, storedSecrets.e2b)+ return { ...docker }+}++function validateRequiredFields(includeTemplate = true): boolean {+ const required = (REQUIRED_FIELDS[backend.value] || []).filter((field) => includeTemplate || field !== 'template_id')+ const values = submittedBackendValues()const errors: Record<string, string> = {}for (const field of required) {const value = values[field]@@ -281,12 +577,11 @@ const affectedSessionCount = computed(() => conflict.value?.inventory?.session_ifunction defaultBackendType(): string {const fromRecord = props.record?.config?.sandbox_type || props.presetType || ''if (isNamedSandboxBackend(fromRecord)) return fromRecord- const fromDeploy = props.defaults?.sandbox_type || ''- if (isNamedSandboxBackend(fromDeploy)) return fromDeployreturn 'cube'}function reset() {+ stopTemplatePolling()const cfg: SandboxConfig = props.record?.config || {}name.value = props.record?.name || ''description.value = props.record?.description || ''@@ -294,53 +589,247 @@ function reset() {? cfg.sandbox_type!: defaultBackendType()defaultTimeoutSec.value = cfg.default_timeout_sec || undefined+ allowPrivateEndpoints.value = cfg.allow_private_endpoints === true// Replace rather than merge: a reused reactive object would otherwise carry// the previously edited config's fields into the next one opened.Object.keys(cube).forEach((key) => delete (cube as Record<string, unknown>)[key])Object.keys(e2b).forEach((key) => delete (e2b as Record<string, unknown>)[key])+ Object.keys(docker).forEach((key) => delete (docker as Record<string, unknown>)[key])Object.assign(cube, cfg.cube || {})Object.assign(e2b, cfg.e2b || {})- envRows.value = Object.entries(cfg.env_vars || {}).map(([key, value]) => ({ key, value }))+ Object.assign(docker, cfg.docker || {})+ if (backend.value === 'docker' && !docker.image) {+ docker.image = 'wechatopenai/weknora-sandbox:latest'+ }+ storedSecrets.cube = isMaskedSecret(cube.api_key)+ storedSecrets.e2b = isMaskedSecret(e2b.api_key)+ if (storedSecrets.cube) cube.api_key = ''+ if (storedSecrets.e2b) e2b.api_key = ''+ envRows.value = Object.entries(cfg.env_vars || {}).map(([key, value]) => (+ isMaskedSecret(value) ? { key, value: '', stored: true } : { key, value }+ ))checkResult.value = nullconflict.value = nullnameError.value = ''fieldErrors.value = {}+ templates.value = []+ templatesLoaded.value = false+ templatesError.value = ''+ wizardStep.value = 0+}++function selectBackend(value: string) {+ if (backend.value === value) return+ backend.value = value+ if (value === 'docker' && !docker.image) {+ docker.image = 'wechatopenai/weknora-sandbox:latest'+ }+ onBackendChange()}watch(() => props.visible, (open) => {- if (open) reset()+ if (open) {+ reset()+ } else {+ stopTemplatePolling()+ }})+function connectionReady(): boolean {+ if (!isRemoteBackend.value) return true+ const required = backend.value === 'cube'+ ? ['api_url', 'proxy_url', 'sandbox_domain']+ : ['api_key']+ const values = submittedBackendValues()+ const errors: Record<string, string> = {}+ for (const field of required) {+ if (typeof values[field] !== 'string' || String(values[field]).trim() === '') {+ errors[field] = t('settings.sandbox.fieldRequired')+ }+ }+ fieldErrors.value = { ...fieldErrors.value, ...errors }+ return Object.keys(errors).length === 0+}++function selectTemplate(value: string | number) {+ if (backend.value === 'cube') cube.template_id = String(value)+ else e2b.template_id = String(value)+ onFieldInput('template_id')+}++function clearTemplateSelection() {+ if (backend.value === 'cube') cube.template_id = ''+ if (backend.value === 'e2b') e2b.template_id = ''+ delete fieldErrors.value.template_id+}++function templateMeta(item: SandboxTemplate): string {+ return [item.status, item.version, item.id].filter(Boolean).join(' · ')+}++function isTemplateSelectable(item: SandboxTemplate): boolean {+ const status = item.status?.trim().toLowerCase()+ if (!status) return true+ return ['ready', 'available', 'complete', 'completed', 'success', 'succeeded'].includes(status)+}++function isTemplatePending(item: SandboxTemplate): boolean {+ const status = item.status?.trim().toLowerCase()+ return ['building', 'waiting', 'pending', 'queued', 'processing'].includes(status || '')+}++// The backend reports this when a template's builds finished without the tag+// sandbox creation resolves, so it can never be spawned as it stands.+function isTemplateUntagged(item: SandboxTemplate): boolean {+ return item.status?.trim().toLowerCase() === 'untagged'+}++function templateStatusTheme(item: SandboxTemplate): 'success' | 'warning' | 'danger' | 'default' {+ if (isTemplateSelectable(item)) return 'success'+ if (isTemplateUntagged(item)) return 'danger'+ if (isTemplatePending(item)) return 'warning'+ const status = item.status?.trim().toLowerCase()+ if (['failed', 'failure', 'error', 'cancelled', 'canceled'].includes(status || '')) return 'danger'+ return 'default'+}++function templateStatusLabel(item: SandboxTemplate): string {+ if (isTemplateSelectable(item)) return t('settings.sandbox.templateStatuses.ready')+ if (isTemplateUntagged(item)) return t('settings.sandbox.templateStatuses.untagged')+ if (isTemplatePending(item)) return t('settings.sandbox.templateStatuses.building')+ const status = item.status?.trim().toLowerCase()+ if (['failed', 'failure', 'error', 'cancelled', 'canceled'].includes(status || '')) {+ return t('settings.sandbox.templateStatuses.failed')+ }+ return t('settings.sandbox.templateStatuses.unknown')+}++function stopTemplatePolling() {+ if (templatePollTimer) clearTimeout(templatePollTimer)+ templatePollTimer = undefined+}++function scheduleTemplatePolling() {+ stopTemplatePolling()+ if (!props.visible || currentStepKey.value !== 'template' || !hasPendingTemplates.value) return+ templatePollTimer = setTimeout(() => {+ void loadTemplates(false, true)+ }, 3000)+}++async function loadTemplates(ensureStandard: boolean, silent = false): Promise<boolean> {+ if (!isRemoteBackend.value) return true+ if (!connectionReady()) return false+ if (!silent) templatesLoading.value = true+ templatesError.value = ''+ try {+ const res = await querySandboxTemplates({+ config: collectPayload(),+ config_id: props.record?.id,+ ensure_standard: ensureStandard,+ })+ templates.value = res.data?.templates || []+ templatesLoaded.value = true+ const standardID = res.data?.standard_template_id+ const current = templates.value.find((item) => item.id === currentTemplateId.value)+ if (currentTemplateId.value && (!current || !isTemplateSelectable(current))) clearTemplateSelection()+ const readyStandard = templates.value.find((item) => item.id === standardID && isTemplateSelectable(item))+ || templates.value.find((item) => item.standard && isTemplateSelectable(item))+ if (!currentTemplateId.value && readyStandard) selectTemplate(readyStandard.id)+ if (res.data?.provisioned && !silent) {+ MessagePlugin.info(t('settings.sandbox.standardTemplateProvisioning'))+ }+ scheduleTemplatePolling()+ return true+ } catch (e: any) {+ templatesError.value = e?.message || t('settings.sandbox.templateLoadFailed')+ return false+ } finally {+ if (!silent) templatesLoading.value = false+ }+}++// Re-attaches the redaction placeholder to a secret the admin left untouched:+// the server reads it as "preserve the stored value".+function withStoredSecret<T extends { api_key?: string }>(block: T, stored: boolean): T {+ if (stored && !block.api_key?.trim()) block.api_key = secretPlaceholder+ return block+}+function collectPayload(): SandboxConfig {const envVars: Record<string, string> = {}for (const row of envRows.value) {const key = row.key.trim()- if (key) envVars[key] = row.value+ if (!key) continue+ envVars[key] = row.stored && row.value === '' ? secretPlaceholder : row.value}const payload: SandboxConfig = {sandbox_type: backend.value,default_timeout_sec: defaultTimeoutSec.value || undefined,+ allow_private_endpoints: allowPrivateEndpoints.value || undefined,env_vars: envVars,}// Send only the selected backend's block so an unused one cannot fail// validation (e.g. a stale private URL left in the other tab).- if (backend.value === 'cube') payload.cube = { ...cube }- if (backend.value === 'e2b') payload.e2b = { ...e2b }+ if (backend.value === 'cube') payload.cube = withStoredSecret({ ...cube }, storedSecrets.cube)+ if (backend.value === 'e2b') payload.e2b = withStoredSecret({ ...e2b }, storedSecrets.e2b)+ if (backend.value === 'docker') payload.docker = { ...docker }return payload}function close() {+ stopTemplatePolling()emit('update:visible', false)}-async function save() {- const trimmed = name.value.trim()- if (!trimmed) {+function validateName(): boolean {+ if (!name.value.trim()) {nameError.value = t('settings.sandbox.configNameRequired')- return+ return false}nameError.value = ''+ return true+}++async function handlePrimaryAction() {+ if (currentStepKey.value === 'connection') {+ if (!validateName() || !validateRequiredFields(false)) return+ if (!(await runCheck(false))) return+ if (isRemoteBackend.value) {+ wizardStep.value += 1+ await loadTemplates(true)+ return+ }+ wizardStep.value += 1+ return+ }+ if (currentStepKey.value === 'template') {+ if (!selectedTemplate.value || !isTemplateSelectable(selectedTemplate.value)) {+ fieldErrors.value.template_id = t('settings.sandbox.templateNotReady')+ return+ }+ stopTemplatePolling()+ wizardStep.value += 1+ return+ }+ await save()+}++function previousStep() {+ if (wizardStep.value <= 0) return+ wizardStep.value -= 1+ if (currentStepKey.value === 'template') scheduleTemplatePolling()+ else stopTemplatePolling()+}++async function save() {+ const trimmed = name.value.trim()+ if (!validateName()) returnif (!validateRequiredFields()) return+ if (isRemoteBackend.value && selectedTemplate.value && !isTemplateSelectable(selectedTemplate.value)) {+ fieldErrors.value.template_id = t('settings.sandbox.templateNotReady')+ return+ }saving.value = trueconflict.value = nulltry {@@ -369,10 +858,10 @@ async function save() {}}-async function runCheck(deep: boolean) {+async function runCheck(deep: boolean): Promise<boolean> {// The probe builds a real client, so an incomplete config would come back as// a generic client_build failure instead of naming the empty field.- if (!validateRequiredFields()) return+ if (!validateRequiredFields(deep)) return falsechecking.value = truecheckResult.value = nulltry {@@ -384,12 +873,15 @@ async function runCheck(deep: boolean) {deep,})checkResult.value = res?.data || null+ lastCheckWasDeep.value = deepif (checkResult.value) {await nextTick()checkResultRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })}+ return checkResult.value?.ok === true} catch (e: any) {MessagePlugin.error(e?.message || t('settings.sandbox.checkFailed'))+ return false} finally {checking.value = false}@@ -400,58 +892,588 @@ function invalidateCheck() {checkResult.value = null}+function invalidateConnection() {+ stopTemplatePolling()+ invalidateCheck()+ templates.value = []+ templatesLoaded.value = false+ templatesError.value = ''+ clearTemplateSelection()+}+// The two backends require different fields, so carrying errors across a switch// would flag inputs the admin can no longer even see.function onBackendChange() {fieldErrors.value = {}- invalidateCheck()+ invalidateConnection()}++onUnmounted(stopTemplatePolling)</script>-<style scoped>+<style lang="less" scoped>+/*+ A step rail rather than segmented buttons: the connector line carries the+ "these run in order" meaning that boxed segments only implied, and the flat+ background keeps the drawer's first visual weight on the form itself.+*/+.sandbox-steps {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0 0 18px;+}++.sandbox-step {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ color: var(--td-text-color-placeholder);+ transition: color 0.15s ease;++ /* Only the steps that draw a connector need to absorb the leftover width. */+ &:not(:last-child) {+ flex: 1;+ }++ &.is-active {+ color: var(--td-brand-color);+ }++ &.is-done {+ color: var(--td-text-color-secondary);+ }+}++.sandbox-step__marker {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ flex-shrink: 0;+ border: 1px solid currentColor;+ border-radius: 50%;+ font-size: 11px;+ font-weight: 600;+ line-height: 1;++ .is-active & {+ background: var(--td-brand-color);+ border-color: var(--td-brand-color);+ color: #fff;+ }++ .is-done & {+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);+ border-color: color-mix(in srgb, var(--td-brand-color) 35%, transparent);+ color: var(--td-brand-color);+ }+}++.sandbox-step__title {+ overflow: hidden;+ font-size: 13px;+ font-weight: 500;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.sandbox-step__line {+ flex: 1;+ min-width: 16px;+ height: 1px;+ margin: 0 4px;+ background: var(--td-component-stroke);++ .is-done & {+ background: color-mix(in srgb, var(--td-brand-color) 35%, transparent);+ }+}++.sandbox-editor-form {+ :deep(.t-form__item) {+ margin-bottom: 0;+ }++ /*+ Form items here stack a control with its own hint text and doc link, so the+ controls area has to be a block instead of TDesign's default single row.+ */+ :deep(.t-form__controls-content) {+ display: block;+ }++ :deep(.t-form__label) {+ padding-bottom: 6px;+ font-size: 13px;+ font-weight: 500;+ line-height: 1.4;+ }++ :deep(.t-input),+ :deep(.t-input-number),+ :deep(.t-select) {+ width: 100%;+ font-size: 13px;+ }+}+.identity-hint {- margin-bottom: 16px;+ margin: 0;+}++.compact-alert {+ padding: 9px 11px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 7px;+ background: var(--td-bg-color-secondarycontainer);++ :deep(.t-alert__icon) {+ font-size: 15px;+ }++ :deep(.t-alert__message) {+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;+ }}-.timeout-row {+.private-endpoint-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 10px 12px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 6px;+ background: var(--td-bg-color-secondarycontainer);+}++.private-endpoint-row__title {+ margin: 0 0 3px;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+}++.form-grid {display: grid;- grid-template-columns: repeat(3, minmax(0, 1fr));gap: 12px;- margin-bottom: 24px;++ &--two {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}++.backend-choice {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 2px 0;+}++.backend-choice__text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.backend-choice__name {+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 500;+ line-height: 1.4;+}++.backend-choice__desc {+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.45;+ white-space: normal;+}++.section-title-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;++ .setting-drawer__section-title {+ margin-bottom: 0;+ }+}++.connection-summary {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 10px 12px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);+}++.connection-summary__icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ flex-shrink: 0;+ border-radius: 50%;+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);+ color: var(--td-brand-color);+ font-size: 13px;+}++.connection-summary__title,+.connection-summary__text {+ margin: 0;+}++.connection-summary__title {+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+ line-height: 1.45;+}++.connection-summary__text {+ margin-top: 2px;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;+}++.weknora-template-card {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 12px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);++ &.is-active {+ border-color: color-mix(in srgb, var(--td-brand-color) 45%, var(--td-component-stroke));+ background: color-mix(in srgb, var(--td-brand-color) 5%, var(--td-bg-color-container));+ }+}++.weknora-template-card__content {+ flex: 1;+ min-width: 0;++ p {+ margin: 4px 0 0;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;+ }+}++.weknora-template-card__title-row {+ display: flex;+ align-items: center;+ gap: 8px;+}++.weknora-template-card__title {+ font-size: 13px;+ font-weight: 600;+}++.template-loading {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ width: 100%;+ min-height: 88px;+ border: 1px dashed var(--td-component-stroke);+ border-radius: 8px;+ color: var(--td-text-color-secondary);+ font-size: 12px;+}++.template-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.template-card {+ display: flex;+ align-items: center;+ gap: 12px;+ width: 100%;+ min-height: 72px;+ padding: 12px 14px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 10px;+ background: var(--td-bg-color-container);+ color: var(--td-text-color-primary);+ cursor: pointer;+ text-align: left;+ transition: border-color 0.18s ease, background-color 0.18s ease, box-shadow 0.18s ease;++ &:hover:not(:disabled) {+ border-color: var(--td-brand-color-3, var(--td-brand-color));+ box-shadow: 0 3px 10px rgba(15, 23, 42, 0.05);+ }++ &.is-active {+ border-color: var(--td-brand-color);+ background: color-mix(in srgb, var(--td-brand-color) 4%, var(--td-bg-color-container));+ }++ &:disabled {+ cursor: not-allowed;+ }++ &.is-pending {+ background: color-mix(in srgb, var(--td-warning-color) 3%, var(--td-bg-color-container));+ }+}++.template-card__badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 36px;+ height: 36px;+ flex-shrink: 0;+ border-radius: 9px;+ background: rgba(0, 82, 217, 0.1);+ color: #0052d9;+ font-size: 16px;++ .is-pending & {+ background: color-mix(in srgb, var(--td-warning-color) 12%, transparent);+ color: var(--td-warning-color);+ }+}++.template-card__body {+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 5px;+ min-width: 0;+}++.template-card__title-row {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+}++.template-card__title {+ overflow: hidden;+ font-size: 13px;+ font-weight: 600;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.template-card__meta,+.template-card__hint {+ overflow-wrap: anywhere;+ color: var(--td-text-color-placeholder);+ font-size: 11px;+ line-height: 1.45;+}++.template-card__hint {+ color: var(--td-warning-color);++ &--error {+ color: var(--td-error-color);+ }+}++.template-card__state {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+ align-self: flex-start;+ padding-top: 1px;+}++.template-card__selected {+ color: var(--td-brand-color);+ font-size: 17px;+}++.template-state-note {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 9px 11px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 7px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;++ > .t-icon {+ flex-shrink: 0;+ color: var(--td-warning-color);+ font-size: 15px;+ }++ &--ready > .t-icon {+ color: var(--td-brand-color);+ }+}++.field-hints {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 4px;+ margin-top: 6px;++ .inline-guide-link {+ margin-top: 0;+ }}-.timeout-row :deep(.t-form__item) {+.inline-guide-link {+ display: inline-flex;+ align-items: center;+ align-self: flex-start;+ gap: 5px;+ margin-top: -4px;+ color: var(--td-brand-color);+ font-size: 12px;+ text-decoration: none;++ &:hover {+ color: var(--td-brand-color-hover);+ }+}++.runtime-fields {+ display: flex;+ flex-direction: column;+}++.runtime-fields :deep(.t-form__item) {margin-bottom: 0;}-.timeout-row :deep(.t-input-number) {+.runtime-fields :deep(.t-input-number) {width: 100%;+ max-width: 240px;+}++.runtime-fields .section-help--field {+ margin-bottom: 16px;++ &:last-child {+ margin-bottom: 0;+ }}.env-rows {display: flex;flex-direction: column;gap: 8px;- align-items: flex-start;}.env-row {- display: flex;+ display: grid;+ grid-template-columns: minmax(140px, 0.7fr) minmax(200px, 1.3fr) 32px;align-items: center;gap: 8px;+ width: 100%;}-.check-actions {- display: flex;- gap: 12px;- margin-top: 4px;+.env-empty {+ padding: 18px;+ border: 1px dashed var(--td-component-stroke);+ border-radius: 8px;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ text-align: center;+}++.section-help {+ margin: 0;+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ line-height: 1.5;++ &--under-title {+ margin-top: 5px;+ max-width: 470px;+ }++ /* Sits under an input inside the same form item. */+ &--field {+ margin-top: 6px;+ }}.check-result {- margin-top: 16px;+ margin-top: 12px;+ padding-top: 14px;+ border-top: 1px solid var(--td-component-stroke);display: flex;flex-direction: column;- gap: 12px;+ gap: 10px;+}++.check-result__summary {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ padding: 10px 12px;+ border: 1px solid var(--td-component-stroke);+ border-radius: 8px;+ background: var(--td-bg-color-secondarycontainer);++ &.is-success .check-result__summary-icon {+ color: var(--td-brand-color);+ }++ &.is-error .check-result__summary-icon {+ color: var(--td-error-color);+ }+}++.check-result__summary-icon {+ flex-shrink: 0;+ padding-top: 1px;+ font-size: 17px;+}++.check-result__title,+.check-result__subtitle {+ margin: 0;+}++.check-result__title {+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+ line-height: 1.45;+}++.check-result__subtitle {+ margin-top: 2px;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;}.check-list {@@ -467,7 +1489,9 @@ function onBackendChange() {display: flex;align-items: center;gap: 8px;- font-size: 13px;+ flex-wrap: wrap;+ padding: 2px 0;+ font-size: 12px;}.check-item .ok {@@ -491,6 +1515,37 @@ function onBackendChange() {color: var(--td-text-color-secondary);}+.check-pending {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 12px;+ padding: 10px 12px;+ border: 1px dashed var(--td-component-stroke);+ border-radius: 8px;+}++.check-pending--standalone {+ margin-top: 16px;+}++.check-pending__text {+ flex: 1;+ min-width: 0;+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.55;+}++.footer-check-ok {+ color: var(--td-success-color);+}++.footer-check-error {+ color: var(--td-error-color);+}+.blocked {margin-top: 16px;}@@ -503,4 +1558,32 @@ function onBackendChange() {.blocked p {margin: 4px 0 0;}++@media (max-width: 720px) {+ .form-grid--two,+ .weknora-template-card {+ align-items: flex-start;+ flex-wrap: wrap;+ }++ .sandbox-step__title {+ font-size: 12px;+ }+}+</style>++<!--+ The select popup is attached to body, outside the scoped style boundary, so+ the two-line backend options need their row height relaxed globally. The+ overlay class keeps it from touching any other select in the app.+-->+<style lang="less">+.sandbox-backend-popup {+ .t-select-option {+ height: auto;+ min-height: 44px;+ padding: 6px 8px;+ line-height: 1.4;+ }+}</style>diff --git a/frontend/src/components/settings/SandboxBackendBadge.vue b/frontend/src/components/settings/SandboxBackendBadge.vuenew file mode 100644index 000000000..ff507cc6e--- /dev/null+++ b/frontend/src/components/settings/SandboxBackendBadge.vue@@ -0,0 +1,99 @@+<template>+ <span class="sandbox-badge" :class="badgeClass" :style="badgeStyle" :aria-hidden="true">+ <t-icon v-if="!logo" :name="iconName" />+ </span>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { providerLogo } from '@/views/settings/providerLogos'++// The sandbox list and the config drawer must show the same mark for a backend,+// so both render this badge instead of each mapping types to icons themselves.+// Vendors we ship a logo for (Docker) win over the generic TDesign glyphs.+const props = withDefaults(defineProps<{+ type: string+ size?: 'sm' | 'md'+}>(), { size: 'md' })++const logo = computed(() => providerLogo('sandbox', props.type))++const iconName = computed(() => {+ if (props.type === 'cube' || props.type === 'local') return 'server'+ if (props.type === 'disabled') return 'minus-circle'+ return 'cloud'+})++const badgeClass = computed(() => [+ `sandbox-badge--${props.type}`,+ `sandbox-badge--${props.size}`,+ { 'sandbox-badge--mono': logo.value?.mode === 'mono' },+])++const badgeStyle = computed((): Record<string, string> => (+ logo.value?.mode === 'mono' ? { '--logo-url': `url("${logo.value.url}")` } : {}+))+</script>++<style lang="less" scoped>+.sandbox-badge {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ border-radius: 9px;+ background: rgba(0, 82, 217, 0.1);+ color: #0052d9;+}++.sandbox-badge--md {+ width: 36px;+ height: 36px;+ font-size: 17px;+}++.sandbox-badge--sm {+ width: 26px;+ height: 26px;+ border-radius: 7px;+ font-size: 14px;+}++.sandbox-badge--e2b {+ background: rgba(98, 53, 187, 0.1);+ color: #6235bb;+}++.sandbox-badge--docker {+ background: rgba(29, 99, 237, 0.1);+ color: #1d63ed;+}++.sandbox-badge--local {+ background: rgba(17, 128, 83, 0.1);+ color: #118053;+}++.sandbox-badge--mono::before {+ content: '';+ background-color: currentColor;+ -webkit-mask-image: var(--logo-url);+ -webkit-mask-position: center;+ -webkit-mask-repeat: no-repeat;+ -webkit-mask-size: contain;+ mask-image: var(--logo-url);+ mask-position: center;+ mask-repeat: no-repeat;+ mask-size: contain;+}++.sandbox-badge--md.sandbox-badge--mono::before {+ width: 22px;+ height: 22px;+}++.sandbox-badge--sm.sandbox-badge--mono::before {+ width: 16px;+ height: 16px;+}+</style>diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex dfbbbefa6..b8e3a5d5b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1017,10 +1017,10 @@ export default {sandboxConfig: 'Sandbox backend',sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',sandboxBackend: 'Sandbox backend',- sandboxBackendDefault: 'Use deployment defaults',+ sandboxBackendDefault: 'Disable sandbox',sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',sandboxBackendMissing: 'Config deleted',- sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',+ sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. Add one under Settings - Sandbox Backend.',sandboxInfoTitle: 'Why choose a backend?',sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',skillsInfoTitle: 'What are Skills?',@@ -1055,18 +1055,34 @@ export default {storageEngine: 'Storage Engine',sandbox: {title: 'Sandbox Backend',- description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',+ description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',+ editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ stepConnection: 'Connect',+ stepTemplate: 'Template',+ stepRuntime: 'Runtime',+ setupProgress: 'Sandbox setup progress',+ stepDescriptions: {+ connection: 'Configure the backend and verify the connection before loading templates.',+ template: 'Choose a ready template returned by the connected cluster.',+ runtime: 'Configure execution settings and environment variables, then save.',+ },+ back: 'Back',+ connectAndContinue: 'Connect and continue',loading: 'Loading sandbox configuration...',loadFailed: 'Failed to load sandbox configuration',backend: 'Sandbox backend',- backendHint: 'Leave unset to inherit the global default',+ backendType: 'Sandbox type',+ backendTypePlaceholder: 'Select a sandbox type',+ scriptPolicyLabel: 'Allow skill scripts to run in sandboxes',+ scriptPolicyDesc: 'When off, agents in this workspace can only read skill content. Remote sandboxes already running are released once their sessions end.',+ backendDescriptions: {+ cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',+ e2b: 'Managed MicroVM service or an E2B-compatible deployment',+ docker: 'Run every script in a short-lived container on this WeKnora host',+ local: 'Run scripts directly in the WeKnora server process environment',+ },addConfig: 'Add sandbox backend',- viewDeployDefaults: 'View deployment defaults',- deployDefaultsTitle: 'Deployment defaults',- deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',- deployDefaultBackend: 'Default backend',- apiKeyConfigured: 'Configured',- apiKeyNotConfigured: 'Not configured',+ viewClusterGuide: 'Cluster setup guide',configName: 'Config name',configNamePlaceholder: 'e.g. Production E2B',configNameRequired: 'Please enter a config name',@@ -1074,10 +1090,17 @@ export default {configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',createTitle: 'Add sandbox backend',editTitle: 'Edit sandbox backend',- noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',+ sectionBasic: 'Basic information',+ sectionConnection: 'Cluster connection',+ sectionRuntimeEnvironment: 'Runtime environment',+ sectionTemplate: 'Runtime template',+ sectionRuntime: 'Execution settings',+ sectionEnvironment: 'Environment variables',+ noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',viewSandboxes: 'View sandbox usage',inventoryTitle: 'Sandbox usage',+ inventoryDrawerDesc: 'Sandboxes this config still holds, plus the sessions and agents affected.',inventoryFailed: 'Failed to load sandbox usage',sandboxCount: 'Sandboxes',sandboxCountUnknown: 'Unknown (backend unreachable)',@@ -1103,9 +1126,60 @@ export default {scriptsEnabled: 'Sandbox execution restored for this workspace',policySaveFailed: 'Failed to update sandbox execution policy',legacyConfig: 'Deprecated',- namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',+ namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',+ weknoraTemplateTitle: 'WeKnora standard template',+ weknoraDockerImage: 'WeKnora standard image',+ weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',+ weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',+ weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',+ recommendedTag: 'Recommended',+ cardTemplateConfigured: 'Template configured',+ cardCredentialMissing: 'API key missing',+ cardTimeout: 'Timeout {sec}s',+ cardTtl: 'Sandbox TTL {sec}s',+ cardVolumeMounted: 'Volume mounted',+ cardEnvVars: '{count} env vars',+ cardPrivateEndpoints: 'Private endpoints allowed',+ templateNotConfigured: 'Template not configured',+ imageNotConfigured: 'Image not configured',+ localRuntimeSummary: 'WeKnora server process',+ templateApplied: 'Applied',+ refreshTemplates: 'Refresh templates',+ templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',+ templateSelectPlaceholder: 'Connect to the cluster to load templates',+ templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',+ templateLoadFailed: 'Failed to load templates',+ standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',+ templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',+ connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',+ connectionPassedTitle: 'Cluster connected',+ templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',+ loadingTemplates: 'Loading templates from the cluster...',+ templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',+ templateUntaggedHint: 'The builds finished but none carries the default tag, so sandbox creation cannot resolve this template. Delete it in E2B and refresh; WeKnora will rebuild it.',+ noTemplates: 'No templates were returned by this cluster.',+ templateReadyHint: 'Template “{name}” is ready and selected.',+ templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',+ templateStatuses: {+ ready: 'Ready',+ building: 'Building',+ untagged: 'No default tag',+ failed: 'Failed',+ unknown: 'Unknown',+ },+ allowPrivateEndpoints: 'Allow private cluster endpoints',+ allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',+ howToBuildTemplate: 'Sandbox cluster setup and template guide',+ noEnvVars: 'No additional environment variables. Add only values required by skills.',fieldRequired: 'Required',cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',+ cubeApiKeyWhere: 'How to enable auth on a self-hosted cluster',+ e2bApiKeyHelp: 'Create one on the API Keys page of the E2B dashboard; it usually starts with e2b_.',+ e2bApiKeyWhere: 'Get an API key from the E2B dashboard',+ apiKeyPlaceholder: 'Paste the API key',+ secretConfigured: 'Key configured (not shown again); enter a new value to rotate',+ secretKeepHint: 'Configured — leave empty to keep it',e2bApiUrlOptional: 'Optional — the SDK default is used when empty',e2bDomainOptional: 'Optional — the SDK default is used when empty',backends: {@@ -1121,9 +1195,12 @@ export default {apiKey: 'API key',templateId: 'Template ID',httpTimeout: 'HTTP timeout (s)',+ httpTimeoutHelp: 'How long a management call to the backend may take before the endpoint counts as unreachable. Empty means 30 seconds.',sandboxTtl: 'Sandbox TTL (s)',+ sandboxTtlHelp: 'How long an idle sandbox survives before the provider reclaims it. Too short and a resumed session has to rebuild it; too long and idle instances keep billing. Empty means the backend default.',dockerImage: 'Docker image',defaultTimeout: 'Execution timeout (s)',+ defaultTimeoutHelp: 'Longest a single skill script may run before it is killed. Empty means 60 seconds.',envVars: 'Environment variables',envKey: 'Name',envValue: 'Value',@@ -1135,11 +1212,24 @@ export default {saveFailed: 'Failed to save',testConnection: 'Test connection',deepCheck: 'Full verification',- deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',+ recheck: 'Verify again',+ deepCheckIntro: 'Before saving you can run a full verification: it creates a throwaway sandbox, runs one script, checks outbound access and destroys it.',+ deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',checkPassed: 'All checks passed',checkFailed: 'Some checks failed',+ checkScopeConnection: 'Only the control plane was verified: the endpoint responds and the credential is valid. Whether a script actually runs is still unverified.',+ checkScopeFull: 'Endpoint, credential, template, in-sandbox execution and outbound network were all verified for real.',+ checkPendingHint: '{names} can only be confirmed by a full verification, which creates a throwaway sandbox, runs one script and destroys it.',noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',+ skipReasons: {+ needs_deep_check: 'Needs full verification',+ control_plane_unreachable: 'Skipped: control plane unreachable',+ environment_unavailable: 'Skipped: runtime unavailable',+ sandbox_not_created: 'Skipped: sandbox was not created',+ sandbox_exec_failed: 'Skipped: in-sandbox execution failed',+ },checks: {+ environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 2ce5bc4dd..a6a0a93ec 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -4655,18 +4655,34 @@ export default {storageEngine: '스토리지 엔진',sandbox: {title: 'Sandbox Backend',- description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',+ description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',+ editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ stepConnection: 'Connect',+ stepTemplate: 'Template',+ stepRuntime: 'Runtime',+ setupProgress: 'Sandbox setup progress',+ stepDescriptions: {+ connection: 'Configure the backend and verify the connection before loading templates.',+ template: 'Choose a ready template returned by the connected cluster.',+ runtime: 'Configure execution settings and environment variables, then save.',+ },+ back: 'Back',+ connectAndContinue: 'Connect and continue',loading: 'Loading sandbox configuration...',loadFailed: 'Failed to load sandbox configuration',backend: 'Sandbox backend',- backendHint: 'Leave unset to inherit the global default',+ backendType: '샌드박스 유형',+ backendTypePlaceholder: '샌드박스 유형 선택',+ scriptPolicyLabel: '샌드박스에서 스킬 스크립트 실행 허용',+ scriptPolicyDesc: '끄면 이 워크스페이스의 에이전트는 스킬 내용만 읽을 수 있습니다. 이미 실행 중인 원격 샌드박스는 해당 세션이 종료된 후 해제됩니다.',+ backendDescriptions: {+ cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',+ e2b: 'Managed MicroVM service or an E2B-compatible deployment',+ docker: 'Run every script in a short-lived container on this WeKnora host',+ local: 'Run scripts directly in the WeKnora server process environment',+ },addConfig: 'Add sandbox backend',- viewDeployDefaults: 'View deployment defaults',- deployDefaultsTitle: 'Deployment defaults',- deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',- deployDefaultBackend: 'Default backend',- apiKeyConfigured: 'Configured',- apiKeyNotConfigured: 'Not configured',+ viewClusterGuide: 'Cluster setup guide',configName: 'Config name',configNamePlaceholder: 'e.g. Production E2B',configNameRequired: 'Please enter a config name',@@ -4674,10 +4690,17 @@ export default {configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',createTitle: 'Add sandbox backend',editTitle: 'Edit sandbox backend',- noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',+ sectionBasic: 'Basic information',+ sectionConnection: 'Cluster connection',+ sectionRuntimeEnvironment: 'Runtime environment',+ sectionTemplate: 'Runtime template',+ sectionRuntime: 'Execution settings',+ sectionEnvironment: 'Environment variables',+ noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',viewSandboxes: 'View sandbox usage',inventoryTitle: 'Sandbox usage',+ inventoryDrawerDesc: '이 설정이 아직 점유한 샌드박스와 영향을 받는 세션·에이전트입니다.',inventoryFailed: 'Failed to load sandbox usage',sandboxCount: 'Sandboxes',sandboxCountUnknown: 'Unknown (backend unreachable)',@@ -4703,9 +4726,60 @@ export default {scriptsEnabled: 'Sandbox execution restored for this workspace',policySaveFailed: 'Failed to update sandbox execution policy',legacyConfig: 'Deprecated',- namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',+ namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',+ weknoraTemplateTitle: 'WeKnora standard template',+ weknoraDockerImage: 'WeKnora standard image',+ weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',+ weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',+ weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',+ recommendedTag: 'Recommended',+ templateNotConfigured: 'Template not configured',+ cardTemplateConfigured: '템플릿 설정됨',+ cardCredentialMissing: 'API 키 없음',+ cardTimeout: '타임아웃 {sec}초',+ cardTtl: '샌드박스 유지 {sec}초',+ cardVolumeMounted: '볼륨 마운트됨',+ cardEnvVars: '환경 변수 {count}개',+ cardPrivateEndpoints: '사설망 접근 허용',+ imageNotConfigured: 'Image not configured',+ localRuntimeSummary: 'WeKnora server process',+ templateApplied: 'Applied',+ refreshTemplates: 'Refresh templates',+ templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',+ templateSelectPlaceholder: 'Connect to the cluster to load templates',+ templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',+ templateLoadFailed: 'Failed to load templates',+ standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',+ templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',+ connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',+ connectionPassedTitle: 'Cluster connected',+ templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',+ loadingTemplates: 'Loading templates from the cluster...',+ templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',+ templateUntaggedHint: '빌드는 끝났지만 default 태그가 붙은 빌드가 없어 샌드박스 생성 시 이 템플릿을 찾을 수 없습니다. E2B에서 템플릿을 삭제하고 새로고침하면 WeKnora가 다시 빌드합니다.',+ noTemplates: 'No templates were returned by this cluster.',+ templateReadyHint: 'Template “{name}” is ready and selected.',+ templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',+ templateStatuses: {+ ready: 'Ready',+ building: 'Building',+ untagged: 'default 태그 없음',+ failed: 'Failed',+ unknown: 'Unknown',+ },+ allowPrivateEndpoints: 'Allow private cluster endpoints',+ allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',+ howToBuildTemplate: 'Sandbox cluster setup and template guide',+ noEnvVars: 'No additional environment variables. Add only values required by skills.',fieldRequired: 'Required',cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',+ cubeApiKeyWhere: '자체 호스팅 클러스터에서 인증을 켜는 방법',+ e2bApiKeyHelp: 'E2B 대시보드의 API Keys 페이지에서 생성하며 보통 e2b_ 로 시작합니다.',+ e2bApiKeyWhere: 'E2B 대시보드에서 API 키 발급받기',+ apiKeyPlaceholder: 'API 키를 붙여넣으세요',+ secretConfigured: '키가 설정되어 있습니다(다시 표시되지 않음). 새 값을 입력하면 교체됩니다',+ secretKeepHint: '설정됨 — 비워 두면 변경되지 않습니다',e2bApiUrlOptional: 'Optional — the SDK default is used when empty',e2bDomainOptional: 'Optional — the SDK default is used when empty',backends: {@@ -4721,9 +4795,12 @@ export default {apiKey: 'API key',templateId: 'Template ID',httpTimeout: 'HTTP timeout (s)',+ httpTimeoutHelp: '백엔드 관리 API 호출을 기다리는 상한입니다. 초과하면 엔드포인트를 사용할 수 없는 것으로 간주합니다. 비워 두면 30초입니다.',sandboxTtl: 'Sandbox TTL (s)',+ sandboxTtlHelp: '유휴 샌드박스가 회수되기까지의 시간입니다. 너무 짧으면 세션을 이어갈 때 다시 만들어야 하고, 너무 길면 유휴 인스턴스에 계속 요금이 발생합니다. 비워 두면 백엔드 기본값을 사용합니다.',dockerImage: 'Docker image',defaultTimeout: 'Execution timeout (s)',+ defaultTimeoutHelp: '스킬 스크립트 한 번이 실행될 수 있는 최대 시간이며, 초과하면 강제 종료됩니다. 비워 두면 60초입니다.',envVars: 'Environment variables',envKey: 'Name',envValue: 'Value',@@ -4735,11 +4812,24 @@ export default {saveFailed: 'Failed to save',testConnection: 'Test connection',deepCheck: 'Full verification',- deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',+ recheck: '다시 검증',+ deepCheckIntro: '저장하기 전에 전체 검증을 한 번 실행할 수 있습니다. 임시 샌드박스를 만들어 스크립트를 실행하고 외부 통신까지 확인한 뒤 삭제합니다.',+ deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',checkPassed: 'All checks passed',checkFailed: 'Some checks failed',+ checkScopeConnection: '이번에는 컨트롤 플레인만 확인했습니다. 엔드포인트는 응답하고 자격 증명도 유효하지만, 스크립트가 실제로 실행되는지는 아직 확인되지 않았습니다.',+ checkScopeFull: '엔드포인트, 자격 증명, 템플릿, 샌드박스 내 실행, 외부 통신까지 모두 실제로 검증했습니다.',+ checkPendingHint: '{names}은(는) 전체 검증으로만 확인할 수 있습니다. 임시 샌드박스를 실제로 만들어 스크립트를 한 번 실행한 뒤 삭제합니다.',+ skipReasons: {+ needs_deep_check: '전체 검증 필요',+ control_plane_unreachable: '컨트롤 플레인에 연결할 수 없어 건너뜀',+ environment_unavailable: '실행 환경을 사용할 수 없어 건너뜀',+ sandbox_not_created: '샌드박스가 생성되지 않아 건너뜀',+ sandbox_exec_failed: '샌드박스 내 실행 실패로 건너뜀',+ },noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',checks: {+ environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',@@ -5145,10 +5235,10 @@ export default {sandboxConfig: 'Sandbox backend',sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',sandboxBackend: 'Sandbox backend',- sandboxBackendDefault: 'Use deployment defaults',+ sandboxBackendDefault: 'Disable sandbox',sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',sandboxBackendMissing: 'Config deleted',- sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',+ sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. Add one under Settings - Sandbox Backend.',sandboxInfoTitle: 'Why choose a backend?',sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',skillsInfoTitle: 'Skills란 무엇인가요?',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex eab495223..8f521d28e 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -4655,18 +4655,34 @@ export default {storageEngine: 'Движок хранения',sandbox: {title: 'Sandbox Backend',- description: 'Configure several sandbox backends for this workspace; each agent picks the one it runs on. Fields left empty inherit the global defaults from .env.',+ description: 'Manage the sandbox runtimes used by agent skills. Each agent can select one workspace backend.',+ editorDescription: 'Configure a workspace runtime. Docker, Local process, CubeSandbox, and E2B use the same management flow.',+ stepConnection: 'Connect',+ stepTemplate: 'Template',+ stepRuntime: 'Runtime',+ setupProgress: 'Sandbox setup progress',+ stepDescriptions: {+ connection: 'Configure the backend and verify the connection before loading templates.',+ template: 'Choose a ready template returned by the connected cluster.',+ runtime: 'Configure execution settings and environment variables, then save.',+ },+ back: 'Back',+ connectAndContinue: 'Connect and continue',loading: 'Loading sandbox configuration...',loadFailed: 'Failed to load sandbox configuration',backend: 'Sandbox backend',- backendHint: 'Leave unset to inherit the global default',+ backendType: 'Тип песочницы',+ backendTypePlaceholder: 'Выберите тип песочницы',+ scriptPolicyLabel: 'Разрешить выполнение скриптов навыков в песочницах',+ scriptPolicyDesc: 'Если выключено, агенты этого пространства смогут только читать содержимое навыков. Уже запущенные удалённые песочницы освободятся после завершения их сессий.',+ backendDescriptions: {+ cube: 'Self-hosted MicroVM cluster for private or on-premises deployments',+ e2b: 'Managed MicroVM service or an E2B-compatible deployment',+ docker: 'Run every script in a short-lived container on this WeKnora host',+ local: 'Run scripts directly in the WeKnora server process environment',+ },addConfig: 'Add sandbox backend',- viewDeployDefaults: 'View deployment defaults',- deployDefaultsTitle: 'Deployment defaults',- deployDefaultsHint: 'The global configuration from .env. Fields left empty in a config inherit these values.',- deployDefaultBackend: 'Default backend',- apiKeyConfigured: 'Configured',- apiKeyNotConfigured: 'Not configured',+ viewClusterGuide: 'Cluster setup guide',configName: 'Config name',configNamePlaceholder: 'e.g. Production E2B',configNameRequired: 'Please enter a config name',@@ -4674,10 +4690,17 @@ export default {configDescriptionPlaceholder: 'Optional, helps tell several configs of the same type apart',createTitle: 'Add sandbox backend',editTitle: 'Edit sandbox backend',- noConfigs: 'No sandbox backend yet. Agents run their skill scripts on the deployment defaults.',+ sectionBasic: 'Basic information',+ sectionConnection: 'Cluster connection',+ sectionRuntimeEnvironment: 'Runtime environment',+ sectionTemplate: 'Runtime template',+ sectionRuntime: 'Execution settings',+ sectionEnvironment: 'Environment variables',+ noConfigs: 'No sandbox backend yet. Agents without a workspace configuration will not run skill scripts.',identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',viewSandboxes: 'View sandbox usage',inventoryTitle: 'Sandbox usage',+ inventoryDrawerDesc: 'Песочницы, которые всё ещё занимает эта конфигурация, а также затронутые сессии и агенты.',inventoryFailed: 'Failed to load sandbox usage',sandboxCount: 'Sandboxes',sandboxCountUnknown: 'Unknown (backend unreachable)',@@ -4703,9 +4726,60 @@ export default {scriptsEnabled: 'Sandbox execution restored for this workspace',policySaveFailed: 'Failed to update sandbox execution policy',legacyConfig: 'Deprecated',- namedBackendHint: 'Named configs support CubeSandbox and E2B only. Use WEKNORA_SANDBOX_MODE in deployment settings for Docker or local process.',+ namedBackendHint: 'Workspace configuration is the only runtime source. Agents without one cannot execute skill scripts.',+ weknoraTemplateTitle: 'WeKnora standard template',+ weknoraDockerImage: 'WeKnora standard image',+ weknoraDockerImageHint: 'Each execution starts an isolated, short-lived container from this image. No session sandbox is retained.',+ localRuntimeWarning: 'Local process runs skill scripts directly on the WeKnora server without container or MicroVM isolation. Use only in a trusted development workspace.',+ weknoraTemplateOverview: 'WeKnora provides the standard runtime. Templates are discovered after connecting and the standard one is created when missing.',+ weknoraTemplateDescription: 'Includes the Python, Node.js, CLI tools, workspace path, and non-root execution user expected by WeKnora skills.',+ recommendedTag: 'Recommended',+ templateNotConfigured: 'Template not configured',+ cardTemplateConfigured: 'Шаблон настроен',+ cardCredentialMissing: 'Нет API-ключа',+ cardTimeout: 'Таймаут {sec} с',+ cardTtl: 'Время жизни песочницы {sec} с',+ cardVolumeMounted: 'Том подключён',+ cardEnvVars: 'Переменных окружения: {count}',+ cardPrivateEndpoints: 'Разрешён доступ к частной сети',+ imageNotConfigured: 'Image not configured',+ localRuntimeSummary: 'WeKnora server process',+ templateApplied: 'Applied',+ refreshTemplates: 'Refresh templates',+ templateSelectHelp: 'Templates are loaded from this cluster. The saved configuration stores the ID automatically.',+ templateSelectPlaceholder: 'Connect to the cluster to load templates',+ templateLoadHint: 'Enter the cluster connection and refresh. WeKnora creates its standard template when missing.',+ templateLoadFailed: 'Failed to load templates',+ standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',+ templateNotReady: 'The selected template is not ready. Refresh and wait for the build to finish.',+ connectionPassed: 'Connection verified. Templates below are loaded from this cluster.',+ connectionPassedTitle: 'Cluster connected',+ templateStepHint: 'WeKnora automatically creates its standard template when missing. You can continue after a template is ready.',+ loadingTemplates: 'Loading templates from the cluster...',+ templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',+ templateUntaggedHint: 'Сборки завершены, но ни одна не имеет тега default, поэтому при создании песочницы шаблон не находится. Удалите его в E2B и обновите список — WeKnora пересоберёт шаблон.',+ noTemplates: 'No templates were returned by this cluster.',+ templateReadyHint: 'Template “{name}” is ready and selected.',+ templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',+ templateStatuses: {+ ready: 'Ready',+ building: 'Building',+ untagged: 'Нет тега default',+ failed: 'Failed',+ unknown: 'Unknown',+ },+ allowPrivateEndpoints: 'Allow private cluster endpoints',+ allowPrivateEndpointsHint: 'Use for self-hosted private control planes. Link-local and cloud metadata addresses remain blocked.',+ howToBuildTemplate: 'Sandbox cluster setup and template guide',+ noEnvVars: 'No additional environment variables. Add only values required by skills.',fieldRequired: 'Required',cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',+ cubeApiKeyWhere: 'Как включить аутентификацию в собственном кластере',+ e2bApiKeyHelp: 'Создайте ключ на странице API Keys в консоли E2B; обычно он начинается с e2b_.',+ e2bApiKeyWhere: 'Получить API-ключ в консоли E2B',+ apiKeyPlaceholder: 'Вставьте API-ключ',+ secretConfigured: 'Ключ настроен (повторно не показывается); введите новое значение для ротации',+ secretKeepHint: 'Настроено — оставьте пустым, чтобы не менять',e2bApiUrlOptional: 'Optional — the SDK default is used when empty',e2bDomainOptional: 'Optional — the SDK default is used when empty',backends: {@@ -4721,9 +4795,12 @@ export default {apiKey: 'API key',templateId: 'Template ID',httpTimeout: 'HTTP timeout (s)',+ httpTimeoutHelp: 'Сколько ждать ответа от управляющего API бэкенда, прежде чем считать эндпоинт недоступным. Пусто — 30 секунд.',sandboxTtl: 'Sandbox TTL (s)',+ sandboxTtlHelp: 'Сколько простаивающая песочница живёт до освобождения провайдером. Слишком мало — при продолжении сессии её придётся создавать заново, слишком много — простаивающие экземпляры продолжают тарифицироваться. Пусто — значение бэкенда по умолчанию.',dockerImage: 'Docker image',defaultTimeout: 'Execution timeout (s)',+ defaultTimeoutHelp: 'Максимальное время одного запуска скрипта навыка; по истечении он прерывается. Пусто — 60 секунд.',envVars: 'Environment variables',envKey: 'Name',envValue: 'Value',@@ -4735,11 +4812,24 @@ export default {saveFailed: 'Failed to save',testConnection: 'Test connection',deepCheck: 'Full verification',- deepCheckConfirm: 'Full verification creates and destroys a real sandbox, consuming a small amount of sandbox time. Continue?',+ recheck: 'Проверить снова',+ deepCheckIntro: 'Перед сохранением можно выполнить полную проверку: она создаёт временную песочницу, запускает скрипт, проверяет исходящую сеть и удаляет её.',+ deepCheckConfirm: 'Full verification runs a throwaway script. Remote backends also create and destroy a real sandbox and may consume a small amount of sandbox time. Continue?',checkPassed: 'All checks passed',checkFailed: 'Some checks failed',+ checkScopeConnection: 'Проверена только плоскость управления: эндпоинт отвечает, ключ действителен. Запустится ли скрипт на самом деле — пока не проверено.',+ checkScopeFull: 'Эндпоинт, ключ, шаблон, выполнение внутри песочницы и исходящая сеть проверены по-настоящему.',+ checkPendingHint: '{names} можно подтвердить только полной проверкой: она создаёт временную песочницу, запускает один скрипт и удаляет её.',+ skipReasons: {+ needs_deep_check: 'Нужна полная проверка',+ control_plane_unreachable: 'Пропущено: плоскость управления недоступна',+ environment_unavailable: 'Пропущено: среда выполнения недоступна',+ sandbox_not_created: 'Пропущено: песочница не создана',+ sandbox_exec_failed: 'Пропущено: выполнение в песочнице не удалось',+ },noVolumeSupport: 'This backend does not support volume mounts; skills relying on a shared volume will be unavailable.',checks: {+ environment_available: 'Runtime availability',client_build: 'Client construction',api_url_reachable: 'Endpoint reachability',credential_valid: 'Credential validity',@@ -5145,10 +5235,10 @@ export default {sandboxConfig: 'Sandbox backend',sandboxConfigDesc: 'Choose which sandbox backend this agent\'s skill scripts execute in.',sandboxBackend: 'Sandbox backend',- sandboxBackendDefault: 'Use deployment defaults',+ sandboxBackendDefault: 'Disable sandbox',sandboxBackendHint: 'Only applies while skill execution is enabled. If the selected config is deleted, this agent\'s skill execution will fail.',sandboxBackendMissing: 'Config deleted',- sandboxNoConfigs: 'This workspace has no named sandbox backend yet, so skill scripts run on the deployment defaults. Add one under Settings - Sandbox Backend.',+ sandboxNoConfigs: 'This workspace has no sandbox backend yet, so skill scripts will not run. Add one under Settings - Sandbox Backend.',sandboxInfoTitle: 'Why choose a backend?',sandboxInfoContent: 'Backends differ in account, region and quota. Once a session\'s sandbox exists, its attachments, artifacts and teardown stay pinned to the config it was created on — changing this only affects sandboxes created afterwards.',skillsInfoTitle: 'Что такое Skills?',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex aa1c33cf7..e8ae3a762 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -4655,18 +4655,34 @@ export default {storageEngine: '存储引擎',sandbox: {title: '沙箱后端',- description: '配置多份沙箱后端,智能体可各自选用其中一份。未填写的项沿用 .env 中的全局默认值。',+ description: '管理智能体技能使用的沙箱运行环境,每个智能体可以选择一份空间后端配置。',+ editorDescription: '配置空间运行环境,Docker、本地进程、CubeSandbox 和 E2B 使用同一套管理流程。',+ stepConnection: '连接',+ stepTemplate: '模板',+ stepRuntime: '运行配置',+ setupProgress: '沙箱配置进度',+ stepDescriptions: {+ connection: '先配置后端并验证连接,通过后再从集群加载模板。',+ template: '选择当前集群返回且已经就绪的运行模板。',+ runtime: '配置执行参数和环境变量,然后保存。',+ },+ back: '上一步',+ connectAndContinue: '连接并继续',loading: '加载沙箱配置...',loadFailed: '加载沙箱配置失败',backend: '沙箱后端',- backendHint: '留空表示沿用全局默认',+ backendType: '沙箱类型',+ backendTypePlaceholder: '选择沙箱类型',+ scriptPolicyLabel: '允许在沙箱中执行技能脚本',+ scriptPolicyDesc: '关闭后本空间所有智能体只能阅读技能内容,不再执行脚本;已在运行的远端沙箱需结束会话后才释放。',+ backendDescriptions: {+ cube: '适合私有化或内网部署的自建 MicroVM 集群',+ e2b: 'E2B 托管服务或兼容 E2B 的集群',+ docker: '每次在当前 WeKnora 主机启动一个短生命周期容器执行脚本',+ local: '直接在 WeKnora 服务进程所在环境执行脚本',+ },addConfig: '添加沙箱后端',- viewDeployDefaults: '查看部署默认配置',- deployDefaultsTitle: '部署默认配置',- deployDefaultsHint: '来自 .env 的全局配置。配置里留空的项即沿用这里的值。',- deployDefaultBackend: '默认后端',- apiKeyConfigured: '已配置',- apiKeyNotConfigured: '未配置',+ viewClusterGuide: '集群搭建指南',configName: '配置名称',configNamePlaceholder: '如:生产 E2B',configNameRequired: '请填写配置名称',@@ -4674,10 +4690,17 @@ export default {configDescriptionPlaceholder: '选填,用于区分多份同类型配置',createTitle: '添加沙箱后端',editTitle: '编辑沙箱后端',- noConfigs: '还没有沙箱后端配置。智能体将使用部署默认配置运行技能脚本。',+ sectionBasic: '基本信息',+ sectionConnection: '集群连接',+ sectionRuntimeEnvironment: '运行环境',+ sectionTemplate: '运行模板',+ sectionRuntime: '执行设置',+ sectionEnvironment: '环境变量',+ noConfigs: '还没有沙箱后端配置。智能体未选择空间配置时不会执行技能脚本。',identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',viewSandboxes: '查看沙箱占用',inventoryTitle: '沙箱占用',+ inventoryDrawerDesc: '该配置当前占用的沙箱,以及受影响的会话与智能体。',inventoryFailed: '获取沙箱占用失败',sandboxCount: '沙箱数量',sandboxCountUnknown: '未知(无法连接该后端)',@@ -4703,9 +4726,60 @@ export default {scriptsEnabled: '已恢复本空间沙盒执行',policySaveFailed: '更新沙盒执行策略失败',legacyConfig: '已废弃',- namedBackendHint: '具名配置支持 CubeSandbox 与 E2B。',+ namedBackendHint: '空间配置是唯一运行时来源;智能体没有选择配置时不会执行技能脚本。',+ weknoraTemplateTitle: 'WeKnora 标准模板',+ weknoraDockerImage: 'WeKnora 标准镜像',+ weknoraDockerImageHint: '每次执行都会基于该镜像创建一个隔离的短生命周期容器,不保留会话沙箱。',+ localRuntimeWarning: '本地进程会直接在 WeKnora 服务器上执行技能脚本,不具备容器或 MicroVM 隔离。仅建议在可信的开发空间使用。',+ weknoraTemplateOverview: 'WeKnora 负责提供标准运行环境。连接集群后会自动发现模板,缺少标准模板时自动创建。',+ weknoraTemplateDescription: '包含 WeKnora 技能所需的 Python、Node.js、CLI 工具、工作目录和非 root 执行用户。',+ recommendedTag: '推荐',+ templateNotConfigured: '未配置模板',+ cardTemplateConfigured: '模板已配置',+ cardCredentialMissing: '缺少 API Key',+ cardTimeout: '超时 {sec}s',+ cardTtl: '沙箱存活 {sec}s',+ cardVolumeMounted: '已挂载卷',+ cardEnvVars: '{count} 个环境变量',+ cardPrivateEndpoints: '允许访问私网',+ imageNotConfigured: '未配置镜像',+ localRuntimeSummary: 'WeKnora 服务器本地进程',+ templateApplied: '已使用',+ refreshTemplates: '刷新模板',+ templateSelectHelp: '模板由当前集群实时返回,保存时仅记录模板 ID,无需手工复制。',+ templateSelectPlaceholder: '先连接集群并加载模板',+ templateLoadHint: '填写集群连接后刷新模板;若缺少 WeKnora 标准模板,系统会自动创建。',+ templateLoadFailed: '模板列表加载失败',+ standardTemplateProvisioning: '已开始在集群中创建 WeKnora 标准模板,请稍后刷新查看状态',+ templateNotReady: '所选模板尚未构建完成,请刷新并等待状态就绪',+ connectionPassed: '连接验证通过,以下模板均从当前集群实时加载。',+ connectionPassedTitle: '集群连接成功',+ templateStepHint: '集群缺少标准模板时,WeKnora 会自动创建;模板就绪后才能继续。',+ loadingTemplates: '正在从集群加载模板…',+ templateBuildingHint: '标准模板正在自动构建,列表会自动刷新。',+ templateUntaggedHint: '构建已完成,但没有构建带 default 标签,创建沙箱时无法解析。请在 E2B 删除该模板,刷新后 WeKnora 会重新构建。',+ noTemplates: '当前集群未返回可用模板。',+ templateReadyHint: '模板「{name}」已就绪并选中。',+ templateProvisioningHint: '模板仍在构建中,状态会自动刷新。',+ templateStatuses: {+ ready: '已就绪',+ building: '构建中',+ untagged: '缺少 default 标签',+ failed: '失败',+ unknown: '未知',+ },+ allowPrivateEndpoints: '允许访问私网集群地址',+ allowPrivateEndpointsHint: '仅用于自建 Cube 等私网控制面;云元数据等链路本地地址始终禁止访问。',+ howToBuildTemplate: '沙箱集群搭建与模板说明',+ noEnvVars: '暂无额外环境变量,仅添加技能确实需要的值。',fieldRequired: '必填',cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',+ cubeApiKeyWhere: '自建集群如何开启鉴权',+ e2bApiKeyHelp: '在 E2B 控制台的 API Keys 页面创建,通常以 e2b_ 开头。',+ e2bApiKeyWhere: '前往 E2B 控制台获取 API Key',+ apiKeyPlaceholder: '粘贴 API Key',+ secretConfigured: '已配置密钥(不可回看);输入新值可轮换',+ secretKeepHint: '已配置,留空表示不修改',e2bApiUrlOptional: '可留空 —— 留空时使用 SDK 默认值',e2bDomainOptional: '可留空 —— 留空时使用 SDK 默认值',backends: {@@ -4721,9 +4795,12 @@ export default {apiKey: 'API Key',templateId: '模板 ID',httpTimeout: 'HTTP 超时(秒)',+ httpTimeoutHelp: '调用沙箱后端管理接口的等待上限,超过即视为端点不可用。留空按 30 秒。',sandboxTtl: '沙箱 TTL(秒)',+ sandboxTtlHelp: '沙箱空闲多久后被远端回收。设得太短,会话继续时要重建沙箱;设得太长,闲置实例会一直计费。留空按后端默认值。',dockerImage: 'Docker 镜像',defaultTimeout: '执行超时(秒)',+ defaultTimeoutHelp: '单次技能脚本允许运行的最长时间,超时会被强制终止。留空按 60 秒。',envVars: '环境变量',envKey: '变量名',envValue: '变量值',@@ -4735,11 +4812,24 @@ export default {saveFailed: '保存失败',testConnection: '测试连接',deepCheck: '完整验证',- deepCheckConfirm: '完整验证会真实创建并销毁一个沙箱,消耗少量沙箱时长,是否继续?',+ recheck: '重新验证',+ deepCheckIntro: '保存前可以跑一次「完整验证」:真实创建一个临时沙箱、执行一次脚本并检查出网,随后自动销毁。',+ deepCheckConfirm: '完整验证会执行一次临时脚本;远端后端还会真实创建并销毁一个沙箱,可能消耗少量沙箱时长。是否继续?',checkPassed: '检测通过',checkFailed: '检测未通过',+ checkScopeConnection: '本次只验证了控制面:端点可达且凭据有效。是否真的能跑起脚本还没有验证。',+ checkScopeFull: '端点、凭据、模板、沙箱内执行与出网均已真实验证。',+ checkPendingHint: '{names} 需要「完整验证」才能确认:会真实创建一个临时沙箱、执行一次脚本再销毁。',noVolumeSupport: '该后端不支持挂载卷,依赖共享卷的技能将不可用。',+ skipReasons: {+ needs_deep_check: '需完整验证',+ control_plane_unreachable: '控制面不可达,已跳过',+ environment_unavailable: '运行环境不可用,已跳过',+ sandbox_not_created: '沙箱未创建,已跳过',+ sandbox_exec_failed: '沙箱内执行失败,已跳过',+ },checks: {+ environment_available: '运行环境可用性',client_build: '客户端构建',api_url_reachable: '端点可达性',credential_valid: '凭据有效性',@@ -5145,10 +5235,10 @@ export default {sandboxConfig: '沙箱后端',sandboxConfigDesc: '选择该智能体的技能脚本在哪个沙箱后端中执行。',sandboxBackend: '沙箱后端',- sandboxBackendDefault: '使用部署默认配置',+ sandboxBackendDefault: '不启用沙箱',sandboxBackendHint: '仅在启用技能执行时生效。所选配置被删除后,该智能体的技能执行会失败。',sandboxBackendMissing: '配置已删除',- sandboxNoConfigs: '当前空间还没有具名沙箱后端配置,技能脚本将运行在部署默认配置上。可在「设置 - 沙箱后端」中添加。',+ sandboxNoConfigs: '当前空间还没有沙箱后端配置,技能脚本不会执行。可在「设置 - 沙箱后端」中添加。',sandboxInfoTitle: '为什么要选后端?',sandboxInfoContent: '不同后端对应不同的账号、区域与配额。同一会话的沙箱一旦创建,后续的附件、产物与销毁都会锁定在创建时那份配置上,改这里只影响之后新建的沙箱。',skillsInfoTitle: '什么是 Skills?',diff --git a/frontend/src/stores/chatResources.ts b/frontend/src/stores/chatResources.tsindex 20916412c..2e6deed1e 100644--- a/frontend/src/stores/chatResources.ts+++ b/frontend/src/stores/chatResources.ts@@ -182,7 +182,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {* 不进 prefetchChatInput:只有编辑智能体时才需要,而对话输入栏用不到,* 没必要让每次首屏都多打一次请求。*- * 失败只吞掉不抛:这是可选资源——拿不到就只剩「使用部署默认配置」一项,+ * 失败只吞掉不抛:这是可选资源——拿不到就只剩「不启用沙箱」一项,* 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个* Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐* (技能可用性拿不到 ⇒ 技能配置分组直接消失)。diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vueindex 94e6c15d6..517b80769 100644--- a/frontend/src/views/agent/AgentEditorModal.vue+++ b/frontend/src/views/agent/AgentEditorModal.vue@@ -1932,7 +1932,7 @@ const skillOptions = ref<{ name: string; description: string }[]>([]);// 是否允许启用 Skills(取决于后端沙箱是否启用,disabled 时为 false;未请求前为 false 避免闪显)const skillsAvailable = ref(false);// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——-// 否则下拉会静默显示为"使用部署默认配置",看不出该智能体其实指着一份不存在的配置。+// 否则下拉会静默显示为“不启用沙箱”,看不出该智能体其实指着一份不存在的配置。const sandboxConfigOptions = computed(() => {const configs = chatResources.sandboxConfigs.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type));const selected = formData.value.config.sandbox_config_id;@@ -2377,7 +2377,7 @@ const defaultFormData = {// Skills 设置skills_selection_mode: 'none' as 'all' | 'selected' | 'none',selected_skills: [] as string[],- // 技能脚本运行在哪份沙箱后端配置上。留空表示使用部署默认配置。+ // 技能脚本运行在哪份空间沙箱配置上。留空表示禁用脚本执行。sandbox_config_id: '' as string,// 知识库设置:新建智能体默认选择 "全部知识库",// 让用户无需先去勾选 KB 即可上手;如有需要可改为 "selected" / "none"。diff --git a/frontend/src/views/dev/MarkdownTestPage.vue b/frontend/src/views/dev/MarkdownTestPage.vueindex 93b40f9a3..ddeb5b4b2 100644--- a/frontend/src/views/dev/MarkdownTestPage.vue+++ b/frontend/src/views/dev/MarkdownTestPage.vue@@ -362,6 +362,54 @@ graph TD>> It can span multiple paragraphs.+\`\`\`mermaid+sequenceDiagram+ participant Driver as 驾驶员 (Driver)+ participant HMI as 人机交互界面 (HMI/Cluster)+ participant ADAS as 组合驾驶辅助系统 (ADAS ECU)+ participant Sensor as 传感器/定位模块+ participant Cloud as 云端服务平台 (可选)++ Note over ADAS, Sensor: 阶段1:正常运行与监控+ Driver->>Sensor: 车辆正常行驶中+ Sensor->>ADAS: 状态数据 (环境、定位、车辆状态)+ ADAS-->>Driver: 维持组合驾驶辅助状态 (显示图标正常)++ Note over ADAS, Sensor: 阶段2:触发接管条件+ alt 系统检测到需接管场景+ Sensor->>ADAS: 检测条件满足 (如: 地图数据缺失/限速变化/系统故障/驾驶员分心)+ ADAS->>HMI: 发送接管请求信号 (HOR Signal)++ Note right of HMI: 阶段3:分级提醒策略 (符合国标要求)+ HMI-->>Driver: 视觉提示 (仪表盘图标闪烁/颜色变化)+ HMI-->>Driver: 听觉提示 (轻柔蜂鸣声)++ ADAS->>HMI: 增强提醒 (若驾驶员无响应)+ HMI-->>Driver: 强视觉警告 (红色边框/文字)+ HMI-->>Driver: 强听觉警告 (连续急促蜂鸣)+ HMI-->>Driver: 触觉提示 (方向盘震动/座椅振动)+ end++ Note over Driver, ADAS: 阶段4:驾驶员响应处理+ alt 驾驶员及时接管+ Driver->>HMI: 手握方向盘动作 (Torque/Grip Detection)+ HMI->>ADAS: 确认驾驶员介入信号+ ADAS-->>Driver: 退出自动驾驶,切换至人工驾驶模式+ ADAS->>HMI: 清除警告提示+ else 驾驶员未响应+ alt 达到最后接管时限 (e.g., T+5s)+ ADAS->>ADAS: 启动最小风险策略 (MRM/MLR)+ ADAS->>HMI: 触发紧急减速/停车提示+ HMI-->>Driver: 紧急警告 (最高级别)+ ADAS->>Sensor: 执行安全停车动作 (靠边、刹车、双闪)+ end+ end++ Note over Cloud, Driver: 阶段5:数据记录与上报+ ADAS->>Cloud: 上传接管事件数据 (时间、原因、驾驶员响应)+ Note right of Cloud: 用于事故定责与算法优化+\`\`\`+Done.`;const streamBuffer = ref('');diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vueindex 90c198b90..ff4c3f3d4 100644--- a/frontend/src/views/settings/SandboxSettings.vue+++ b/frontend/src/views/settings/SandboxSettings.vue@@ -3,14 +3,61 @@<div class="section-header"><div class="section-header__top"><div>- <h2>{{ $t('settings.sandbox.title') }}</h2>+ <div class="section-header__titlewrap">+ <h2>{{ $t('settings.sandbox.title') }}</h2>+ <!--+ The standard-template explainer used to be a permanent note block+ above the list, where it pushed the actual configs below the fold.+ It is reference material, so it belongs behind the title's hint.+ -->+ <t-popup placement="bottom-start" trigger="hover" :overlay-inner-style="{ maxWidth: '380px' }">+ <button type="button" class="hint-trigger"+ :aria-label="$t('settings.sandbox.weknoraTemplateTitle')">+ <t-icon name="info-circle" size="16px" />+ </button>+ <template #content>+ <div class="hint-popover">+ <p class="hint-popover__title">{{ $t('settings.sandbox.weknoraTemplateTitle') }}</p>+ <p class="hint-popover__text">{{ $t('settings.sandbox.weknoraTemplateOverview') }}</p>+ <p class="hint-popover__text">{{ $t('settings.sandbox.namedBackendHint') }}</p>+ </div>+ </template>+ </t-popup>+ </div><p class="section-description">{{ $t('settings.sandbox.description') }}</p>- <p class="section-description section-description--hint">{{ $t('settings.sandbox.namedBackendHint') }}</p></div>- <t-button theme="primary" variant="text" size="medium" class="defaults-trigger" @click="showDefaults = true">- <template #icon><t-icon name="info-circle" /></template>- {{ $t('settings.sandbox.viewDeployDefaults') }}- </t-button>+ <div class="header-actions">+ <a class="header-action-link" :href="sandboxGuideUrl" target="_blank" rel="noopener noreferrer">+ <t-icon name="help-circle" />+ {{ $t('settings.sandbox.viewClusterGuide') }}+ </a>+ </div>+ </div>+ </div>++ <!--+ Workspace-wide kill switch. It used to be a text button next to the type+ tabs, where it read as a filter action; as a labelled switch row it is+ clearly a persistent workspace setting instead.+ -->+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('settings.sandbox.scriptPolicyLabel') }}</label>+ <p class="desc">{{ $t('settings.sandbox.scriptPolicyDesc') }}</p>+ </div>+ <div class="setting-control">+ <!--+ Only switching execution off needs a confirmation, and binding :value+ one-way means the switch cannot flip until the change is accepted.+ -->+ <t-popconfirm v-if="!workspaceScriptsDisabled" theme="warning"+ :content="$t('settings.sandbox.disableScriptsConfirm')"+ :confirm-btn="{ content: $t('settings.sandbox.disableScripts'), theme: 'danger' }"+ :cancel-btn="{ content: $t('common.cancel') }" placement="left"+ @confirm="setScriptsDisabled(true)">+ <t-switch :value="true" :loading="policySaving" />+ </t-popconfirm>+ <t-switch v-else :value="false" :loading="policySaving" @change="setScriptsDisabled(false)" /></div></div>@@ -20,41 +67,38 @@<t-tab-panel v-for="type in backendTypes" :key="type" :value="type":label="`${backendLabel(type)}(${countByType(type)})`" /></t-tabs>- <div class="sandbox-tabs-actions">- <t-button v-if="!workspaceScriptsDisabled" variant="outline" theme="danger" size="medium"- :loading="policySaving" @click="confirmDisableScripts">- {{ $t('settings.sandbox.disableScripts') }}- </t-button>- <t-button v-else variant="outline" theme="primary" size="medium" :loading="policySaving"- @click="enableScripts">- {{ $t('settings.sandbox.enableScripts') }}- </t-button>- </div></div><t-loading :loading="loading" size="small" class="sandbox-list-loading"><div v-if="!loading" class="sandbox-grid"><div v-for="record in filteredRecords" :key="record.id" class="sandbox-card"- :class="`sandbox-card--${record.sandbox_type}`">- <div class="sandbox-card__badge">- <t-icon :name="typeIcon(record.sandbox_type)" size="18px" />- </div>+ :class="[`sandbox-card--${record.sandbox_type}`, { 'sandbox-card--clickable': !isLegacyRecord(record) }]"+ :role="isLegacyRecord(record) ? undefined : 'button'"+ :tabindex="isLegacyRecord(record) ? undefined : 0"+ @click="openEdit(record)" @keydown.enter="openEdit(record)">+ <SandboxBackendBadge :type="record.sandbox_type" /><div class="sandbox-card__body"><div class="sandbox-card__header"><h3 class="sandbox-card__title">{{ record.name }}</h3><div class="sandbox-card__actions" @click.stop>- <t-dropdown :options="cardMenu(record)" trigger="click" attach="body" placement="bottom-right"- @click="(data: any) => onMenuAction(data.value, record)">+ <t-dropdown v-if="!isLegacyRecord(record)" :options="cardMenu(record)" trigger="click" attach="body"+ placement="bottom-right" @click="(data: any) => onMenuAction(data.value, record)"><t-button variant="text" shape="square" size="small" class="sandbox-card__action-btn"><t-icon name="ellipsis" /></t-button></t-dropdown>- <t-tooltip :content="$t('common.delete')" placement="top">- <t-button theme="danger" shape="square" variant="text" size="small"- class="sandbox-card__action-btn" @click.stop="confirmDelete(record)">- <template #icon><t-icon name="delete" /></template>- </t-button>- </t-tooltip>+ <t-popconfirm theme="warning" :content="deleteConfirmText(record)"+ :confirm-btn="{ content: $t('common.delete'), theme: 'danger' }"+ :cancel-btn="{ content: $t('common.cancel') }" placement="bottom-right"+ @visible-change="(visible: boolean) => onDeleteConfirmOpen(visible, record)"+ @confirm="removeRecord(record)">+ <t-tooltip :content="$t('common.delete')" placement="top">+ <t-button theme="danger" shape="square" variant="text" size="small"+ class="sandbox-card__action-btn" @click.stop>+ <template #icon><t-icon name="delete" /></template>+ </t-button>+ </t-tooltip>+ </t-popconfirm></div></div><p class="sandbox-card__subtitle">@@ -62,12 +106,24 @@<t-tag v-if="isLegacyRecord(record)" theme="warning" variant="light" size="small" class="legacy-tag">{{ $t('settings.sandbox.legacyConfig') }}</t-tag>- <template v-if="endpointHost(record)">+ <template v-if="targetSummary(record)"><span class="sandbox-card__sep">·</span>- <span>{{ endpointHost(record) }}</span>+ <span class="sandbox-card__target" :title="targetSummary(record)">{{ targetSummary(record) }}</span></template></p><p v-if="record.description" class="sandbox-card__desc">{{ record.description }}</p>+ <!--+ The card used to spell out the raw template ID, which nobody can+ read or act on. What an admin needs when scanning the list is+ whether the config is complete and how it will behave at runtime.+ -->+ <ul v-if="cardFacts[record.id]?.length" class="sandbox-card__facts">+ <li v-for="fact in cardFacts[record.id]" :key="fact.key" class="sandbox-card__fact"+ :class="{ 'is-warning': fact.tone === 'warning' }" :title="fact.title">+ <t-icon :name="fact.icon" size="12px" />+ <span>{{ fact.text }}</span>+ </li>+ </ul></div></div><button type="button" class="sandbox-card sandbox-card--add" @click="openCreate">@@ -81,99 +137,116 @@</t-loading><SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"- :preset-type="activeType === 'all' ? '' : activeType" :defaults="defaults" @saved="load" />-- <t-dialog v-model:visible="showDefaults" :header="$t('settings.sandbox.deployDefaultsTitle')" width="560px"- :cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showDefaults = false">- <p class="dialog-hint">{{ $t('settings.sandbox.deployDefaultsHint') }}</p>- <ul class="defaults-list">- <li>- <span class="defaults-label">{{ $t('settings.sandbox.deployDefaultBackend') }}</span>- <span>{{ defaults?.sandbox_type ? backendLabel(defaults.sandbox_type) : '-' }}</span>- </li>- <template v-for="provider in defaultProviders" :key="provider.type">- <li class="defaults-group">{{ backendLabel(provider.type) }}</li>- <li v-for="row in provider.rows" :key="row.label">- <span class="defaults-label">{{ row.label }}</span>- <span>{{ row.value }}</span>- </li>- </template>- </ul>- </t-dialog>-- <t-dialog v-model:visible="showInventory" :header="$t('settings.sandbox.inventoryTitle')" width="520px"- :cancel-btn="null" :confirm-btn="{ content: $t('common.close') }" @confirm="showInventory = false">+ :preset-type="activeType === 'all' ? '' : activeType" @saved="load" />++ <!--+ Occupancy is a list of sessions and agents, not a one-line status, and it+ is also what explains a refused delete — so it gets a drawer rather than a+ toast or a cramped dialog.+ -->+ <SettingDrawer v-model:visible="showInventory" :title="$t('settings.sandbox.inventoryTitle')"+ :description="$t('settings.sandbox.inventoryDrawerDesc')" icon="server"+ width="480px" storage-key="setting-drawer:width:sandbox-inventory" hide-footer><t-loading :loading="inventoryLoading" size="small">- <div v-if="inventory" class="inventory">- <t-alert v-if="inventory.unverifiable" theme="warning"+ <section class="setting-drawer__section">+ <t-alert v-if="inventoryNotice === 'blocked'" theme="warning"+ :message="$t('settings.sandbox.sandboxesStillLive', { count: inventory?.sandbox_count ?? 0 })">+ <template #description>+ <p>{{ $t('settings.sandbox.blockedHint') }}</p>+ </template>+ </t-alert>+ <t-alert v-else-if="inventory?.unverifiable" theme="warning":message="$t('settings.sandbox.inventoryUnverifiableHint')" />- <ul class="defaults-list">++ <ul v-if="inventory" class="inventory-list">+ <li v-if="inventoryRecord">+ <span class="inventory-label">{{ $t('settings.sandbox.configName') }}</span>+ <span class="inventory-value">{{ inventoryRecord.name }}</span>+ </li><li>- <span class="defaults-label">{{ $t('settings.sandbox.sandboxCount') }}</span>- <span>{{ inventory.unverifiable+ <span class="inventory-label">{{ $t('settings.sandbox.sandboxCount') }}</span>+ <span class="inventory-value">{{ inventory.unverifiable? $t('settings.sandbox.sandboxCountUnknown'): inventory.sandbox_count }}</span></li><li v-if="inventory.session_ids?.length">- <span class="defaults-label">{{ $t('settings.sandbox.affectedSessions', {+ <span class="inventory-label">{{ $t('settings.sandbox.affectedSessions', {count: inventory.session_ids.length }) }}</span></li><li v-if="inventory.agent_names?.length">- <span class="defaults-label">{{ $t('settings.sandbox.affectedAgents', {+ <span class="inventory-label">{{ $t('settings.sandbox.affectedAgents', {names: inventory.agent_names.join('、') }) }}</span></li></ul>- </div>+ </section>++ <!--+ Force delete only surfaces where its justification is on screen: the+ occupancy could not be verified, so the admin decides with the+ unverifiable warning right above the button.+ -->+ <section v-if="inventoryNotice === 'unverifiable' && inventoryRecord" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.forceDeleteTitle') }}</h4>+ <t-popconfirm theme="warning" :content="$t('settings.sandbox.forceDeleteConfirm')"+ :confirm-btn="{ content: $t('settings.sandbox.forceDelete'), theme: 'danger' }"+ :cancel-btn="{ content: $t('common.cancel') }" placement="top"+ @confirm="forceRemove(inventoryRecord)">+ <t-button theme="danger" variant="outline" size="small">+ {{ $t('settings.sandbox.forceDelete') }}+ </t-button>+ </t-popconfirm>+ </section></t-loading>- </t-dialog>+ </SettingDrawer></div></template><script setup lang="ts">import { computed, onMounted, ref } from 'vue'-import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'+import { MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import SandboxConfigEditorDrawer from '@/components/SandboxConfigEditorDrawer.vue'+import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'+import SettingDrawer from '@/components/settings/SettingDrawer.vue'import {checkSandboxConfig,deleteSandboxConfig,getSandboxConfigInventory,isNamedSandboxBackend,listSandboxConfigs,+ NAMED_SANDBOX_BACKEND_TYPES,parseSandboxConflict,setSandboxWorkspacePolicy,- type SandboxConfigDefaults,type SandboxConfigRecord,type SandboxInventory,} from '@/api/system'const { t } = useI18n()-const backendTypes = ['cube', 'e2b'] as const+const sandboxGuideUrl = 'https://github.com/Tencent/WeKnora/blob/main/docs/sandbox-cluster.md'++const backendTypes = NAMED_SANDBOX_BACKEND_TYPESconst loading = ref(false)const policySaving = ref(false)const workspaceScriptsDisabled = ref(false)const records = ref<SandboxConfigRecord[]>([])-const defaults = ref<SandboxConfigDefaults | null>(null)const activeType = ref<string>('all')const showEditor = ref(false)const editingRecord = ref<SandboxConfigRecord | null>(null)-const showDefaults = ref(false)const showInventory = ref(false)const inventoryLoading = ref(false)const inventory = ref<SandboxInventory | null>(null)+const inventoryRecord = ref<SandboxConfigRecord | null>(null)+// Why the drawer is open: a plain look, or a delete the server refused.+const inventoryNotice = ref<'' | 'blocked' | 'unverifiable'>('')+// Agent names per config, filled in when a delete confirmation opens.+const deleteAgents = ref<Record<string, string[]>>({})const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)-const typeIcon = (type: string) => {- if (type === 'docker' || type === 'local') return 'server'- if (type === 'disabled') return 'minus-circle'- return 'cloud'-}-const isLegacyRecord = (record: SandboxConfigRecord) => !isNamedSandboxBackend(record.sandbox_type)const filteredRecords = computed(() => {@@ -186,15 +259,17 @@ const filteredRecords = computed(() => {const countByType = (type: string) =>records.value.filter((r) => r.sandbox_type === type && isNamedSandboxBackend(r.sandbox_type)).length+// Legacy rows can only be deleted, and that action has its own button, so they+// get no menu at all.const cardMenu = (record: SandboxConfigRecord) => {- if (isLegacyRecord(record)) {- return [{ content: t('common.delete'), value: 'delete-only' }]- }- return [+ const options = [{ content: t('common.edit'), value: 'edit' },{ content: t('settings.sandbox.testConnection'), value: 'check' },- { content: t('settings.sandbox.viewSandboxes'), value: 'inventory' },]+ if (record.sandbox_type === 'cube' || record.sandbox_type === 'e2b') {+ options.push({ content: t('settings.sandbox.viewSandboxes'), value: 'inventory' })+ }+ return options}// The endpoint host is what tells two configs of the same backend apart at a@@ -209,61 +284,29 @@ function endpointHost(record: SandboxConfigRecord): string {}}-const defaultProviders = computed(() => {- const groups: { type: string; rows: { label: string; value: string }[] }[] = []- const describe = (type: 'cube' | 'e2b') => {- const provider = defaults.value?.[type]- if (!provider) return- const rows = [- { label: t('settings.sandbox.apiUrl'), value: provider.api_url || '-' },- ...(type === 'cube'- ? [{ label: t('settings.sandbox.proxyUrl'), value: provider.proxy_url || '-' }]- : []),- { label: t('settings.sandbox.sandboxDomain'), value: provider.sandbox_domain || '-' },- { label: t('settings.sandbox.templateId'), value: provider.template_id || '-' },- {- label: t('settings.sandbox.apiKey'),- value: provider.api_key_configured- ? t('settings.sandbox.apiKeyConfigured')- : t('settings.sandbox.apiKeyNotConfigured'),- },- ]- groups.push({ type, rows })- }- describe('cube')- describe('e2b')- return groups-})-// Agent references never block deletion, but the admin has to see which agents// will start failing — otherwise the breakage is discovered mid-conversation.-// The inventory is fetched first purely for that warning; the DELETE itself is-// still the authoritative check.-async function confirmDelete(record: SandboxConfigRecord) {- let agents: string[] = []+// The lookup happens when the confirmation opens, so the warning appears in the+// same popup without every card probing its backend on page load.+function deleteConfirmText(record: SandboxConfigRecord): string {+ const agents = deleteAgents.value[record.id]+ if (agents?.length) {+ return t('settings.sandbox.confirmDeleteWithAgents', {+ name: record.name,+ agents: t('settings.sandbox.affectedAgents', { names: agents.join('、') }) + ' ',+ })+ }+ return t('settings.sandbox.confirmDelete', { name: record.name })+}++async function onDeleteConfirmOpen(visible: boolean, record: SandboxConfigRecord) {+ if (!visible || deleteAgents.value[record.id]) returntry {const res = await getSandboxConfigInventory(record.id)- agents = res?.data?.agent_names || []+ deleteAgents.value = { ...deleteAgents.value, [record.id]: res?.data?.agent_names || [] }} catch {// An unreachable backend must not stop the admin from trying to delete.}- const body = agents.length- ? t('settings.sandbox.confirmDeleteWithAgents', {- name: record.name,- agents: t('settings.sandbox.affectedAgents', { names: agents.join('、') }) + ' ',- })- : t('settings.sandbox.confirmDelete', { name: record.name })- const dialog = DialogPlugin.confirm({- header: t('common.confirmDelete'),- body,- theme: 'warning',- confirmBtn: { content: t('common.delete'), theme: 'danger' },- cancelBtn: t('common.cancel'),- onConfirm: async () => {- dialog.destroy()- await removeRecord(record)- },- })}function openCreate() {@@ -271,12 +314,136 @@ function openCreate() {showEditor.value = true}+function openEdit(record: SandboxConfigRecord) {+ if (isLegacyRecord(record)) return+ editingRecord.value = record+ showEditor.value = true+}++// What this config actually points at: the remote host, the container image, or+// the local runtime. Two configs of the same backend are told apart by it.+function targetSummary(record: SandboxConfigRecord): string {+ if (record.sandbox_type === 'docker') {+ return record.config?.docker?.image || ''+ }+ if (record.sandbox_type === 'local') {+ return t('settings.sandbox.localRuntimeSummary')+ }+ return endpointHost(record)+}++interface CardFact {+ key: string+ icon: string+ text: string+ /** Full value for opaque identifiers we only summarise on the card. */+ title?: string+ tone?: 'warning'+}++const REMOTE_BACKENDS = new Set(['cube', 'e2b'])++// Facts are derived from the config we already hold, so the list stays cheap:+// nothing here probes a provider. Anything that would need a remote call+// (liveness, running sandboxes) stays behind the card menu.+const cardFacts = computed<Record<string, CardFact[]>>(() => {+ const map: Record<string, CardFact[]> = {}+ for (const record of records.value) {+ map[record.id] = buildCardFacts(record)+ }+ return map+})++function buildCardFacts(record: SandboxConfigRecord): CardFact[] {+ const facts: CardFact[] = []+ const config = record.config || {}+ const remote = config.cube || config.e2b++ // Incomplete configs come first: they are why a skill fails at runtime.+ if (REMOTE_BACKENDS.has(record.sandbox_type)) {+ const templateID = remote?.template_id?.trim() || ''+ facts.push(templateID+ ? {+ key: 'template',+ icon: 'code',+ text: t('settings.sandbox.cardTemplateConfigured'),+ title: templateID,+ }+ : {+ key: 'template',+ icon: 'error-circle',+ text: t('settings.sandbox.templateNotConfigured'),+ tone: 'warning',+ })+ if (!remote?.api_key?.trim()) {+ facts.push({+ key: 'credential',+ icon: 'error-circle',+ text: t('settings.sandbox.cardCredentialMissing'),+ tone: 'warning',+ })+ }+ }+ if (record.sandbox_type === 'docker' && !config.docker?.image?.trim()) {+ facts.push({+ key: 'image',+ icon: 'error-circle',+ text: t('settings.sandbox.imageNotConfigured'),+ tone: 'warning',+ })+ }++ if (config.default_timeout_sec) {+ facts.push({+ key: 'timeout',+ icon: 'time',+ text: t('settings.sandbox.cardTimeout', { sec: config.default_timeout_sec }),+ })+ }+ const ttl = record.config?.cube?.cube_sandbox_ttl_seconds+ || record.config?.e2b?.e2b_sandbox_ttl_seconds+ if (ttl) {+ facts.push({+ key: 'ttl',+ icon: 'hourglass',+ text: t('settings.sandbox.cardTtl', { sec: ttl }),+ })+ }+ if (config.volume_mount?.enabled) {+ facts.push({+ key: 'volume',+ icon: 'folder',+ text: config.volume_mount.volume_name?.trim()+ || config.volume_mount.mount_path?.trim()+ || t('settings.sandbox.cardVolumeMounted'),+ })+ }+ const envCount = Object.keys(config.env_vars || {}).length+ if (envCount) {+ facts.push({+ key: 'env',+ icon: 'code-1',+ text: t('settings.sandbox.cardEnvVars', { count: envCount }),+ })+ }+ // A config allowed to reach private addresses widens the workspace's SSRF+ // surface, so it is called out rather than buried in the form.+ if (config.allow_private_endpoints) {+ facts.push({+ key: 'private',+ icon: 'lock-on',+ text: t('settings.sandbox.cardPrivateEndpoints'),+ tone: 'warning',+ })+ }+ return facts+}+async function load() {loading.value = truetry {const res = await listSandboxConfigs()records.value = res?.data || []- defaults.value = res?.defaults || nullworkspaceScriptsDisabled.value = res?.workspace_scripts_disabled === true} catch (e: any) {MessagePlugin.error(e?.message || t('settings.sandbox.loadFailed'))@@ -285,24 +452,6 @@ async function load() {}}-function confirmDisableScripts() {- const dialog = DialogPlugin.confirm({- header: t('settings.sandbox.disableScripts'),- body: t('settings.sandbox.disableScriptsConfirm'),- theme: 'warning',- confirmBtn: { content: t('settings.sandbox.disableScripts'), theme: 'danger' },- cancelBtn: t('common.cancel'),- onConfirm: async () => {- dialog.destroy()- await setScriptsDisabled(true)- },- })-}--async function enableScripts() {- await setScriptsDisabled(false)-}-async function setScriptsDisabled(disabled: boolean) {policySaving.value = truetry {@@ -319,10 +468,6 @@ async function setScriptsDisabled(disabled: boolean) {}async function onMenuAction(action: string, record: SandboxConfigRecord) {- if (action === 'delete-only') {- confirmDelete(record)- return- }if (action === 'edit') {editingRecord.value = recordshowEditor.value = true@@ -356,6 +501,8 @@ async function runQuickCheck(record: SandboxConfigRecord) {}async function openInventory(record: SandboxConfigRecord) {+ inventoryRecord.value = record+ inventoryNotice.value = ''showInventory.value = trueinventoryLoading.value = trueinventory.value = null@@ -374,53 +521,41 @@ async function removeRecord(record: SandboxConfigRecord, force = false) {try {await deleteSandboxConfig(record.id, force)MessagePlugin.success(t('settings.sandbox.deleted'))+ showInventory.value = falseawait load()} catch (e: any) {const refusal = parseSandboxConflict(e)+ // Both refusals are about what the config still occupies, so both land in+ // the occupancy drawer where that state is spelled out. Counted sandboxes+ // are never overridable — forcing the row away would leave paused instances+ // nobody can reach, billing indefinitely — so only the unverifiable case+ // offers a force option there.if (refusal?.code === 'sandboxes_still_live') {- // Counted sandboxes are never overridable: forcing the row away would- // leave paused instances nobody can reach, billing indefinitely.- showStillLiveDialog(refusal.inventory)+ showRefusal(record, 'blocked', refusal.inventory)return}if (refusal?.code === 'sandbox_inventory_unverifiable') {- confirmForceDelete(record)+ showRefusal(record, 'unverifiable', refusal.inventory)return}MessagePlugin.error(e?.message || t('settings.sandbox.deleteFailed'))}}-function showStillLiveDialog(inv?: SandboxInventory) {- const lines = [t('settings.sandbox.sandboxesStillLive', { count: inv?.sandbox_count ?? 0 })]- if (inv?.session_ids?.length) {- lines.push(t('settings.sandbox.affectedSessions', { count: inv.session_ids.length }))- }- lines.push(t('settings.sandbox.blockedHint'))- const dialog = DialogPlugin.alert({- header: t('settings.sandbox.inventoryTitle'),- // A dialog body is plain text, so newlines would collapse.- body: lines.join(' '),- confirmBtn: t('common.close'),- onConfirm: () => dialog.destroy(),- })+function showRefusal(+ record: SandboxConfigRecord,+ notice: 'blocked' | 'unverifiable',+ inv?: SandboxInventory,+) {+ inventoryRecord.value = record+ inventoryNotice.value = notice+ inventory.value = inv || { sandbox_count: 0, unverifiable: notice === 'unverifiable' }+ inventoryLoading.value = false+ showInventory.value = true}-// Deleting is the one action with no second way out: an endpoint whose DNS-// record is gone can never be verified again, so the row would be permanently-// undeletable. The admin takes that call explicitly.-function confirmForceDelete(record: SandboxConfigRecord) {- const dialog = DialogPlugin.confirm({- header: t('settings.sandbox.forceDeleteTitle'),- body: t('settings.sandbox.forceDeleteConfirm'),- theme: 'warning',- confirmBtn: { content: t('settings.sandbox.forceDelete'), theme: 'danger' },- cancelBtn: t('common.cancel'),- onConfirm: async () => {- dialog.destroy()- await removeRecord(record, true)- },- })+async function forceRemove(record: SandboxConfigRecord) {+ await removeRecord(record, true)}onMounted(load)@@ -428,24 +563,25 @@ onMounted(load)<style lang="less" scoped>.sandbox-settings {- padding: 4px 0;+ width: 100%;}-.section-header h2 {- margin: 0 0 6px;- font-size: 18px;- font-weight: 600;+.section-header {+ margin-bottom: 20px;++ h2 {+ margin: 0 0 8px;+ font-size: 20px;+ font-weight: 600;+ color: var(--td-text-color-primary);+ }}.section-description {- margin: 0 0 20px;+ margin: 0;color: var(--td-text-color-secondary);- font-size: 13px;-- &--hint {- margin-top: -12px;- margin-bottom: 20px;- }+ font-size: 14px;+ line-height: 1.6;}.section-header__top {@@ -463,21 +599,121 @@ onMounted(load)font-weight: 600;}+.header-actions {+ display: flex;+ align-items: center;+ gap: 18px;+ flex-shrink: 0;+}++.header-action-link {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ color: var(--td-brand-color);+ font-size: 14px;+ font-weight: 600;+ text-decoration: none;++ &:hover {+ color: var(--td-brand-color-hover);+ }+}++.section-header__titlewrap {+ display: flex;+ align-items: center;+ gap: 6px;++ h2 {+ margin-bottom: 0;+ }+}++.hint-trigger {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 2px;+ border: none;+ border-radius: 4px;+ background: transparent;+ color: var(--td-text-color-placeholder);+ cursor: help;+ line-height: 1;++ &:hover,+ &:focus-visible {+ color: var(--td-brand-color);+ }+}++.hint-popover {+ display: flex;+ flex-direction: column;+ gap: 4px;+ max-width: 340px;+}++.hint-popover__title {+ margin: 0;+ color: var(--td-text-color-primary);+ font-size: 13px;+ font-weight: 600;+}++.hint-popover__text {+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.55;+}+.sandbox-list-loading {min-height: 120px;}-.sandbox-tabs-row {+.setting-row {display: flex;align-items: flex-start;justify-content: space-between;- gap: 16px;- margin-bottom: 16px;+ gap: 24px;+ padding: 0 0 16px;+ margin-bottom: 8px;+ border-bottom: 1px solid var(--td-component-stroke);+}++.setting-info {+ flex: 1;+ min-width: 0;++ label {+ display: block;+ margin-bottom: 4px;+ color: var(--td-text-color-primary);+ font-size: 14px;+ font-weight: 500;+ }++ .desc {+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: 13px;+ line-height: 1.5;+ }}-.sandbox-tabs-actions {+.setting-control {flex-shrink: 0;- padding-top: 4px;+ display: flex;+ align-items: center;+}++.sandbox-tabs-row {+ display: flex;+ align-items: flex-start;+ gap: 16px;+ margin-bottom: 16px;}.sandbox-type-tabs {@@ -489,6 +725,24 @@ onMounted(load)font-size: 13px;}+ :deep(.t-tabs__nav-item-wrapper) {+ padding: 0 12px;+ margin: 0;+ }++ :deep(.t-tabs__operations) {+ display: none;+ }++ :deep(.t-tabs__nav-scroll) {+ overflow-x: auto;+ scrollbar-width: none;++ &::-webkit-scrollbar {+ display: none;+ }+ }+:deep(.t-tabs__content) {display: none;}@@ -522,6 +776,15 @@ onMounted(load)box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);}+ &--clickable {+ cursor: pointer;++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 2px;+ }+ }+&--add {flex-direction: column;align-items: center;@@ -567,30 +830,6 @@ onMounted(load)}}-.sandbox-card__badge {- flex-shrink: 0;- width: 36px;- height: 36px;- border-radius: 9px;- display: flex;- align-items: center;- justify-content: center;- margin-top: 1px;- background: rgba(0, 82, 217, 0.1);- color: #0052D9;-}--.sandbox-card--e2b .sandbox-card__badge {- background: rgba(98, 53, 187, 0.1);- color: #6235BB;-}--.sandbox-card--docker .sandbox-card__badge,-.sandbox-card--local .sandbox-card__badge {- background: rgba(17, 128, 83, 0.1);- color: #118053;-}-.sandbox-card__body {flex: 1;min-width: 0;@@ -635,6 +874,44 @@ onMounted(load)color: var(--td-text-color-placeholder);}+.sandbox-card__target {+ font-family: var(--td-font-family-medium, inherit);+}++.sandbox-card__facts {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px 6px;+ margin: 8px 0 0;+ padding: 0;+ list-style: none;+}++.sandbox-card__fact {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ max-width: 100%;+ padding: 2px 7px;+ border-radius: 5px;+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-size: 12px;+ line-height: 1.5;++ span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ &.is-warning {+ background: color-mix(in srgb, var(--td-warning-color) 12%, transparent);+ color: var(--td-warning-color-7, var(--td-warning-color));+ }+}+.sandbox-card__sep {margin: 0 4px;color: var(--td-text-color-placeholder);@@ -655,13 +932,13 @@ onMounted(load).sandbox-card__action-btn {flex-shrink: 0;padding: 2px;- opacity: 0;- transition: opacity 0.15s ease;-}+ color: var(--td-text-color-placeholder);+ transition: color 0.15s ease, background-color 0.15s ease;-.sandbox-card:hover .sandbox-card__action-btn,-.sandbox-card:focus-within .sandbox-card__action-btn {- opacity: 1;+ &:hover {+ color: var(--td-text-color-primary);+ background: var(--td-bg-color-secondarycontainer);+ }}.sandbox-empty-hint {@@ -670,37 +947,29 @@ onMounted(load)color: var(--td-text-color-placeholder);}-.dialog-hint {- margin: 0 0 12px;- font-size: 13px;- color: var(--td-text-color-secondary);-}--.defaults-list {+.inventory-list {margin: 0;padding: 0;list-style: none;display: flex;flex-direction: column;- gap: 6px;+ gap: 8px;font-size: 13px;}-.defaults-group {- margin-top: 8px;- font-weight: 600;- color: var(--td-text-color-primary);+.inventory-list li {+ display: flex;+ align-items: baseline;+ gap: 8px;+ line-height: 1.55;}-.defaults-label {- display: inline-block;- min-width: 120px;+.inventory-label {color: var(--td-text-color-secondary);}-.inventory {- display: flex;- flex-direction: column;- gap: 12px;+.inventory-value {+ color: var(--td-text-color-primary);+ font-weight: 500;}</style>diff --git a/frontend/src/views/settings/providerLogos.ts b/frontend/src/views/settings/providerLogos.tsindex e15b054e7..53ed76771 100644--- a/frontend/src/views/settings/providerLogos.ts+++ b/frontend/src/views/settings/providerLogos.ts@@ -21,7 +21,7 @@ const monoModules = import.meta.glob('@/assets/img/providers/mono/*/*.svg', {import: 'default',}) as Record<string, string>;-export type ProviderCategory = 'vectorstore' | 'storage' | 'websearch' | 'parser';+export type ProviderCategory = 'vectorstore' | 'storage' | 'websearch' | 'parser' | 'sandbox';export type LogoMatch = {mode: 'color' | 'mono';diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex b75fc1ee2..5e605c3ec 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -4,9 +4,6 @@ import ("context""database/sql""fmt"- "os"- "strconv"- "strings""github.com/Tencent/WeKnora/internal/agent""github.com/Tencent/WeKnora/internal/agent/approval"@@ -352,10 +349,10 @@ func (s *agentService) resolveKBAndDocInfos(// initializeSkillsManager creates and initializes the skills manager.//// The sandbox manager is resolved per workspace: backends differ in-// capability (E2B exposes a session file store, local does not), so tool+// capability (remote MicroVMs expose a session file store, local does not), so tool// registration below must inspect this workspace's real manager rather than a-// process-wide singleton. Workspaces without their own sandbox configuration-// resolve to the injected default.+// process-wide singleton. Workspaces without a selected configuration resolve+// to the disabled manager.func (s *agentService) initializeSkillsManager(ctx context.Context,sessionID string,@@ -363,30 +360,18 @@ func (s *agentService) initializeSkillsManager(toolRegistry *tools.ToolRegistry,) (*skills.Manager, error) {tenantID, _ := types.TenantIDFromContext(ctx)- configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, config.SandboxConfigID)+ sandboxMgr, configID, err := resolveSandboxForExecution(+ ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,+ tenantID, sessionID, config.SandboxConfigID, s.sandboxPolicy,+ )if err != nil {return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)}- sandboxMgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)- if err != nil {- return nil, err- }if sandboxMgr == nil {sandboxMgr = sandbox.NewDisabledManager()}- sandboxMode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))- if sandboxMode == "" {- sandboxMode = "disabled"- }- sandboxTimeout := 60- if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- sandboxTimeout = n- }- }- logger.Infof(ctx, "Sandbox in use: mode=%s type=%s timeout=%ds",- sandboxMode, sandboxMgr.GetType(), sandboxTimeout)+ logger.Infof(ctx, "Workspace sandbox in use: config=%s type=%s", configID, sandboxMgr.GetType())// Create skills managerskillsConfig := &skills.ManagerConfig{diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.goindex c194cd26d..e808eac37 100644--- a/internal/application/service/session_agent_qa.go+++ b/internal/application/service/session_agent_qa.go@@ -5,7 +5,6 @@ import ("encoding/json""errors""fmt"- "os""github.com/Tencent/WeKnora/internal/agent/tools""github.com/Tencent/WeKnora/internal/event"@@ -147,17 +146,15 @@ func (s *sessionService) AgentQA(// sandbox before the model can request shell or skill execution. The// durable storage URL — not the ephemeral sandbox path — remains the// source of truth. Gated on the sandbox manager advertising a session- // filesystem capability so provider-neutral wiring (Cube today, E2B- // tomorrow) drops in without touching this call site.+ // filesystem capability so provider-neutral remote wiring stays here.var stagedAttachments []stagedSessionAttachmentstager, ok := s.agentService.(sessionAttachmentStager)if !ok {return errors.New("agent service does not support session attachment staging")}// Probe the backend this session's sandbox actually runs on. Gating on the- // process-wide manager instead would skip staging whenever the deployment- // default is docker/local but the agent selected a named Cube/E2B config —- // the tools would still run remotely, against an empty /workspace/input.+ // process-wide manager instead could inspect a different backend than the+ // named workspace config selected by this agent.inputStore, storeErr := stager.sessionSandboxInputStore(ctx, sessionID, agentConfig.SandboxConfigID)if storeErr != nil {return fmt.Errorf("resolve sandbox file store for session %s: %w", sessionID, storeErr)@@ -537,15 +534,6 @@ func (s *sessionService) configureSkillsFromAgent(return}agentConfig.SandboxConfigID = customAgent.Config.SandboxConfigID- // When sandbox is disabled, skills cannot be enabled (no script execution environment)- sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")- if sandboxMode == "" || sandboxMode == "disabled" {- agentConfig.SkillsEnabled = false- agentConfig.SkillDirs = nil- agentConfig.AllowedSkills = nil- logger.Infof(ctx, "Sandbox is disabled: skills are not available")- return- }dir := getPreloadedSkillsDir()switch customAgent.Config.SkillsSelectionMode {case "all":diff --git a/internal/application/service/session_attachment_staging.go b/internal/application/service/session_attachment_staging.goindex c4287773d..ecc4cbaf9 100644--- a/internal/application/service/session_attachment_staging.go+++ b/internal/application/service/session_attachment_staging.go@@ -59,9 +59,9 @@ type sessionAttachmentStager interface {// backend this session's sandbox actually runs on.//// Callers must gate staging on this rather than on the process-wide manager: a-// workspace can select a named Cube/E2B config while the deployment default is-// docker/local, and in that combination the agent still registers shell/skill-// tools against the remote sandbox, so its attachments have to be staged too.+// different workspace configs expose different capabilities. Remote backends+// need attachment staging; stateless Docker/Local backends do not advertise a+// session filesystem at all.func (s *agentService) sessionSandboxInputStore(ctx context.Context,sessionID string,@@ -71,15 +71,12 @@ func (s *agentService) sessionSandboxInputStore(return nil, nil}tenantID, _ := types.TenantIDFromContext(ctx)- configID, err := sandboxConfigForExecution(ctx, s.sandboxPinner, sessionID, agentSandboxConfigID)- if err != nil {- return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)- }- mgr, err := resolveTenantSandboxForConfig(- ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy,+ mgr, _, err := resolveSandboxForExecution(+ ctx, s.sandboxResolver, s.sandboxMgr, s.sandboxPinner,+ tenantID, sessionID, agentSandboxConfigID, s.sandboxPolicy,)if err != nil {- return nil, err+ return nil, fmt.Errorf("resolve sandbox config for session %s: %w", sessionID, err)}return sessionSandboxFileStore(mgr), nil}diff --git a/internal/application/service/session_attachment_staging_test.go b/internal/application/service/session_attachment_staging_test.goindex 783be3ff3..9b63d1aea 100644--- a/internal/application/service/session_attachment_staging_test.go+++ b/internal/application/service/session_attachment_staging_test.go@@ -106,8 +106,6 @@ func (m *stagingSandboxManager) RemoveSessionInputPath(_ context.Context, _ stri}func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_MODE", "cube")-attachment := types.MessageAttachment{URL: "local://tenant/attachment-1",FileName: "report.pdf",@@ -124,12 +122,16 @@ func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {fileService := &stagingFileService{files: map[string][]byte{attachment.URL: []byte("content")},}- service := &agentService{sandboxMgr: manager, fileService: fileService}+ service := &agentService{+ sandboxMgr: manager, fileService: fileService,+ sandboxResolver: stubSandboxResolver{mgr: manager},+ }+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))staged, err := service.stageSessionAttachments(- context.Background(),+ ctx,"session-1",- "",+ "cfg-remote",types.MessageAttachments{attachment, attachment},)@@ -142,14 +144,12 @@ func TestStageSessionAttachmentsReconcilesAndSkipsExisting(t *testing.T) {assert.NotContains(t, manager.files, stalePath)// The second reconciliation sees the same path and size and avoids storage IO.- _, err = service.stageSessionAttachments(context.Background(), "session-1", "", types.MessageAttachments{attachment})+ _, err = service.stageSessionAttachments(ctx, "session-1", "cfg-remote", types.MessageAttachments{attachment})require.NoError(t, err)assert.Equal(t, 1, fileService.getCalls[attachment.URL])}func TestStageSessionAttachmentsSkipsWhenNoFilesystemCapability(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_MODE", "local")-// disableFiles=true simulates any manager without a session filesystem// capability (Local/Docker/Disabled DefaultManager, or a// SessionBoundManager whose remote provider fell back to Local).diff --git a/internal/application/service/session_sandbox_entry_test.go b/internal/application/service/session_sandbox_entry_test.goindex e6b8d7ebd..d588a6a99 100644--- a/internal/application/service/session_sandbox_entry_test.go+++ b/internal/application/service/session_sandbox_entry_test.go@@ -43,23 +43,6 @@ func (m *artifactFallbackManager) ReadSessionFile(ctx context.Context, sessionIDreturn m.source.ReadSessionFile(ctx, sessionID, path)}-// Execution decides the config; every later operation must follow the pin, so-// that re-pointing the agent mid-conversation cannot split a session across-// two backends.-func TestSandboxConfigForExecutionPinsAgentChoice(t *testing.T) {- pinner := NewSessionSandboxPinner(newPinTestDB(t))- ctx := context.Background()-- got, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")- require.NoError(t, err)- require.Equal(t, "cfg-a", got)-- // Admin re-points the agent at cfg-b: the live sandbox stays on cfg-a.- got, err = sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-b")- require.NoError(t, err)- require.Equal(t, "cfg-a", got)-}-func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))@@ -68,38 +51,9 @@ func TestSandboxConfigForExistingSandboxReturnsEmptyWhenUnpinned(t *testing.T) {require.Empty(t, got, "no pin means no live sandbox; callers must skip")}-func TestSandboxConfigForExecutionUsesSentinelForGlobalDefault(t *testing.T) {- pinner := NewSessionSandboxPinner(newPinTestDB(t))-- got, err := sandboxConfigForExecution(context.Background(), pinner, "s-1", "")- require.NoError(t, err)- require.Equal(t, types.SandboxConfigIDGlobalDefault, got)-}--// Attachment staging can be the call that creates the session's first sandbox-// (WriteSessionInputFile provisions on first write), so it must pin like-// execution does - not follow a pin that does not exist yet.-func TestSandboxConfigForExecutionPinsOnFirstStaging(t *testing.T) {- pinner := NewSessionSandboxPinner(newPinTestDB(t))- ctx := context.Background()-- staged, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")- require.NoError(t, err)- require.Equal(t, "cfg-a", staged)-- // The execution that follows in the same turn must land on the same config.- executed, err := sandboxConfigForExecution(ctx, pinner, "s-1", "cfg-a")- require.NoError(t, err)- require.Equal(t, staged, executed)-}--// Most deployments run every session on the WEKNORA_SANDBOX_* default, whose-// pin is the sentinel and whose manager is the injected process-wide one. That-// must keep collecting artifacts: resolving the sentinel yields no per-config-// manager, which is not the same as "this session has no sandbox".+// Older sessions can still carry the historical default-config sentinel. The+// fallback manager remains readable so those sessions can be cleaned up.func TestArtifactSessionSourceKeepsDefaultBackendForSentinelPin(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_MODE", "cube")-pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()_, err := pinner.Pin(ctx, "s-1", types.SandboxConfigIDGlobalDefault)diff --git a/internal/application/service/session_sandbox_gating_test.go b/internal/application/service/session_sandbox_gating_test.goindex 5c6b9494f..e3f61a84a 100644--- a/internal/application/service/session_sandbox_gating_test.go+++ b/internal/application/service/session_sandbox_gating_test.go@@ -17,8 +17,6 @@ import (// process-wide manager would leave those tools running against an empty// /workspace/input.func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_MODE", "local")-// The deployment default advertises no session filesystem, standing in for// docker/local/disabled.deploymentDefault := &stagingSandboxManager{@@ -43,8 +41,6 @@ func TestSessionSandboxInputStoreUsesNamedConfigNotDeploymentDefault(t *testing.// The mirror case: no named config means the deployment default decides, and a// backend without a session filesystem must not stage anything.func TestSessionSandboxInputStoreSkipsWhenDeploymentDefaultHasNoFilesystem(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_MODE", "local")-deploymentDefault := &stagingSandboxManager{sandboxType: sandbox.SandboxTypeLocal,disableFiles: true,diff --git a/internal/application/service/session_sandbox_pin.go b/internal/application/service/session_sandbox_pin.goindex e6712e93e..50f7e24ef 100644--- a/internal/application/service/session_sandbox_pin.go+++ b/internal/application/service/session_sandbox_pin.go@@ -23,6 +23,7 @@ import ("gorm.io/gorm"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/types")@@ -86,7 +87,9 @@ func (p *SessionSandboxPinner) Pin() (string, error) {configID = strings.TrimSpace(configID)if configID == "" {- configID = types.SandboxConfigIDGlobalDefault+ // No workspace config means sandbox execution is disabled, so there is+ // no remote resource whose backend needs pinning.+ return "", 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@@ -136,28 +139,58 @@ func (p *SessionSandboxPinner) Clear(ctx context.Context, sessionID string) erroUpdate("sandbox_config_id", nil).Error}-// sandboxConfigForExecution decides which config a session's sandbox runs on.-//-// Skill execution and attachment staging can be the first operation that creates-// a session sandbox, so they adopt an existing pin and otherwise claim the-// agent's current choice. Later operations must follow the pin instead.-func sandboxConfigForExecution(+// resolveSandboxForExecution resolves before pinning so stateless workspace+// backends (docker/local) 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.+func resolveSandboxForExecution(ctx context.Context,+ resolver sandbox.TenantSandboxResolver,+ fallback sandbox.Manager,pinner *SessionSandboxPinner,+ tenantID uint64,sessionID string,agentConfigID string,-) (string, error) {+ policy WorkspaceSandboxPolicy,+) (sandbox.Manager, string, error) {+ if pinner != nil && strings.TrimSpace(sessionID) != "" {+ pinned, err := pinner.Read(ctx, sessionID)+ if err != nil {+ return nil, "", err+ }+ if pinned != "" {+ mgr, err := resolveTenantSandboxForConfig(+ ctx, resolver, fallback, tenantID, pinned, policy,+ )+ return mgr, pinned, err+ }+ }++ configID := strings.TrimSpace(agentConfigID)+ mgr, err := resolveTenantSandboxForConfig(+ ctx, resolver, fallback, tenantID, configID, policy,+ )+ if err != nil || mgr == nil {+ return mgr, configID, err+ }+ if mgr.GetType() != sandbox.SandboxTypeCube && mgr.GetType() != sandbox.SandboxTypeE2B {+ return mgr, configID, nil+ }if pinner == nil || strings.TrimSpace(sessionID) == "" {- return agentConfigID, nil+ return mgr, configID, nil}- pinned, err := pinner.Read(ctx, sessionID)++ winner, err := pinner.Pin(ctx, sessionID, configID)if err != nil {- return "", err+ return nil, "", err}- if pinned != "" {- return pinned, nil+ if winner == configID {+ return mgr, winner, nil}- return pinner.Pin(ctx, sessionID, agentConfigID)+ mgr, err = resolveTenantSandboxForConfig(+ ctx, resolver, fallback, tenantID, winner, policy,+ )+ return mgr, winner, err}// sandboxConfigForExistingSandbox returns the config an already-createddiff --git a/internal/application/service/session_sandbox_pin_test.go b/internal/application/service/session_sandbox_pin_test.goindex 33163779a..cd94a43da 100644--- a/internal/application/service/session_sandbox_pin_test.go+++ b/internal/application/service/session_sandbox_pin_test.go@@ -8,9 +8,21 @@ import ("gorm.io/driver/sqlite""gorm.io/gorm"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/types")+type pinTestManager struct {+ typ sandbox.SandboxType+}++func (m *pinTestManager) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {+ return nil, nil+}+func (m *pinTestManager) Cleanup(context.Context) error { return nil }+func (m *pinTestManager) GetSandbox() sandbox.Sandbox { return nil }+func (m *pinTestManager) GetType() sandbox.SandboxType { return m.typ }+func newPinTestDB(t *testing.T) *gorm.DB {t.Helper()db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})@@ -52,13 +64,13 @@ func TestPinIsIdempotentAndReturnsExistingWinner(t *testing.T) {require.Equal(t, "cfg-a", second, "the first writer wins; later callers adopt it")}-func TestPinNormalizesEmptyConfigToSentinel(t *testing.T) {+func TestPinLeavesEmptyConfigUnpinned(t *testing.T) {pinner := NewSessionSandboxPinner(newPinTestDB(t))ctx := context.Background()got, err := pinner.Pin(ctx, "s-1", "")require.NoError(t, err)- require.Equal(t, types.SandboxConfigIDGlobalDefault, got)+ require.Empty(t, got)}// A padded ID must land in the column exactly as Read will compare it, or the@@ -134,3 +146,54 @@ func TestSoftDeleteHidesSandboxPin(t *testing.T) {require.NoError(t, err)require.Empty(t, read, "soft-deleted session must not expose its pin")}++func TestResolveSandboxForExecutionDoesNotPinStatelessBackend(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ want := &pinTestManager{typ: sandbox.SandboxTypeLocal}++ got, configID, 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)+ pinned, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Empty(t, pinned, "local and Docker executions must not leave a session binding")+}++func TestResolveSandboxForExecutionPinsRemoteBackend(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ want := &pinTestManager{typ: sandbox.SandboxTypeCube}++ got, configID, 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)+ pinned, err := pinner.Read(context.Background(), "s-1")+ require.NoError(t, err)+ require.Equal(t, "cfg-cube", pinned)+}++func TestResolveSandboxForExecutionKeepsExistingRemotePin(t *testing.T) {+ pinner := NewSessionSandboxPinner(newPinTestDB(t))+ _, err := pinner.Pin(context.Background(), "s-1", "cfg-existing")+ require.NoError(t, err)+ want := &pinTestManager{typ: sandbox.SandboxTypeE2B}++ got, configID, 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,+ "re-pointing an agent must not move an existing remote session")+}diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.goindex c95b81609..294fae020 100644--- a/internal/application/service/tenant_sandbox_config.go+++ b/internal/application/service/tenant_sandbox_config.go@@ -27,6 +27,7 @@ import ("context"stderrors "errors""fmt"+ "sort""strings""time"@@ -101,7 +102,7 @@ var ErrSandboxConfigNameRequired = stderrors.New("sandbox config name is require// ErrNamedSandboxBackendUnsupported marks a sandbox type that cannot be stored// as a user-facing named backend config.var ErrNamedSandboxBackendUnsupported = stderrors.New(- "named sandbox configs only support cube and e2b backends",+ "named sandbox configs only support cube, e2b, docker and local backends",)// SandboxInventory describes what a config holds and who a change disturbs.@@ -131,6 +132,21 @@ type UpdateSandboxConfigInput struct {Config *types.TenantSandboxConfig}+// SandboxTemplateQueryInput describes an unsaved connection from the settings+// drawer. ConfigID is optional and lets masked credentials resolve against the+// stored row while editing.+type SandboxTemplateQueryInput struct {+ Config *types.TenantSandboxConfig+ ConfigID string+ EnsureStandard bool+}++type SandboxTemplateCatalog struct {+ Templates []sandbox.RemoteTemplate `json:"templates"`+ StandardTemplateID string `json:"standard_template_id,omitempty"`+ Provisioned bool `json:"provisioned"`+}+// SandboxConfigAgentRepo is the slice of the agent repository this service// needs. Agent references are warnings, never grounds for refusing a change.type SandboxConfigAgentRepo interface {@@ -181,7 +197,9 @@ func SanitizeSandboxConfig(}}for _, endpoint := range sandboxConfigEndpoints(merged) {- if err := sandbox.ValidateOutboundURL(endpoint); err != nil {+ if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{+ AllowPrivate: merged.AllowPrivateEndpoints,+ }); err != nil {return nil, err}}@@ -241,8 +259,8 @@ func findWorkspacePolicyRow(return nil}-// WorkspaceScriptsDisabled reports whether agents that rely on the deployment-// default (empty sandbox_config_id) must not execute skill scripts.+// WorkspaceScriptsDisabled reports whether the workspace-wide kill switch is+// active, regardless of which named backend an agent selected.func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(ctx context.Context, tenantID uint64,) (bool, error) {@@ -253,8 +271,8 @@ func (s *TenantSandboxConfigService) WorkspaceScriptsDisabled(return findWorkspacePolicyRow(list) != nil, nil}-// SetWorkspaceScriptsDisabled toggles workspace-level script execution for-// agents that do not point at a named cube/e2b config.+// SetWorkspaceScriptsDisabled toggles script execution for the entire+// workspace, across all named backend types.func (s *TenantSandboxConfigService) SetWorkspaceScriptsDisabled(ctx context.Context, tenantID uint64, disabled bool,) error {@@ -339,6 +357,152 @@ func (s *TenantSandboxConfigService) Get(return entity, nil}+// QueryTemplates reads the provider's template catalog and optionally installs+// the standard WeKnora image when it is absent. This is intentionally driven by+// workspace credentials instead of deployment environment variables.+func (s *TenantSandboxConfigService) QueryTemplates(+ ctx context.Context, tenantID uint64, in SandboxTemplateQueryInput,+) (*SandboxTemplateCatalog, error) {+ var existing *types.TenantSandboxConfig+ if strings.TrimSpace(in.ConfigID) != "" {+ entity, err := s.repo.GetByID(ctx, tenantID, in.ConfigID)+ if err != nil {+ return nil, err+ }+ if entity == nil || types.IsSandboxWorkspacePolicyRow(entity) {+ return nil, apperrors.NewNotFoundError("sandbox config not found")+ }+ existing = entity.Config+ }+ merged := types.MergeSandboxConfigForUpdate(in.Config, existing)+ if merged == nil {+ merged = types.MergeSandboxConfigForUpdate(existing, nil)+ }+ if merged == nil {+ return nil, apperrors.NewBadRequestError("sandbox config is required")+ }++ // Catalog access needs the control-plane connection but does not need a+ // spawn template yet. A private placeholder lets the same effective-config+ // validation protect every other required field without weakening runtime+ // validation.+ switch merged.SandboxType {+ case string(sandbox.SandboxTypeCube):+ if merged.Cube == nil {+ merged.Cube = &types.CubeSandboxConfig{}+ }+ if strings.TrimSpace(merged.Cube.TemplateID) == "" {+ merged.Cube.TemplateID = "__catalog__"+ }+ case string(sandbox.SandboxTypeE2B):+ if merged.E2B == nil {+ merged.E2B = &types.E2BSandboxConfig{}+ }+ if strings.TrimSpace(merged.E2B.TemplateID) == "" {+ merged.E2B.TemplateID = "__catalog__"+ }+ default:+ return nil, apperrors.NewBadRequestError(+ "sandbox template catalog only supports cube and e2b backends")+ }++ for _, endpoint := range sandboxConfigEndpoints(merged) {+ if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{+ AllowPrivate: merged.AllowPrivateEndpoints,+ }); err != nil {+ return nil, err+ }+ }+ effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig())+ if err != nil {+ return nil, err+ }+ client, err := s.newClient(effective)+ if err != nil {+ return nil, err+ }+ catalog, ok := any(client).(sandbox.RemoteTemplateCatalog)+ if !ok {+ return nil, fmt.Errorf("sandbox: provider %q does not expose templates", effective.Type)+ }+ templates, err := catalog.ListTemplates(ctx)+ if err != nil {+ return nil, err+ }+ result := &SandboxTemplateCatalog{Templates: deduplicateSandboxTemplates(templates)}+ for _, item := range result.Templates {+ if item.Standard {+ result.StandardTemplateID = item.ID+ break+ }+ }+ if in.EnsureStandard && result.StandardTemplateID == "" {+ standard, ensureErr := catalog.EnsureStandardTemplate(ctx)+ if ensureErr != nil {+ return nil, ensureErr+ }+ result.Provisioned = true+ result.StandardTemplateID = standard.ID+ result.Templates = deduplicateSandboxTemplates(append(result.Templates, *standard))+ }+ sort.SliceStable(result.Templates, func(i, j int) bool {+ if result.Templates[i].Standard != result.Templates[j].Standard {+ return result.Templates[i].Standard+ }+ return strings.ToLower(result.Templates[i].Name) < strings.ToLower(result.Templates[j].Name)+ })+ return result, nil+}++func deduplicateSandboxTemplates(items []sandbox.RemoteTemplate) []sandbox.RemoteTemplate {+ if len(items) < 2 {+ return items+ }+ result := make([]sandbox.RemoteTemplate, 0, len(items))+ indexByID := make(map[string]int, len(items))+ for _, item := range items {+ id := strings.TrimSpace(item.ID)+ if id == "" {+ result = append(result, item)+ continue+ }+ idx, exists := indexByID[id]+ if !exists {+ indexByID[id] = len(result)+ result = append(result, item)+ continue+ }+ current := &result[idx]+ current.Standard = current.Standard || item.Standard+ if templateStatusRank(item.Status) > templateStatusRank(current.Status) {+ current.Status = item.Status+ current.Version = item.Version+ current.UpdatedAt = item.UpdatedAt+ }+ if strings.TrimSpace(current.Name) == "" ||+ (strings.EqualFold(current.Name, sandbox.StandardTemplateName) && strings.Contains(item.Name, "/")) {+ current.Name = item.Name+ }+ if current.Image == "" {+ current.Image = item.Image+ }+ }+ return result+}++func templateStatusRank(status string) int {+ switch strings.ToLower(strings.TrimSpace(status)) {+ case "ready", "available", "complete", "completed", "success", "succeeded":+ return 3+ case "building", "waiting", "pending", "queued", "processing":+ return 2+ case "failed", "error", "cancelled", "canceled":+ return 1+ default:+ return 0+ }+}+// Inventory answers what changing or deleting this config would disturb.//// An unreachable provider is reported through Unverifiable rather than as andiff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.goindex b96aec545..35593406d 100644--- a/internal/application/service/tenant_sandbox_config_test.go+++ b/internal/application/service/tenant_sandbox_config_test.go@@ -15,7 +15,7 @@ import ("github.com/Tencent/WeKnora/internal/types")-// testGlobalSandboxConfig mirrors a deployment's WEKNORA_SANDBOX_* values. Named+// testGlobalSandboxConfig supplies built-in runtime tuning values. Named// configs inherit none of the provider fields from it; it is here so the service// under test is wired the way production wires it.func testGlobalSandboxConfig() *sandbox.Config {@@ -108,6 +108,16 @@ func TestSandboxIdentityChanged(t *testing.T) {new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),want: false,},+ {+ name: "private endpoint policy changes transport identity",+ old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),+ new: func() *types.TenantSandboxConfig {+ cfg := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)+ cfg.AllowPrivateEndpoints = true+ return cfg+ }(),+ want: true,+ },{// Nothing is inherited, so filling in an endpoint that was blank// really does re-point the config at a different account.@@ -269,12 +279,26 @@ func (s stubAgentRepo) ListNamesBySandboxConfigID(type stubProviderClient struct {inventories [][]sandbox.RemoteSandboxSummary+ templates []sandbox.RemoteTemplate+ ensured *sandbox.RemoteTemplatelistCalls intdeleted []stringdeleteCtxErr error}+func (s *stubProviderClient) ListTemplates(context.Context) ([]sandbox.RemoteTemplate, error) {+ return append([]sandbox.RemoteTemplate(nil), s.templates...), nil+}++func (s *stubProviderClient) EnsureStandardTemplate(context.Context) (*sandbox.RemoteTemplate, error) {+ if s.ensured != nil {+ copy := *s.ensured+ return ©, nil+ }+ return &sandbox.RemoteTemplate{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true}, nil+}+func (s *stubProviderClient) List(ctx context.Context, _ sandbox.RemoteListFilter,) ([]sandbox.RemoteSandboxSummary, error) {@@ -312,6 +336,62 @@ func newTestConfigService(return svc}+func TestQueryTemplatesEnsuresMissingWeKnoraTemplate(t *testing.T) {+ client := &stubProviderClient{+ templates: []sandbox.RemoteTemplate{{ID: "tpl-custom", Name: "custom", Status: "ready"}},+ ensured: &sandbox.RemoteTemplate{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true},+ }+ svc := newTestConfigService(t, &fakeConfigRepo{}, client, stubAgentRepo{})++ result, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "", 300),+ EnsureStandard: true,+ })++ require.NoError(t, err)+ require.True(t, result.Provisioned)+ require.Equal(t, "tpl-weknora", result.StandardTemplateID)+ require.Len(t, result.Templates, 2)+ require.True(t, result.Templates[0].Standard, "standard template should sort first")+}++func TestQueryTemplatesDeduplicatesSameProviderTemplateID(t *testing.T) {+ client := &stubProviderClient{templates: []sandbox.RemoteTemplate{+ {ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true},+ {ID: "tpl-weknora", Name: "project-b89e/weknora", Status: "ready", Standard: true},+ }}+ svc := newTestConfigService(t, &fakeConfigRepo{}, client, stubAgentRepo{})++ result, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "", 300),+ })++ require.NoError(t, err)+ require.Len(t, result.Templates, 1)+ require.Equal(t, "project-b89e/weknora", result.Templates[0].Name)+ require.Equal(t, "ready", result.Templates[0].Status)+ require.Equal(t, "tpl-weknora", result.StandardTemplateID)+}++func TestQueryTemplatesResolvesMaskedStoredCredential(t *testing.T) {+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{+ ID: "cfg-a", TenantID: 7, SandboxType: "e2b",+ Config: e2bCfg("stored-secret", "https://api.e2b.app", "e2b.app", "old", 300),+ }}+ svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, sandbox.DefaultConfig())+ client := &stubProviderClient{templates: []sandbox.RemoteTemplate{{ID: "tpl-a", Name: "a", Status: "ready"}}}+ svc.newClient = func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {+ require.Equal(t, "stored-secret", cfg.E2BAPIKey)+ return client, nil+ }++ _, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{+ ConfigID: "cfg-a",+ Config: e2bCfg(types.RedactedSecretPlaceholder, "https://api.e2b.app", "e2b.app", "", 300),+ })+ require.NoError(t, err)+}+// An identity change while sandboxes are alive must be refused, and the stored// credentials must remain untouched so cleanup stays possible.func TestUpdateRefusesIdentityChangeWhileSandboxesLive(t *testing.T) {@@ -721,15 +801,37 @@ func TestSandboxesStillLiveErrorSupportsErrorsIs(t *testing.T) {require.True(t, stderrors.Is(err, ErrSandboxesStillLive))}-func TestCreateRejectsNonNamedSandboxBackend(t *testing.T) {- svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})+func TestCreateAcceptsStatelessNamedSandboxBackends(t *testing.T) {+ repo := &fakeConfigRepo{}+ svc := newTestConfigService(t, repo, nil, stubAgentRepo{})- _, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{+ local, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{Name: "local-dev",Config: &types.TenantSandboxConfig{SandboxType: "local"},})+ require.NoError(t, err)+ require.Equal(t, "local", local.SandboxType)++ docker, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{+ Name: "docker-dev",+ Config: &types.TenantSandboxConfig{+ SandboxType: "docker",+ Docker: &types.DockerSandboxConfig{Image: "weknora:test"},+ },+ })+ require.NoError(t, err)+ require.Equal(t, "docker", docker.SandboxType)+}- require.ErrorIs(t, err, ErrNamedSandboxBackendUnsupported)+func TestCreateRejectsDockerWithoutImage(t *testing.T) {+ svc := newTestConfigService(t, &fakeConfigRepo{}, nil, stubAgentRepo{})++ _, err := svc.Create(context.Background(), 7, CreateSandboxConfigInput{+ Name: "docker-dev",+ Config: &types.TenantSandboxConfig{SandboxType: "docker"},+ })++ require.ErrorIs(t, err, sandbox.ErrSandboxConfigIncomplete)}func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {diff --git a/internal/application/service/tenant_sandbox_resolve.go b/internal/application/service/tenant_sandbox_resolve.goindex a75961e18..67939a10e 100644--- a/internal/application/service/tenant_sandbox_resolve.go+++ b/internal/application/service/tenant_sandbox_resolve.go@@ -7,8 +7,6 @@ package serviceimport ("context""fmt"- "os"- "strings""time""github.com/Tencent/WeKnora/internal/application/repository"@@ -58,16 +56,11 @@ func (l *tenantSandboxConfigLoader) Load(}// WorkspaceSandboxPolicy reports whether sandbox execution is disabled for the-// entire workspace, including agents bound to named cube/e2b configs.+// entire workspace, including agents bound to any named backend config.type WorkspaceSandboxPolicy interface {WorkspaceScriptsDisabled(ctx context.Context, tenantID uint64) (bool, error)}-func deploymentSandboxDisabled() bool {- mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))- return mode == "" || mode == "disabled"-}-// resolveTenantSandboxForConfig returns the Manager for an explicit config.//// Unlike the previous tenant-only helper this does NOT degrade to the default@@ -77,17 +70,12 @@ func deploymentSandboxDisabled() bool {func resolveTenantSandboxForConfig(ctx context.Context,resolver sandbox.TenantSandboxResolver,- fallback sandbox.Manager,+ _ sandbox.Manager,tenantID uint64,configID string,policy WorkspaceSandboxPolicy,) (sandbox.Manager, error) {- // ① Deployment-wide kill switch (WEKNORA_SANDBOX_MODE empty/disabled).- if deploymentSandboxDisabled() {- return sandbox.NewDisabledManager(), nil- }-- // ② Workspace kill switch — independent of resolver availability.+ // ① Workspace kill switch — independent of resolver availability.if policy != nil && tenantID != 0 {disabled, err := policy.WorkspaceScriptsDisabled(ctx, tenantID)if err != nil {@@ -99,12 +87,13 @@ func resolveTenantSandboxForConfig(}}- // ③ Default path: agents with no named config use the process-wide manager.+ // ② No named workspace config means sandbox execution is disabled. There is+ // no deployment-level provider fallback anymore.if configID == "" || configID == types.SandboxConfigIDGlobalDefault {- return fallback, nil+ return sandbox.NewDisabledManager(), nil}- // ④ Named config: must not silently fall back to the deployment default.+ // ③ Named config: must not silently fall back to another backend.if tenantID == 0 {return nil, fmt.Errorf("sandbox: resolve config %q: missing workspace context", configID)diff --git a/internal/container/container.go b/internal/container/container.goindex 97bcac74e..a0449966d 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -181,10 +181,8 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(mcp.NewMCPManager))must(container.Provide(mcp.NewOAuthManager))- // Sandbox manager (script execution backend for skills). Reads- // WEKNORA_SANDBOX_MODE env var: "docker" | "local" | "cube" | "disabled"- // (default). The Cube mode wires a SessionBoundManager so each Session- // gets its own persistent MicroVM. See internal/sandbox/session_manager.go.+ // Sandbox manager fallback is disabled; executable backends are resolved+ // from named workspace configurations.logger.Debugf(ctx, "[Container] Registering sandbox manager...")must(container.Provide(newSandboxManager))// Per-tenant sandbox backends: the resolver builds a manager per request@@ -192,7 +190,6 @@ func BuildContainer(container *dig.Container) *dig.Container {// for tenants that configured nothing.must(container.Provide(service.NewTenantSandboxConfigLoader))must(container.Provide(newTenantSandboxResolver))- must(container.Provide(newSandboxConfigDefaults))// Business service layerlogger.Debugf(ctx, "[Container] Registering business services...")diff --git a/internal/container/sandbox.go b/internal/container/sandbox.goindex 04a9f0980..115935dee 100644--- a/internal/container/sandbox.go+++ b/internal/container/sandbox.go@@ -1,9 +1,4 @@-// Package container - sandbox provider.-//-// This file wires up the sandbox.Manager singleton that gets injected into-// agent_service and session_service. It is intentionally isolated from-// container.go so environment-variable parsing and provider-specific-// configuration stay out of the main provider table.+// Package container - workspace sandbox provider wiring.package containerimport (@@ -23,151 +18,20 @@ import ("github.com/Tencent/WeKnora/internal/types/interfaces")-// newSandboxManager builds a sandbox.Manager from environment variables.-// Recognised variables:-//-// WEKNORA_SANDBOX_MODE "docker" | "local" | "cube" | "e2b" | "disabled" (default "disabled")-// WEKNORA_SANDBOX_TIMEOUT per-execute timeout in seconds (default 60)-// WEKNORA_SANDBOX_DOCKER_IMAGE custom docker image (docker mode only)-// WEKNORA_SANDBOX_REDIS_NAMESPACE Redis key namespace suffix (default derives from-// WEKNORA_REDIS_NAMESPACE, then "weknora")-// WEKNORA_SANDBOX_CUBE_API_URL CubeAPI endpoint (default http://127.0.0.1:33000)-// WEKNORA_SANDBOX_CUBE_PROXY_URL CubeProxy endpoint (envd) (default http://127.0.0.1:80)-// WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN sandbox routing domain (default cube.app)-// WEKNORA_SANDBOX_CUBE_ENVD_PORT internal envd port (default 49983)-// WEKNORA_SANDBOX_CUBE_API_KEY X-API-Key value (default empty; Cube auth disabled)-// WEKNORA_SANDBOX_CUBE_TEMPLATE template ID (default tpl-2b7911a5c3bb419a8745957a)-// WEKNORA_SANDBOX_CUBE_SANDBOX_TTL Cube-side sandbox timeout, seconds (default 1800)-// WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)-// WEKNORA_SANDBOX_E2B_API_KEY X-API-Key for the E2B backend (required for mode=e2b)-// WEKNORA_SANDBOX_E2B_API_URL E2B control-plane endpoint (default https://api.e2b.app)-// WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN sandbox routing domain (default e2b.app)-// WEKNORA_SANDBOX_E2B_TEMPLATE template ID / alias-// WEKNORA_SANDBOX_E2B_SANDBOX_TTL E2B-side idle timeout, seconds (default 300)-// WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT single HTTP call timeout, seconds (default 30)+// newSandboxManager is deliberately disabled. Every executable backend now+// comes from a named workspace configuration resolved at request time.func newSandboxManager(- redisClient *redis.Client,- sessionRepo interfaces.SessionRepository,+ _ *redis.Client,+ _ interfaces.SessionRepository,) sandbox.Manager {- ctx := context.Background()-- mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))- if mode == "" {- mode = "disabled"- }-- switch mode {- case "docker":- dockerImage := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE")- if dockerImage == "" {- dockerImage = sandbox.DefaultDockerImage- }- m, err := sandbox.NewManagerFromType("docker", true, dockerImage)- if err != nil {- logger.Warnf(ctx, "Failed to initialize Docker sandbox, falling back to disabled: %v", err)- return sandbox.NewDisabledManager()- }- logger.Infof(ctx, "Sandbox configured: mode=docker image=%s", dockerImage)- return m-- case "local":- m, err := sandbox.NewManagerFromType("local", false, "")- if err != nil {- logger.Warnf(ctx, "Failed to initialize local sandbox: %v", err)- return sandbox.NewDisabledManager()- }- logger.Infof(ctx, "Sandbox configured: mode=local")- return m-- case "cube":- return buildCubeManager(ctx, redisClient, sessionRepo)-- case "e2b":- return buildE2BManager(ctx, redisClient, sessionRepo)-- default:- logger.Infof(ctx, "Sandbox configured: mode=disabled")- return sandbox.NewDisabledManager()- }-}--func buildCubeManager(- ctx context.Context,- redisClient *redis.Client,- sessionRepo interfaces.SessionRepository,-) sandbox.Manager {- cfg := sandbox.CubeConfigFromEnv()- // The pool lives as long as this process-wide manager, and its guarded- // dialer keeps the deployment default on the same outbound policy the- // per-tenant resolver enforces.- client, err := sandbox.NewCubeRemoteClientWithPool(cfg, sandbox.NewCubeTransportPool(nil))- if err != nil {- logger.Warnf(ctx, "Failed to build Cube sandbox client: %v (falling back to disabled)", err)- return sandbox.NewDisabledManager()- }- store, storeKind, err := selectSessionBindingStore(redisClient, true)- if err != nil {- logger.Errorf(ctx, "Refusing to start Cube sandbox: %v", err)- return sandbox.NewDisabledManager()- }- m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{- Config: cfg,- Client: client,- Store: store,- Checker: sessionExistenceCheckerFor(sessionRepo),- })- if err != nil {- logger.Warnf(ctx, "Failed to initialize Cube sandbox: %v (falling back to disabled)", err)- return sandbox.NewDisabledManager()- }- logger.Infof(ctx,- "Sandbox configured: mode=cube api=%s proxy=%s domain=%s template=%s binding=%s",- cfg.CubeAPIURL, cfg.CubeProxyURL, cfg.CubeSandboxDomain, cfg.CubeTemplate, storeKind,- )- return m-}--func buildE2BManager(- ctx context.Context,- redisClient *redis.Client,- sessionRepo interfaces.SessionRepository,-) sandbox.Manager {- cfg := sandbox.E2BConfigFromEnv()- client, err := sandbox.NewE2BRemoteClientWithTransport(cfg, sandbox.NewGuardedTransport())- if err != nil {- logger.Warnf(ctx, "Failed to build E2B sandbox client: %v (falling back to disabled)", err)- return sandbox.NewDisabledManager()- }- store, storeKind, err := selectSessionBindingStore(redisClient, true)- if err != nil {- logger.Errorf(ctx, "Refusing to start E2B sandbox: %v", err)- return sandbox.NewDisabledManager()- }- m, err := sandbox.NewSessionBoundManager(sandbox.SessionBoundManagerConfig{- Config: cfg,- Client: client,- Store: store,- Checker: sessionExistenceCheckerFor(sessionRepo),- })- if err != nil {- logger.Warnf(ctx, "Failed to initialize E2B sandbox: %v (falling back to disabled)", err)- return sandbox.NewDisabledManager()- }- logger.Infof(ctx,- "Sandbox configured: mode=e2b api=%s domain=%s template=%s ttl=%s binding=%s",- cfg.E2BAPIURL, cfg.E2BSandboxDomain, cfg.E2BTemplate, cfg.E2BSandboxTTL, storeKind,- )- return m+ return sandbox.NewDisabledManager()}func selectSessionBindingStore(redisClient *redis.Client,requireRedis bool,) (sandbox.SessionSandboxBindingStore, string, error) {- namespace := strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_REDIS_NAMESPACE"))- if namespace == "" {- namespace = strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))- }+ namespace := strings.TrimSpace(os.Getenv("WEKNORA_REDIS_NAMESPACE"))if namespace == "" {namespace = "weknora"}@@ -178,21 +42,12 @@ func selectSessionBindingStore(}return store, "redis", nil}- if requireRedis && !allowMemorySandboxBinding() {- return nil, "", errors.New(- "remote sandbox modes (cube/e2b) require Redis for session binding; " +- "set WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING=true only for single-instance dev",- )- }+ _ = requireRedislogger.Warnf(context.Background(),"[sandbox] No Redis configured, using in-memory binding store (single-instance)")return sandbox.NewMemorySessionSandboxBindingStore(), "memory", nil}-func allowMemorySandboxBinding() bool {- return strings.EqualFold(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING")), "true")-}-// sessionExistenceLookup is the narrow slice of SessionRepository the// session existence checker actually needs. Declaring it here (rather than// depending on interfaces.SessionRepository) keeps the checker easy to test@@ -244,19 +99,15 @@ func (c *repositorySessionExistenceChecker) SessionExists(// buildGlobalSandboxConfig returns the process-wide *sandbox.Config that// per-tenant overrides are merged onto.func buildGlobalSandboxConfig() *sandbox.Config {- return sandbox.DeploymentConfig()-}--// newSandboxConfigDefaults exposes the deployment's inheritable sandbox-// defaults (secret-free) so the settings API can show what a workspace without-// its own overrides actually runs on.-func newSandboxConfigDefaults() *sandbox.ConfigDefaults {- return sandbox.DescribeDefaults(buildGlobalSandboxConfig())+ cfg := sandbox.DefaultConfig()+ cfg.Type = sandbox.SandboxTypeDisabled+ cfg.FallbackEnabled = false+ return cfg}-// newTenantSandboxResolver wires the per-tenant resolver. The process-wide-// manager remains the fallback for tenants that configured nothing, so-// existing deployments are unaffected.+// newTenantSandboxResolver wires the workspace-config resolver. The+// process-wide manager is disabled; agents without a selected config stay+// disabled as well.func newTenantSandboxResolver(defaultManager sandbox.Manager,loader sandbox.TenantSandboxConfigLoader,@@ -265,10 +116,9 @@ func newTenantSandboxResolver() sandbox.TenantSandboxResolver {ctx := context.Background()- // Tenants may configure cube/e2b regardless of the global mode, so the- // resolver needs the same Redis-backed binding guarantees the global- // remote path demands. Without them per-tenant config stays disabled and- // every workspace keeps using the process-wide manager.+ // Tenants may configure any supported backend regardless of process startup+ // mode. Remote configs use this binding store for session persistence;+ // Docker and Local configs remain stateless.store, storeKind, err := selectSessionBindingStore(redisClient, true)if err != nil {logger.Warnf(ctx,diff --git a/internal/container/sandbox_test.go b/internal/container/sandbox_test.goindex c9e1952f4..abbaecb40 100644--- a/internal/container/sandbox_test.go+++ b/internal/container/sandbox_test.go@@ -26,15 +26,7 @@ func TestSelectSessionBindingStorePrefersRedis(t *testing.T) {require.IsType(t, &sandbox.RedisSessionSandboxBindingStore{}, store)}-func TestSelectSessionBindingStoreRequiresRedisForRemoteModes(t *testing.T) {- _, _, err := selectSessionBindingStore(nil, true)- require.Error(t, err)- require.Contains(t, err.Error(), "require Redis")-}--func TestSelectSessionBindingStoreAllowsMemoryWhenOptedIn(t *testing.T) {- t.Setenv("WEKNORA_SANDBOX_ALLOW_MEMORY_BINDING", "true")-+func TestSelectSessionBindingStoreUsesMemoryWithoutRedis(t *testing.T) {store, kind, err := selectSessionBindingStore(nil, true)require.NoError(t, err)require.Equal(t, "memory", kind)diff --git a/internal/handler/sandbox_check.go b/internal/handler/sandbox_check.goindex dc6cfefec..06e13e5ba 100644--- a/internal/handler/sandbox_check.go+++ b/internal/handler/sandbox_check.go@@ -5,6 +5,8 @@ import (stderrors "errors""fmt""net/http"+ "os"+ "path/filepath""strings""time"@@ -26,22 +28,39 @@ type SandboxCheckRequest struct {// ConfigID lets an edit form test stored credentials while overriding only// the fields the admin changed in the drawer.ConfigID string `json:"config_id"`- // Deep additionally creates and destroys one sandbox, which is the only- // way to validate the template ID, Cube's proxy/envd data plane,- // in-sandbox execution, and outbound egress (CN + international probes,- // any one success). It consumes real sandbox time, so it is opt-in.+ // Deep additionally runs a throwaway script. For remote backends this also+ // creates and destroys one sandbox, which is the only way to validate the+ // template ID, data plane, in-sandbox execution, and outbound egress. It may+ // consume real sandbox time, so it is opt-in.Deep bool `json:"deep"`}// SandboxCheckItem is one probe outcome. OK is nil when the probe was not// executed, which distinguishes "skipped" from "failed" in the UI.type SandboxCheckItem struct {- Name string `json:"name"`- OK *bool `json:"ok"`- Message string `json:"message,omitempty"`+ Name string `json:"name"`+ OK *bool `json:"ok"`+ // Message carries free-form provider detail for an executed probe.+ Message string `json:"message,omitempty"`+ // Reason is a stable code explaining why a probe was skipped. It exists so+ // the UI can phrase the skip in the operator's language instead of echoing+ // a server-side sentence.+ Reason string `json:"reason,omitempty"`LatencyMS int64 `json:"latency_ms,omitempty"`}+// Why a probe was not executed. Kept as codes because the operator reads them+// in the frontend, which is localized.+const (+ // The probe needs a real sandbox, so it only runs on an opt-in deep check.+ skipReasonNeedsDeepCheck = "needs_deep_check"+ // An earlier probe failed and this one cannot be reached without it.+ skipReasonControlPlaneUnreachable = "control_plane_unreachable"+ skipReasonEnvironmentUnavailable = "environment_unavailable"+ skipReasonSandboxNotCreated = "sandbox_not_created"+ skipReasonSandboxExecFailed = "sandbox_exec_failed"+)+// SandboxCheckResponse aggregates the probes for one sandbox configuration.type SandboxCheckResponse struct {OK bool `json:"ok"`@@ -62,13 +81,13 @@ func (r *SandboxCheckResponse) add(name string, ok bool, message string, latency}// skip records a probe that was not run; it never affects OK.-func (r *SandboxCheckResponse) skip(name, message string) {- r.Checks = append(r.Checks, SandboxCheckItem{Name: name, OK: nil, Message: message})+func (r *SandboxCheckResponse) skip(name, reason string) {+ r.Checks = append(r.Checks, SandboxCheckItem{Name: name, OK: nil, Reason: reason})}// CheckSandboxConfig tests a sandbox configuration without persisting it.// @Summary 测试沙箱连通性-// @Description 使用当前填写的参数测试沙箱后端连通性,不保存配置;deep=true 会额外创建并销毁一个沙箱+// @Description 使用当前填写的参数测试沙箱后端,不保存配置;deep=true 会执行临时脚本,远端后端还会创建并销毁一个沙箱// @Tags 系统// @Accept json// @Produce json@@ -110,18 +129,26 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {incoming = stored}}+ if !req.Deep {+ incoming = sandboxConnectionCheckConfig(incoming)+ }merged, err := service.SanitizeSandboxConfig(incoming, stored)if err != nil {c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})return}- effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DeploymentConfig())+ effective, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig())if err != nil {c.JSON(http.StatusBadRequest, gin.H{"code": 1, "msg": err.Error()})return}result := &SandboxCheckResponse{OK: true, Provider: string(effective.Type)}+ if effective.Type == sandbox.SandboxTypeDocker || effective.Type == sandbox.SandboxTypeLocal {+ h.runStatelessSandboxCheck(ctx, effective, req.Deep, result)+ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})+ return+ }client, err := sandbox.NewRemoteClientForCheck(effective)if err != nil {@@ -137,7 +164,7 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {latency := time.Since(start).Milliseconds()if healthErr != nil {result.add("api_url_reachable", false, sandboxCheckReason(healthErr), latency)- result.skip("credential_valid", "未检测(控制面不可达)")+ result.skip("credential_valid", skipReasonControlPlaneUnreachable)} else {result.add("api_url_reachable", true, "", latency)result.add("credential_valid", true, "", 0)@@ -151,9 +178,13 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {}if !req.Deep || healthErr != nil {- result.skip("template_exists", "未检测(需完整验证)")- result.skip("sandbox_exec", "未检测(需完整验证)")- result.skip("egress_available", "未检测(需完整验证)")+ reason := skipReasonNeedsDeepCheck+ if healthErr != nil {+ reason = skipReasonControlPlaneUnreachable+ }+ result.skip("template_exists", reason)+ result.skip("sandbox_exec", reason)+ result.skip("egress_available", reason)c.JSON(http.StatusOK, gin.H{"success": true, "data": result})return}@@ -162,6 +193,183 @@ func (h *SystemHandler) CheckSandboxConfig(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"success": true, "data": result})}+// sandboxConnectionCheckConfig supplies a private template placeholder for a+// shallow remote probe. Connectivity is deliberately checked before template+// discovery in the settings wizard, and Health never uses this value.+func sandboxConnectionCheckConfig(cfg *types.TenantSandboxConfig) *types.TenantSandboxConfig {+ if cfg == nil {+ return nil+ }+ copy := *cfg+ switch sandbox.SandboxType(copy.SandboxType) {+ case sandbox.SandboxTypeCube:+ cube := types.CubeSandboxConfig{}+ if copy.Cube != nil {+ cube = *copy.Cube+ }+ if strings.TrimSpace(cube.TemplateID) == "" {+ cube.TemplateID = "__connection_check__"+ }+ copy.Cube = &cube+ case sandbox.SandboxTypeE2B:+ e2b := types.E2BSandboxConfig{}+ if copy.E2B != nil {+ e2b = *copy.E2B+ }+ if strings.TrimSpace(e2b.TemplateID) == "" {+ e2b.TemplateID = "__connection_check__"+ }+ copy.E2B = &e2b+ }+ return ©+}++func (h *SystemHandler) runStatelessSandboxCheck(+ ctx context.Context,+ cfg *sandbox.Config,+ deep bool,+ result *SandboxCheckResponse,+) {+ cfg.FallbackEnabled = false+ mgr, err := sandbox.NewManager(cfg)+ if err != nil {+ result.add("environment_available", false, err.Error(), 0)+ result.skip("sandbox_exec", skipReasonEnvironmentUnavailable)+ return+ }+ defer func() { _ = mgr.Cleanup(context.WithoutCancel(ctx)) }()+ active := mgr.GetSandbox()+ available := active != nil && active.IsAvailable(ctx)+ result.add("environment_available", available, "", 0)+ if !available || !deep {+ reason := skipReasonNeedsDeepCheck+ if !available {+ reason = skipReasonEnvironmentUnavailable+ }+ result.skip("sandbox_exec", reason)+ return+ }++ dir, err := createProbeStagingDir()+ if err != nil {+ result.add("sandbox_exec", false, err.Error(), 0)+ return+ }+ defer func() { _ = os.RemoveAll(dir) }()+ // Docker executes as a non-root user that differs from the WeKnora process+ // owner. The isolated bind-mount directory and probe must be traversable and+ // readable by that user.+ if err := os.Chmod(dir, 0o755); err != nil {+ result.add("sandbox_exec", false, err.Error(), 0)+ return+ }+ path := filepath.Join(dir, "check.sh")+ const script = "#!/bin/sh\nprintf 'weknora-ok\\n'\n"+ if err := os.WriteFile(path, []byte(script), 0o644); err != nil {+ result.add("sandbox_exec", false, err.Error(), 0)+ return+ }+ if err := os.Chmod(path, 0o644); err != nil {+ result.add("sandbox_exec", false, err.Error(), 0)+ return+ }++ start := time.Now()+ execResult, err := mgr.Execute(ctx, &sandbox.ExecuteConfig{+ Script: path,+ ScriptContent: script,+ Timeout: 90 * time.Second,+ })+ latency := time.Since(start).Milliseconds()+ if err != nil {+ result.add("sandbox_exec", false, err.Error(), latency)+ return+ }+ if execResult == nil || !strings.Contains(execResult.Stdout, "weknora-ok") {+ if execResult == nil {+ result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)+ return+ }+ message := describeProbeMismatch(+ execResult.ExitCode, execResult.Killed,+ execResult.Stdout, execResult.Stderr, execResult.Error,+ )+ if cfg.Type == sandbox.SandboxTypeDocker && probeScriptWasInvisible(execResult.Stderr) {+ message += ";容器没有看到挂载进去的脚本,请确认 Docker 运行时共享了目录 " + dir ++ "(Docker Desktop / colima 需要在文件共享设置里包含该路径)"+ }+ result.add("sandbox_exec", false, message, latency)+ return+ }+ result.add("sandbox_exec", true, "", latency)+}++// createProbeStagingDir makes the directory the probe script is bind-mounted+// from. The OS temp dir looks like the obvious home for it but is the wrong+// choice for Docker: on macOS runtimes $TMPDIR lives under /var/folders, which+// the Docker VM does not share, so the mount arrives empty and the probe fails+// where real skill runs — staged under the process working directory, next to+// skills/ — succeed. Stage where the real scripts live and fall back to the temp+// dir only when the working directory is not writable.+func createProbeStagingDir() (string, error) {+ if wd, err := os.Getwd(); err == nil {+ if dir, err := os.MkdirTemp(wd, ".weknora-sandbox-check-*"); err == nil {+ return dir, nil+ }+ }+ return os.MkdirTemp("", "weknora-sandbox-check-*")+}++// probeScriptWasInvisible reports whether the interpreter could not find the+// script at all, which for Docker means the bind mount never carried it into+// the container rather than anything being wrong with the image.+func probeScriptWasInvisible(stderr string) bool {+ lowered := strings.ToLower(stderr)+ return strings.Contains(lowered, "check.sh") &&+ (strings.Contains(lowered, "no such file") ||+ strings.Contains(lowered, "not found") ||+ strings.Contains(lowered, "cannot open"))+}++// describeProbeMismatch reports why the probe script did not print its marker.+// "命令输出与预期不符" on its own hides the exit code and the stderr line that+// normally name the actual problem — a missing interpreter, an image entrypoint+// that swallowed the command, or a bind mount that never reached the Docker VM.+func describeProbeMismatch(exitCode int, killed bool, stdout, stderr, execErr string) string {+ parts := []string{fmt.Sprintf("退出码 %d", exitCode)}+ if killed {+ parts = append(parts, "执行超时被终止")+ }+ switch {+ case firstProbeLine(stderr) != "":+ parts = append(parts, "stderr: "+firstProbeLine(stderr))+ case firstProbeLine(stdout) != "":+ parts = append(parts, "stdout: "+firstProbeLine(stdout))+ default:+ parts = append(parts, "没有任何输出")+ }+ if trimmed := strings.TrimSpace(execErr); trimmed != "" {+ parts = append(parts, trimmed)+ }+ return strings.Join(parts, ";")+}++// firstProbeLine picks the first non-empty line and caps it, so one runaway log+// line cannot flood the check panel.+func firstProbeLine(output string) string {+ for _, line := range strings.Split(output, "\n") {+ trimmed := strings.TrimSpace(line)+ if trimmed == "" {+ continue+ }+ if len(trimmed) > 300 {+ return trimmed[:300] + "…"+ }+ return trimmed+ }+ return ""+}+// runDeepSandboxCheck creates one throwaway sandbox and verifies a command can// run inside it. The sandbox is always deleted, including on failure.func (h *SystemHandler) runDeepSandboxCheck(@@ -182,9 +390,9 @@ func (h *SystemHandler) runDeepSandboxCheck(},})if err != nil {- result.add("template_exists", false, sandboxCheckReason(err), 0)- result.skip("sandbox_exec", "未检测(沙箱未创建)")- result.skip("egress_available", "未检测(沙箱未创建)")+ result.add("template_exists", false, explainSandboxCreateFailure(ctx, client, cfg, err), 0)+ result.skip("sandbox_exec", skipReasonSandboxNotCreated)+ result.skip("egress_available", skipReasonSandboxNotCreated)return}defer func() {@@ -212,11 +420,18 @@ func (h *SystemHandler) runDeepSandboxCheck(switch {case err != nil:result.add("sandbox_exec", false, sandboxCheckReason(err), latency)- result.skip("egress_available", "未检测(沙箱执行失败)")+ result.skip("egress_available", skipReasonSandboxExecFailed)+ return+ case execResult == nil:+ result.add("sandbox_exec", false, "沙箱没有返回执行结果", latency)+ result.skip("egress_available", skipReasonSandboxExecFailed)return- case execResult == nil || !strings.Contains(execResult.Stdout, marker):- result.add("sandbox_exec", false, "命令输出与预期不符", latency)- result.skip("egress_available", "未检测(沙箱执行失败)")+ case !strings.Contains(execResult.Stdout, marker):+ result.add("sandbox_exec", false, describeProbeMismatch(+ execResult.ExitCode, execResult.Killed,+ execResult.Stdout, execResult.Stderr, "",+ ), latency)+ result.skip("egress_available", skipReasonSandboxExecFailed)returndefault:result.add("sandbox_exec", true, "", latency)@@ -288,6 +503,72 @@ func (h *SystemHandler) probeSandboxEgress(}}+// explainSandboxCreateFailure turns a failed sandbox creation into a cause the+// operator can act on.+//+// A 404 from the provider is not proof that the template is gone: the E2B SDK+// discards the response body of any 404 on the create endpoint and substitutes+// a fixed "template not found" sentence, so the message alone cannot tell a+// deleted template apart from one whose build cannot boot yet. The catalog is+// the only place that distinction exists, so it is consulted before blaming the+// template ID the admin just picked from a list.+func explainSandboxCreateFailure(+ ctx context.Context,+ client sandbox.RemoteSandboxClient,+ cfg *sandbox.Config,+ err error,+) string {+ reason := sandboxCheckReason(err)+ var remoteErr *sandbox.RemoteError+ if !stderrors.As(err, &remoteErr) {+ return reason+ }+ // A create-time 404 is classified as InvalidRequest, not NotFound, because+ // for the lifecycle it means "bad argument" rather than "sandbox is gone".+ // Diagnosis needs the status itself.+ if remoteErr.Kind != sandbox.RemoteErrorKindNotFound &&+ remoteErr.StatusCode != http.StatusNotFound {+ return reason+ }+ templateID := strings.TrimSpace(sandbox.EffectiveTemplateID(cfg))+ catalog, ok := client.(sandbox.RemoteTemplateCatalog)+ if !ok || templateID == "" {+ return reason+ }+ templates, listErr := catalog.ListTemplates(ctx)+ if listErr != nil {+ logger.Warnf(ctx, "[SandboxCheck] template lookup after create 404 failed: %v", listErr)+ return reason+ }+ for _, tpl := range templates {+ if tpl.ID != templateID && !strings.EqualFold(tpl.Name, templateID) {+ continue+ }+ if tpl.Status == sandbox.TemplateStatusUntagged {+ return fmt.Sprintf(+ "模板 %s 的构建已完成,但没有一个构建带上 %q 标签,创建沙箱时无法解析;"++ "请重新构建该模板(删除后由 WeKnora 重新创建即可)",+ templateID, sandbox.DefaultE2BTemplateTag,+ )+ }+ if tpl.Status == "ready" || tpl.Status == "" {+ return fmt.Sprintf(+ "模板 %s 在列表中已就绪,但集群拒绝创建沙箱(HTTP 404);"++ "通常是构建快照尚未生效,请稍后重试或重新构建模板",+ templateID,+ )+ }+ return fmt.Sprintf(+ "模板 %s 存在,但构建状态为 %s,还不能启动沙箱;请等待构建完成或查看构建日志",+ templateID, tpl.Status,+ )+ }+ return fmt.Sprintf(+ "当前 API Key 看不到模板 %s:模板可能已删除,或该 Key 属于其他团队/集群",+ templateID,+ )+}+// shellSingleQuote wraps s for safe inclusion in a single-quoted shell string.func shellSingleQuote(s string) string {return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"diff --git a/internal/handler/sandbox_check_test.go b/internal/handler/sandbox_check_test.gonew file mode 100644index 000000000..e61fb9198--- /dev/null+++ b/internal/handler/sandbox_check_test.go@@ -0,0 +1,40 @@+package handler++import (+ "context"+ "testing"++ "github.com/stretchr/testify/require"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+)++func TestSandboxConnectionCheckConfigAllowsTemplateDiscoveryAfterConnection(t *testing.T) {+ incoming := &types.TenantSandboxConfig{+ SandboxType: "e2b",+ E2B: &types.E2BSandboxConfig{APIKey: "key"},+ }++ got := sandboxConnectionCheckConfig(incoming)++ require.Equal(t, "__connection_check__", got.E2B.TemplateID)+ require.Empty(t, incoming.E2B.TemplateID, "the submitted form must not be mutated")+}++func TestRunStatelessSandboxCheckLocal(t *testing.T) {+ cfg := sandbox.DefaultConfig()+ cfg.Type = sandbox.SandboxTypeLocal+ result := &SandboxCheckResponse{OK: true, Provider: string(cfg.Type)}++ (&SystemHandler{}).runStatelessSandboxCheck(context.Background(), cfg, true, result)++ require.True(t, result.OK)+ require.Len(t, result.Checks, 2)+ require.Equal(t, "environment_available", result.Checks[0].Name)+ require.NotNil(t, result.Checks[0].OK)+ require.True(t, *result.Checks[0].OK)+ require.Equal(t, "sandbox_exec", result.Checks[1].Name)+ require.NotNil(t, result.Checks[1].OK)+ require.True(t, *result.Checks[1].OK)+}diff --git a/internal/handler/sandbox_config.go b/internal/handler/sandbox_config.goindex edfafa28c..240cb42ae 100644--- a/internal/handler/sandbox_config.go+++ b/internal/handler/sandbox_config.go@@ -24,18 +24,45 @@ type sandboxConfigService interface {Inventory(context.Context, uint64, string) (service.SandboxInventory, error)WorkspaceScriptsDisabled(context.Context, uint64) (bool, error)SetWorkspaceScriptsDisabled(context.Context, uint64, bool) error+ QueryTemplates(context.Context, uint64, service.SandboxTemplateQueryInput) (*service.SandboxTemplateCatalog, error)+}++type sandboxTemplateQueryRequest struct {+ Config *types.TenantSandboxConfig `json:"config"`+ ConfigID string `json:"config_id,omitempty"`+ EnsureStandard bool `json:"ensure_standard"`+}++// QueryTemplates returns the templates visible through an unsaved workspace+// connection. When requested, it also starts provisioning the standard+// WeKnora image if that cluster does not have one yet.+func (h *SandboxConfigHandler) QueryTemplates(c *gin.Context) {+ var req sandboxTemplateQueryRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.Error(apperrors.NewBadRequestError(err.Error()))+ return+ }+ result, err := h.service.QueryTemplates(c.Request.Context(), sandboxConfigTenantID(c),+ service.SandboxTemplateQueryInput{+ Config: req.Config,+ ConfigID: req.ConfigID,+ EnsureStandard: req.EnsureStandard,+ })+ if err != nil {+ respondSandboxConfigServiceError(c, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})}type SandboxConfigHandler struct {- service sandboxConfigService- defaults *sandbox.ConfigDefaults+ service sandboxConfigService}func NewSandboxConfigHandler(service *service.TenantSandboxConfigService,- defaults *sandbox.ConfigDefaults,) *SandboxConfigHandler {- return &SandboxConfigHandler{service: service, defaults: defaults}+ return &SandboxConfigHandler{service: service}}type sandboxConfigRequest struct {@@ -143,7 +170,7 @@ func respondSandboxConfigServiceError(c *gin.Context, err error) {// List godoc// @Summary List sandbox configs-// @Description List workspace sandbox backend configs with credentials masked and deployment defaults included.+// @Description List workspace sandbox backend configs with credentials masked.// @Tags SandboxConfig// @Produce json// @Success 200 {object} map[string]interface{} "Sandbox configs and defaults"@@ -171,7 +198,6 @@ func (h *SandboxConfigHandler) List(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"success": true,"data": data,- "defaults": h.defaults,"workspace_scripts_disabled": disabled,})}@@ -180,7 +206,7 @@ type workspacePolicyRequest struct {ScriptsDisabled bool `json:"scripts_disabled"`}-// SetWorkspacePolicy toggles script execution for agents that use the deployment default.+// SetWorkspacePolicy toggles script execution for the whole workspace.func (h *SandboxConfigHandler) SetWorkspacePolicy(c *gin.Context) {var req workspacePolicyRequestif err := c.ShouldBindJSON(&req); err != nil {diff --git a/internal/handler/sandbox_config_test.go b/internal/handler/sandbox_config_test.goindex 01ddaf830..3d308cf59 100644--- a/internal/handler/sandbox_config_test.go+++ b/internal/handler/sandbox_config_test.go@@ -110,7 +110,7 @@ func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {gin.SetMode(gin.TestMode)svc := &fakeSandboxConfigService{}- h := &SandboxConfigHandler{service: svc, defaults: &sandbox.ConfigDefaults{}}+ h := &SandboxConfigHandler{service: svc}router := gin.New()router.Use(func(c *gin.Context) {c.Set(types.TenantIDContextKey.String(), uint64(42))@@ -247,3 +247,11 @@ func (s *fakeSandboxConfigService) SetWorkspaceScriptsDisabled() error {return nil}++func (s *fakeSandboxConfigService) QueryTemplates(+ context.Context,+ uint64,+ service.SandboxTemplateQueryInput,+) (*service.SandboxTemplateCatalog, error) {+ return &service.SandboxTemplateCatalog{}, nil+}diff --git a/internal/handler/skill_handler.go b/internal/handler/skill_handler.goindex 56395e7a6..d0930b769 100644--- a/internal/handler/skill_handler.go+++ b/internal/handler/skill_handler.go@@ -2,7 +2,6 @@ package handlerimport ("net/http"- "os""github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/logger"@@ -58,15 +57,11 @@ func (h *SkillHandler) ListSkills(c *gin.Context) {})}- // skills_available: true only when sandbox is enabled (docker or local), so frontend can hide/disable Skills UI- sandboxMode := os.Getenv("WEKNORA_SANDBOX_MODE")- skillsAvailable := sandboxMode != "" && sandboxMode != "disabled"-- logger.Infof(ctx, "skills_available: %v, sandboxMode: %s", skillsAvailable, sandboxMode)-c.JSON(http.StatusOK, gin.H{- "success": true,- "data": response,- "skills_available": skillsAvailable,+ "success": true,+ "data": response,+ // Skills can be selected before a workspace sandbox is configured; the+ // execution path remains disabled until the agent chooses a config.+ "skills_available": true,})}diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.goindex 3fd151c28..901d7cb83 100644--- a/internal/router/router_api_key_capabilities_test.go+++ b/internal/router/router_api_key_capabilities_test.go@@ -393,6 +393,7 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {}{{http.MethodGet, "/api/v1/sandbox-configs"},{http.MethodPost, "/api/v1/sandbox-configs"},+ {http.MethodPost, "/api/v1/sandbox-configs/templates/query"},{http.MethodGet, "/api/v1/sandbox-configs/:id"},{http.MethodPut, "/api/v1/sandbox-configs/:id"},{http.MethodDelete, "/api/v1/sandbox-configs/:id"},diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.goindex 98aaea1a4..3631273b2 100644--- a/internal/router/routes_infra.go+++ b/internal/router/routes_infra.go@@ -52,6 +52,7 @@ func RegisterSandboxConfigRoutes({configs.GET("", g.Viewer(), h.List)configs.PUT("/workspace-policy", g.Admin(), h.SetWorkspacePolicy)+ configs.POST("/templates/query", g.Admin(), h.QueryTemplates)configs.POST("", g.Admin(), h.Create)configs.GET("/:id", g.Viewer(), h.Get)configs.PUT("/:id", g.Admin(), h.Update)diff --git a/internal/sandbox/check_client_guard_test.go b/internal/sandbox/check_client_guard_test.goindex 154eb49de..184293bc9 100644--- a/internal/sandbox/check_client_guard_test.go+++ b/internal/sandbox/check_client_guard_test.go@@ -16,9 +16,6 @@ import (// link-local at dial time, and they must do so even under the private-endpoint// opt-in that self-hosted Cube deployments need.func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {- // The opt-in is deliberately ON: link-local must stay blocked regardless.- t.Setenv(AllowPrivateEndpointsEnv, "true")-const metadata = "http://169.254.169.254"for _, tc := range []struct {@@ -28,20 +25,22 @@ func TestNewRemoteClientForCheckRefusesLinkLocalAtDial(t *testing.T) {{name: "cube",cfg: &Config{- Type: SandboxTypeCube,- CubeAPIURL: metadata,- CubeProxyURL: metadata,- CubeSandboxDomain: "cube.app",- CubeTemplate: "tpl-test",+ AllowPrivateEndpoints: true,+ Type: SandboxTypeCube,+ CubeAPIURL: metadata,+ CubeProxyURL: metadata,+ CubeSandboxDomain: "cube.app",+ CubeTemplate: "tpl-test",},},{name: "e2b",cfg: &Config{- Type: SandboxTypeE2B,- E2BAPIKey: "key-test",- E2BAPIURL: metadata,- E2BTemplate: "base",+ AllowPrivateEndpoints: true,+ Type: SandboxTypeE2B,+ E2BAPIKey: "key-test",+ E2BAPIURL: metadata,+ E2BTemplate: "base",},},} {diff --git a/internal/sandbox/config_defaults.go b/internal/sandbox/config_defaults.godeleted file mode 100644index 9828b497f..000000000--- a/internal/sandbox/config_defaults.go+++ /dev/null@@ -1,65 +0,0 @@-// Package sandbox: description of the process-wide defaults a tenant inherits.-//-// A tenant that has not overridden a field runs on the deployment's global-// WEKNORA_SANDBOX_* configuration. The settings UI has to show what is actually-// in effect, otherwise an empty override set looks indistinguishable from-// "disabled" — and saving that impression would silently disable the sandbox.-//-// Secrets are deliberately never included here; only whether one is present.-package sandbox--// ProviderDefaults is the inheritable, non-secret configuration of one backend.-type ProviderDefaults struct {- APIURL string `json:"api_url,omitempty"`- ProxyURL string `json:"proxy_url,omitempty"`- SandboxDomain string `json:"sandbox_domain,omitempty"`- TemplateID string `json:"template_id,omitempty"`- APIKeyConfigured bool `json:"api_key_configured"`- HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`- SandboxTTLSec int `json:"sandbox_ttl_seconds,omitempty"`-}--// ConfigDefaults mirrors types.TenantSandboxConfig's shape so the UI can render-// inherited values as placeholders next to the tenant's own overrides.-type ConfigDefaults struct {- // SandboxType is the backend a tenant gets when it sets no override.- SandboxType string `json:"sandbox_type"`- DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`- DockerImage string `json:"docker_image,omitempty"`- Cube *ProviderDefaults `json:"cube,omitempty"`- E2B *ProviderDefaults `json:"e2b,omitempty"`-}--// DescribeDefaults projects a resolved global Config into its inheritable,-// secret-free description.-func DescribeDefaults(cfg *Config) *ConfigDefaults {- if cfg == nil {- return &ConfigDefaults{SandboxType: string(SandboxTypeDisabled)}- }- defaults := &ConfigDefaults{- SandboxType: string(cfg.Type),- DefaultTimeoutSec: int(cfg.DefaultTimeout.Seconds()),- DockerImage: cfg.DockerImage,- }- // Describe both remote backends regardless of the active mode: an admin- // switching a workspace to the other one still needs to see what it would- // inherit.- defaults.Cube = &ProviderDefaults{- APIURL: cfg.CubeAPIURL,- ProxyURL: cfg.CubeProxyURL,- SandboxDomain: cfg.CubeSandboxDomain,- TemplateID: cfg.CubeTemplate,- APIKeyConfigured: cfg.CubeAPIKey != "",- HTTPTimeoutSec: int(cfg.CubeHTTPTimeout.Seconds()),- SandboxTTLSec: int(cfg.CubeSandboxTTL.Seconds()),- }- defaults.E2B = &ProviderDefaults{- APIURL: cfg.E2BAPIURL,- SandboxDomain: cfg.E2BSandboxDomain,- TemplateID: cfg.E2BTemplate,- APIKeyConfigured: cfg.E2BAPIKey != "",- HTTPTimeoutSec: int(cfg.E2BHTTPTimeout.Seconds()),- SandboxTTLSec: int(cfg.E2BSandboxTTL.Seconds()),- }- return defaults-}diff --git a/internal/sandbox/config_identity.go b/internal/sandbox/config_identity.goindex 38634598d..984ce99ca 100644--- a/internal/sandbox/config_identity.go+++ b/internal/sandbox/config_identity.go@@ -25,7 +25,8 @@ import (// SandboxIdentity is the comparable projection of a config: two configs with// equal identities can operate each other's sandboxes.type SandboxIdentity struct {- Provider string+ Provider string+ AllowPrivateEndpoints bool// Control plane - whether an existing sandbox can still be reclaimed.APIURL string@@ -53,7 +54,10 @@ func IdentityOf(tenantCfg *types.TenantSandboxConfig) SandboxIdentity {if tenantCfg == nil {return SandboxIdentity{}}- identity := SandboxIdentity{Provider: tenantCfg.SandboxType}+ identity := SandboxIdentity{+ Provider: tenantCfg.SandboxType,+ AllowPrivateEndpoints: tenantCfg.AllowPrivateEndpoints,+ }switch SandboxType(tenantCfg.SandboxType) {case SandboxTypeCube:if cube := tenantCfg.Cube; cube != nil {diff --git a/internal/sandbox/config_identity_test.go b/internal/sandbox/config_identity_test.goindex ab11f28b3..867016c8e 100644--- a/internal/sandbox/config_identity_test.go+++ b/internal/sandbox/config_identity_test.go@@ -10,7 +10,7 @@ import (// Identity comes from the stored row alone. Nothing about the deployment can// change it, which is what makes "did this edit strand a sandbox" answerable-// without reaching for WEKNORA_SANDBOX_*.+// without reaching for process-level sandbox configuration.func TestIdentityOfReadsStoredFieldsOnly(t *testing.T) {identity := IdentityOf(&types.TenantSandboxConfig{SandboxType: "e2b",diff --git a/internal/sandbox/config_required.go b/internal/sandbox/config_required.goindex 49b9f501a..36653804a 100644--- a/internal/sandbox/config_required.go+++ b/internal/sandbox/config_required.go@@ -1,11 +1,8 @@// Package sandbox: what a named backend config must carry on its own.//-// A named config is self-contained. Nothing is inherited from the deployment-// WEKNORA_SANDBOX_* baseline, which exists only to serve agents that selected no-// config at all. The trade for that clarity is that every value the provider-// client cannot synthesize has to be present in the config itself, so this file-// names those values once and both the save path and the resolve path check-// against it.+// A named config is self-contained. Every value the provider client cannot+// synthesize has to be present in the workspace config itself, so this file+// names those values once and both save and resolve paths check against it.//// Two classes are deliberately NOT required://@@ -33,8 +30,8 @@ var ErrSandboxConfigIncomplete = errors.New("sandbox: config is missing required// MissingRequiredFields lists the fields cfg fails to supply for its own// provider, named after the JSON keys the API and the settings form use so the-// message can be surfaced without translation. Backends that hold no endpoint-// of their own (docker / local / disabled) require nothing.+// message can be surfaced without translation. Local and disabled hold no+// backend-specific values; Docker must explicitly name its image.func MissingRequiredFields(cfg *Config) []string {if cfg == nil {return nil@@ -54,6 +51,8 @@ func MissingRequiredFields(cfg *Config) []string {case SandboxTypeE2B:require("api_key", cfg.E2BAPIKey)require("template_id", cfg.E2BTemplate)+ case SandboxTypeDocker:+ require("image", cfg.DockerImage)}return missing}diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.goindex ae86bc89b..34d063efd 100644--- a/internal/sandbox/cube_remote_client.go+++ b/internal/sandbox/cube_remote_client.go@@ -141,6 +141,58 @@ func (c *CubeRemoteClient) Health(ctx context.Context) error {return nil}+func (c *CubeRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {+ items, err := c.client.ListTemplates(ctx)+ if err != nil {+ return nil, normalizeCubeError("ListTemplates", err)+ }+ result := make([]RemoteTemplate, 0, len(items))+ for _, item := range items {+ name := strings.TrimSpace(item.Name)+ if name == "" {+ name = item.TemplateID+ }+ result = append(result, RemoteTemplate{+ ID: item.TemplateID,+ Name: name,+ Status: item.Status,+ Version: item.Version,+ Image: item.ImageInfo,+ CreatedAt: item.CreatedAt,+ Standard: isStandardTemplate(name),+ })+ }+ return result, nil+}++func (c *CubeRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {+ items, err := c.ListTemplates(ctx)+ if err != nil {+ return nil, err+ }+ for i := range items {+ if items[i].Standard {+ return &items[i], nil+ }+ }+ job, err := c.client.BuildTemplate(ctx, cubesandbox.BuildTemplateOptions{+ Image: DefaultDockerImage,+ Name: StandardTemplateName,+ WritableLayerSize: "1G",+ ExposedPorts: []uint16{49983},+ })+ if err != nil {+ return nil, normalizeCubeError("EnsureStandardTemplate", err)+ }+ return &RemoteTemplate{+ ID: job.TemplateID,+ Name: StandardTemplateName,+ Status: job.Status,+ Image: DefaultDockerImage,+ Standard: true,+ }, nil+}+func (c *CubeRemoteClient) Create(ctx context.Context,request RemoteCreateRequest,diff --git a/internal/sandbox/cube_transport.go b/internal/sandbox/cube_transport.goindex d8ce45055..a189dcad0 100644--- a/internal/sandbox/cube_transport.go+++ b/internal/sandbox/cube_transport.go@@ -35,6 +35,7 @@ import (// One instance lives for the process; clients built from it come and go.type CubeTransportPool struct {control http.RoundTripper+ policy OutboundURLPolicy// data maps a proxy "host:port" to the transport that dials it.data sync.Map@@ -43,10 +44,14 @@ type CubeTransportPool struct {// NewCubeTransportPool returns a pool whose control plane rides control.// A nil control transport installs a guarded one.func NewCubeTransportPool(control http.RoundTripper) *CubeTransportPool {+ return NewCubeTransportPoolWithPolicy(control, DefaultOutboundURLPolicy())+}++func NewCubeTransportPoolWithPolicy(control http.RoundTripper, policy OutboundURLPolicy) *CubeTransportPool {if control == nil {- control = NewGuardedTransport()+ control = NewGuardedTransportWithPolicy(policy)}- return &CubeTransportPool{control: control}+ return &CubeTransportPool{control: control, policy: policy}}// RoundTripperFor returns the transport a client built from cfg should use.@@ -68,7 +73,7 @@ func (p *CubeTransportPool) dataTransport(target string) http.RoundTripper {if existing, ok := p.data.Load(target); ok {return existing.(http.RoundTripper)}- actual, _ := p.data.LoadOrStore(target, newCubeDataTransport(target))+ actual, _ := p.data.LoadOrStore(target, newCubeDataTransportWithPolicy(target, p.policy))return actual.(http.RoundTripper)}@@ -76,10 +81,14 @@ func (p *CubeTransportPool) dataTransport(target string) http.RoundTripper {// mirroring the SDK's proxy rewrite while adding the outbound address guard// the SDK has no notion of.func newCubeDataTransport(target string) *http.Transport {+ return newCubeDataTransportWithPolicy(target, DefaultOutboundURLPolicy())+}++func newCubeDataTransportWithPolicy(target string, policy OutboundURLPolicy) *http.Transport {dialer := &net.Dialer{Timeout: 10 * time.Second,KeepAlive: 30 * time.Second,- Control: SafeDialControl,+ Control: SafeDialControlForPolicy(policy),}return &http.Transport{// The proxy is addressed directly; an ambient HTTP proxy woulddiff --git a/internal/sandbox/cube_transport_test.go b/internal/sandbox/cube_transport_test.goindex 0fd453be7..af465deb7 100644--- a/internal/sandbox/cube_transport_test.go+++ b/internal/sandbox/cube_transport_test.go@@ -36,8 +36,6 @@ func (c *countingRoundTripper) seen() []string {// rewrite, which is exactly the regression this guards: the proxy has to see// the request, and it has to see the sandbox authority in the Host header.func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {- t.Setenv(AllowPrivateEndpointsEnv, "true")-api := newCubeMockServer(t)var mu sync.Mutex@@ -51,10 +49,12 @@ func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {t.Cleanup(proxy.Close)cfg := testConfig(t, api)+ cfg.AllowPrivateEndpoints = truecfg.CubeProxyURL = proxy.URL- control := &countingRoundTripper{next: NewGuardedTransport()}- client, err := NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(control))+ policy := OutboundURLPolicy{AllowPrivate: true}+ control := &countingRoundTripper{next: NewGuardedTransportWithPolicy(policy)}+ client, err := NewCubeRemoteClientWithPool(cfg, NewCubeTransportPoolWithPolicy(control, policy))require.NoError(t, err)ctx := context.Background()@@ -91,7 +91,10 @@ func TestCubeTransportPoolRoutesDataPlaneThroughProxy(t *testing.T) {// Configs pointing at the same proxy must share one pool - otherwise building// a client per request pools nothing.func TestCubeTransportPoolReusesTransportPerProxyEndpoint(t *testing.T) {- pool := NewCubeTransportPool(NewGuardedTransport())+ pool := NewCubeTransportPoolWithPolicy(+ NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),+ OutboundURLPolicy{AllowPrivate: true},+ )first := pool.RoundTripperFor(&Config{CubeProxyURL: "http://127.0.0.1:8080",diff --git a/internal/sandbox/defaults.go b/internal/sandbox/defaults.godeleted file mode 100644index 6c3696bc9..000000000--- a/internal/sandbox/defaults.go+++ /dev/null@@ -1,189 +0,0 @@-// Package sandbox: configuration defaults and deployment baseline.-//-// DeploymentConfig reads WEKNORA_SANDBOX_* into the process-wide baseline. That-// baseline backs agents which selected no named config; it is NOT merged into-// named configs, so the built-in endpoint constants below stay on this path only-// (see tenant_config.go for why).-//-// The provider defaults come in two flavours. Deployment defaults fill endpoints-// and templates and exist so a developer can run `WEKNORA_SANDBOX_MODE=cube` with-// an empty .env. Runtime defaults fill TTLs and HTTP timeouts and are safe-// anywhere, because those have meaningful built-in values while an endpoint does-// not.-package sandbox--import (- "os"- "strconv"- "strings"- "time"-)--// DeploymentConfig returns the process-wide *Config built from WEKNORA_SANDBOX_*.-func DeploymentConfig() *Config {- mode := strings.ToLower(strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_MODE")))- switch mode {- case "cube":- return cubeConfigFromEnv()- case "e2b":- return e2bConfigFromEnv()- case "docker":- cfg := DefaultConfig()- cfg.Type = SandboxTypeDocker- if v := os.Getenv("WEKNORA_SANDBOX_DOCKER_IMAGE"); v != "" {- cfg.DockerImage = v- }- return cfg- case "local":- cfg := DefaultConfig()- cfg.Type = SandboxTypeLocal- return cfg- default:- cfg := DefaultConfig()- cfg.Type = SandboxTypeDisabled- return cfg- }-}--// CubeConfigFromEnv assembles a Cube *Config from WEKNORA_SANDBOX_CUBE_* env vars.-func CubeConfigFromEnv() *Config {- return cubeConfigFromEnv()-}--// E2BConfigFromEnv assembles an E2B *Config from WEKNORA_SANDBOX_E2B_* env vars.-func E2BConfigFromEnv() *Config {- return e2bConfigFromEnv()-}--func cubeConfigFromEnv() *Config {- cfg := DefaultConfig()- cfg.Type = SandboxTypeCube- cfg.FallbackEnabled = false-- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_API_URL"); v != "" {- cfg.CubeAPIURL = v- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_PROXY_URL"); v != "" {- cfg.CubeProxyURL = v- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_SANDBOX_DOMAIN"); v != "" {- cfg.CubeSandboxDomain = v- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_API_KEY"); v != "" {- cfg.CubeAPIKey = v- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_TEMPLATE"); v != "" {- cfg.CubeTemplate = v- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_SANDBOX_TTL"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.CubeSandboxTTL = time.Duration(n) * time.Second- }- }- if v := os.Getenv("WEKNORA_SANDBOX_CUBE_HTTP_TIMEOUT"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.CubeHTTPTimeout = time.Duration(n) * time.Second- }- }- if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.DefaultTimeout = time.Duration(n) * time.Second- }- }- // After the environment so an explicit value always wins.- applyCubeDeploymentDefaults(cfg)- applyCubeRuntimeDefaults(cfg)- return cfg-}--func e2bConfigFromEnv() *Config {- cfg := DefaultConfig()- cfg.Type = SandboxTypeE2B- cfg.FallbackEnabled = false-- if v := os.Getenv("WEKNORA_SANDBOX_E2B_API_KEY"); v != "" {- cfg.E2BAPIKey = v- }- if v := os.Getenv("WEKNORA_SANDBOX_E2B_API_URL"); v != "" {- cfg.E2BAPIURL = v- }- if v := os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN"); v != "" {- cfg.E2BSandboxDomain = v- }- if v := os.Getenv("WEKNORA_SANDBOX_E2B_TEMPLATE"); v != "" {- cfg.E2BTemplate = v- }- if v := os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_TTL"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.E2BSandboxTTL = time.Duration(n) * time.Second- }- }- if v := os.Getenv("WEKNORA_SANDBOX_E2B_HTTP_TIMEOUT"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.E2BHTTPTimeout = time.Duration(n) * time.Second- }- }- if v := os.Getenv("WEKNORA_SANDBOX_TIMEOUT"); v != "" {- if n, err := strconv.Atoi(v); err == nil && n > 0 {- cfg.DefaultTimeout = time.Duration(n) * time.Second- }- }- applyE2BRuntimeDefaults(cfg)- return cfg-}--// applyCubeDeploymentDefaults fills the Cube endpoint, domain and template with-// the built-in single-node values so `WEKNORA_SANDBOX_MODE=cube` works out of the-// box on a developer machine.-//-// It is reachable from the deployment baseline only. Named configs must not see-// these constants: inheriting them is how a workspace config ends up dialling-// 127.0.0.1 instead of being told which field it forgot.-func applyCubeDeploymentDefaults(cfg *Config) {- if cfg == nil {- return- }- if cfg.CubeAPIURL == "" {- cfg.CubeAPIURL = DefaultCubeAPIURL- }- if cfg.CubeProxyURL == "" {- cfg.CubeProxyURL = DefaultCubeProxyURL- }- if cfg.CubeSandboxDomain == "" {- cfg.CubeSandboxDomain = DefaultCubeSandboxDomain- }- if cfg.CubeTemplate == "" {- cfg.CubeTemplate = DefaultCubeTemplate- }-}--// applyCubeRuntimeDefaults fills the Cube tuning fields downstream code relies-// on being non-zero. Unlike the endpoint defaults these are safe everywhere:-// a TTL or an HTTP timeout has a sane built-in value, an endpoint does not.-// Safe to call multiple times.-func applyCubeRuntimeDefaults(cfg *Config) {- if cfg == nil {- return- }- if cfg.CubeSandboxTTL <= 0 {- cfg.CubeSandboxTTL = DefaultCubeSandboxTTL- }- if cfg.CubeHTTPTimeout <= 0 {- cfg.CubeHTTPTimeout = DefaultCubeHTTPTimeout- }-}--// applyE2BRuntimeDefaults is applyCubeRuntimeDefaults for E2B. There is no-// applyE2BDeploymentDefaults: go-e2b resolves its own API base URL and sandbox-// domain, and it ships no template ID that would work for anyone.-func applyE2BRuntimeDefaults(cfg *Config) {- if cfg == nil {- return- }- if cfg.E2BSandboxTTL <= 0 {- cfg.E2BSandboxTTL = DefaultE2BSandboxTTL- }- if cfg.E2BHTTPTimeout <= 0 {- cfg.E2BHTTPTimeout = DefaultE2BHTTPTimeout- }-}diff --git a/internal/sandbox/docker.go b/internal/sandbox/docker.goindex 11e82a5cd..9f34b6773 100644--- a/internal/sandbox/docker.go+++ b/internal/sandbox/docker.go@@ -60,6 +60,12 @@ func (s *DockerSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*Ex// Create context with timeoutexecCtx, cancel := context.WithTimeout(ctx, timeout)defer cancel()+ // Managers are resolved from workspace configuration on demand, so an+ // asynchronous pre-pull would race the first execution and start duplicate+ // pulls on every resolve. Make image readiness part of the execution result.+ if err := s.EnsureImage(execCtx); err != nil {+ return nil, err+ }// Build docker run commandargs := s.buildDockerArgs(config)@@ -195,8 +201,6 @@ func (s *DockerSandbox) ImageExists(ctx context.Context) bool {}// EnsureImage pulls the Docker image if it doesn't exist locally.-// This is intended to be called during initialization so the image is-// ready before the first script execution.func (s *DockerSandbox) EnsureImage(ctx context.Context) error {if s.ImageExists(ctx) {return nildiff --git a/internal/sandbox/e2b_integration_test.go b/internal/sandbox/e2b_integration_test.goindex 2880ca4d3..6c27d50a8 100644--- a/internal/sandbox/e2b_integration_test.go+++ b/internal/sandbox/e2b_integration_test.go@@ -197,11 +197,11 @@ func TestE2BIntegrationLifecycleParity(t *testing.T) {func e2bIntegrationConfig(t *testing.T) *Config {t.Helper()apiKey := firstNonEmptyEnvironment(- "WEKNORA_SANDBOX_E2B_API_KEY",+ "E2B_INTEGRATION_API_KEY","E2B_API_KEY",)template := firstNonEmptyEnvironment(- "WEKNORA_SANDBOX_E2B_TEMPLATE",+ "E2B_INTEGRATION_TEMPLATE","E2B_TEMPLATE",)if apiKey == "" || template == "" {@@ -212,8 +212,8 @@ func e2bIntegrationConfig(t *testing.T) *Config {cfg.Type = SandboxTypeE2Bcfg.FallbackEnabled = falsecfg.E2BAPIKey = apiKey- cfg.E2BAPIURL = strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_E2B_API_URL"))- cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("WEKNORA_SANDBOX_E2B_SANDBOX_DOMAIN"))+ cfg.E2BAPIURL = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_API_URL"))+ cfg.E2BSandboxDomain = strings.TrimSpace(os.Getenv("E2B_INTEGRATION_SANDBOX_DOMAIN"))cfg.E2BTemplate = templatecfg.E2BSandboxTTL = e2bIntegrationTTLcfg.E2BHTTPTimeout = e2bIntegrationHTTPTimeoutdiff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.goindex b6dedfc7e..5c006658d 100644--- a/internal/sandbox/e2b_remote_client.go+++ b/internal/sandbox/e2b_remote_client.go@@ -17,6 +17,8 @@ import ("connectrpc.com/connect"e2b "github.com/matiasinsaurralde/go-e2b"++ "github.com/Tencent/WeKnora/internal/logger")// E2BRemoteClient implements RemoteSandboxClient on top of the go-e2b client.@@ -127,6 +129,191 @@ func (c *E2BRemoteClient) Health(ctx context.Context) error {return nil}+func (c *E2BRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate, error) {+ items, err := c.client.ListTemplates(ctx)+ if err != nil {+ return nil, normalizeE2BError("ListTemplates", err)+ }+ result := make([]RemoteTemplate, 0, len(items))+ for _, item := range items {+ name := item.TemplateID+ if len(item.Names) > 0 && strings.TrimSpace(item.Names[0]) != "" {+ name = strings.TrimSpace(item.Names[0])+ } else if len(item.Aliases) > 0 && strings.TrimSpace(item.Aliases[0]) != "" {+ name = strings.TrimSpace(item.Aliases[0])+ }+ standard := isStandardTemplate(name)+ for _, candidate := range append(append([]string(nil), item.Aliases...), item.Names...) {+ if isStandardTemplate(candidate) {+ standard = true+ break+ }+ }+ status := normalizeE2BTemplateBuildStatus(item.BuildStatus)+ // E2B's template list keeps reporting a pending build status after the+ // template already became spawnable, so reconcile our standard template+ // against the build endpoints before telling the UI to keep waiting+ // forever. Limit these extra requests to the standard template; polling+ // every public template would turn one catalog refresh into an+ // unbounded N+1 request pattern.+ if standard && isE2BTemplateBuildPending(status) {+ if reconciled := c.reconcileE2BTemplateStatus(ctx, item); reconciled != "" {+ status = reconciled+ }+ }+ result = append(result, RemoteTemplate{+ ID: item.TemplateID,+ Name: name,+ Status: status,+ Version: item.EnvdVersion,+ CreatedAt: item.CreatedAt,+ UpdatedAt: item.UpdatedAt,+ Standard: standard,+ })+ }+ return result, nil+}++// reconcileE2BTemplateStatus resolves the real build state of a template whose+// list entry still looks pending, by asking the per-build endpoint that owns+// that answer.+//+// Only the template's *current* build counts as evidence. E2B spawns from that+// build alone, so neither an older successful build nor a non-zero spawn count+// proves the template can boot now — both happily coexist with a template that+// answers every sandbox creation with a 404. It returns an empty string when+// nothing more authoritative than the list status could be established.+func (c *E2BRemoteClient) reconcileE2BTemplateStatus(+ ctx context.Context,+ item e2b.TemplateDetail,+) string {+ templateID := strings.TrimSpace(item.TemplateID)+ buildID := strings.TrimSpace(item.BuildID)+ if templateID == "" {+ return ""+ }+ // buildID is "the last successful build", so the all-zero UUID means the+ // provider sees none under the tag it resolves. When builds did finish, the+ // template is not building at all — its builds are untagged, and no amount+ // of waiting will change that.+ if isBlankE2BUUID(buildID) {+ if item.BuildCount > 0 && c.hasSuccessfulE2BBuild(ctx, templateID) {+ return TemplateStatusUntagged+ }+ return ""+ }+ build, err := c.client.GetBuildStatus(ctx, templateID, buildID)+ if err != nil {+ logger.Warnf(ctx,+ "e2b build status lookup failed for template %s build %s: %v",+ templateID, buildID, err,+ )+ return ""+ }+ if isE2BTemplateBuildPending(build.Status) {+ return ""+ }+ reconciled := normalizeE2BTemplateBuildStatus(build.Status)+ if reconciled == "" {+ return ""+ }+ logger.Debugf(ctx,+ "e2b template %s list status %q reconciled to %q from build %s",+ templateID, item.BuildStatus, reconciled, buildID,+ )+ return reconciled+}++// hasSuccessfulE2BBuild reports whether the template's build history contains a+// finished build. It separates "the first build is still running" from "builds+// succeeded but none is reachable under the default tag".+func (c *E2BRemoteClient) hasSuccessfulE2BBuild(ctx context.Context, templateID string) bool {+ result, err := c.client.GetTemplate(ctx, templateID, e2b.WithTemplateBuildsLimit(100))+ if err != nil {+ logger.Warnf(ctx, "e2b template build history lookup failed for %s: %v", templateID, err)+ return false+ }+ for _, build := range result.Template.Builds {+ if normalizeE2BTemplateBuildStatus(build.Status) == "ready" {+ return true+ }+ }+ return false+}++// isBlankE2BUUID reports whether id carries no build reference. E2B returns the+// all-zero UUID, not an empty string, for a template without a build.+func isBlankE2BUUID(id string) bool {+ trimmed := strings.TrimSpace(id)+ if trimmed == "" {+ return true+ }+ for _, char := range trimmed {+ if char != '0' && char != '-' {+ return false+ }+ }+ return true+}++func normalizeE2BTemplateBuildStatus(status string) string {+ switch strings.ToLower(strings.TrimSpace(status)) {+ case "ready", "success", "succeeded", "complete", "completed":+ return "ready"+ case "building", "processing":+ return "building"+ case "waiting", "queued", "pending", "uploaded":+ return "waiting"+ case "error", "failed", "failure", "cancelled", "canceled":+ return "error"+ default:+ return strings.ToLower(strings.TrimSpace(status))+ }+}++func isE2BTemplateBuildPending(status string) bool {+ switch normalizeE2BTemplateBuildStatus(status) {+ case "building", "waiting":+ return true+ default:+ return false+ }+}++func (c *E2BRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {+ items, err := c.ListTemplates(ctx)+ if err != nil {+ return nil, err+ }+ for i := range items {+ if items[i].Standard {+ return &items[i], nil+ }+ }+ builder := e2b.NewTemplate().FromImage(DefaultDockerImage)+ build, err := builder.BuildInBackground(ctx, c.client, e2b.BuildConfig{+ Name: StandardTemplateName,+ // Creating a sandbox from a plain template name or ID resolves the+ // "default" tag, so a build tagged anything else is unreachable: E2B+ // answers every creation with "tag 'default' does not exist for+ // template ...". Naming the tag explicitly keeps that contract visible+ // instead of relying on the server-side default.+ Tags: []string{DefaultE2BTemplateTag},+ CPUCount: 2,+ MemoryMB: 2048,+ })+ if err != nil {+ return nil, normalizeE2BError("EnsureStandardTemplate", err)+ }+ return &RemoteTemplate{+ ID: build.TemplateID,+ Name: StandardTemplateName,+ Status: "building",+ Image: DefaultDockerImage,+ Standard: true,+ }, nil+}+func (c *E2BRemoteClient) Create(ctx context.Context,request RemoteCreateRequest,@@ -807,6 +994,7 @@ func normalizeE2BError(op string, err error) error {return fmt.Errorf("e2b %s: %w", op, err)}kind := RemoteErrorKindInternal+ status := 0switch {case errors.Is(err, context.DeadlineExceeded):kind = RemoteErrorKindTimeout@@ -839,6 +1027,7 @@ func normalizeE2BError(op string, err error) error {kind = RemoteErrorKindTimeoutcase errors.As(err, &apiErr):kind = httpErrorKind(op, apiErr.StatusCode)+ status = apiErr.StatusCodecase errors.As(err, &connectErr):switch connectErr.Code() {case connect.CodeCanceled, connect.CodeDeadlineExceeded:@@ -868,7 +1057,9 @@ func normalizeE2BError(op string, err error) error {}}}- return NewRemoteError(SandboxTypeE2B, op, kind, err.Error(), err)+ remoteErr := NewRemoteError(SandboxTypeE2B, op, kind, err.Error(), err)+ remoteErr.StatusCode = status+ return remoteErr}// e2bRemoteEntryType maps the E2B SDK FileInfo.Type onto the provider-neutraldiff --git a/internal/sandbox/e2b_remote_client_test.go b/internal/sandbox/e2b_remote_client_test.goindex dbf5d19ce..ce9436ccb 100644--- a/internal/sandbox/e2b_remote_client_test.go+++ b/internal/sandbox/e2b_remote_client_test.go@@ -269,6 +269,307 @@ func TestE2BRemoteClientProviderAndCapabilities(t *testing.T) {require.True(t, caps.SupportsFilesystemEnumeration)}+func TestE2BRemoteClientListTemplatesReconcilesStandardTemplateBuildStatus(t *testing.T) {+ var statusRequests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-ready",+ "buildID": "build-success",+ "names": []string{"project/weknora"},+ "aliases": []string{"weknora"},+ "buildStatus": "waiting",+ "envdVersion": "0.4.0",+ }})+ case "/templates/template-ready/builds/build-success/status":+ statusRequests.Add(1)+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-ready",+ "buildID": "build-success",+ "status": "ready",+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BTemplate: "template-ready",+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.True(t, templates[0].Standard)+ require.Equal(t, "project/weknora", templates[0].Name)+ require.Equal(t, "ready", templates[0].Status)+ require.Equal(t, int32(1), statusRequests.Load())+}++// An older successful build does not make the current one spawnable: E2B boots+// the current build only, and reporting "ready" here let the UI hand out a+// template that every sandbox creation rejected with a 404.+func TestE2BRemoteClientListTemplatesIgnoresOlderSuccessfulBuild(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-queued",+ "buildID": "build-queued",+ "names": []string{"project/weknora"},+ "buildStatus": "waiting",+ }})+ case "/templates/template-queued/builds/build-queued/status":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-queued",+ "buildID": "build-queued",+ "status": "waiting",+ })+ case "/templates/template-queued":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-queued",+ "names": []string{"project/weknora"},+ "builds": []map[string]any{+ {"buildID": "build-queued", "status": "waiting"},+ {"buildID": "build-older", "status": "success"},+ },+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, "waiting", templates[0].Status)+}++// E2B reports the all-zero UUID for a template that never got a build attached.+// Asking the build endpoint about it only yields a 400, and the template cannot+// be spawned, so the pending list status stands.+func TestE2BRemoteClientListTemplatesKeepsPendingWithoutBuildReference(t *testing.T) {+ var buildRequests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.URL.Path == "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-unbuilt",+ "buildID": "00000000-0000-0000-0000-000000000000",+ "names": []string{"project/weknora"},+ "buildStatus": "building",+ "spawnCount": 0,+ }})+ case strings.Contains(r.URL.Path, "/builds/"):+ buildRequests.Add(1)+ http.Error(w, `{"code":400,"message":"Build not found"}`, http.StatusBadRequest)+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, "building", templates[0].Status)+ require.Equal(t, int32(0), buildRequests.Load())+}++func TestE2BRemoteClientListTemplatesKeepsPendingWithoutSuccessfulBuild(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-fresh",+ "buildID": "build-fresh",+ "names": []string{"project/weknora"},+ "buildStatus": "building",+ }})+ case "/templates/template-fresh/builds/build-fresh/status":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-fresh",+ "buildID": "build-fresh",+ "status": "building",+ })+ case "/templates/template-fresh":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-fresh",+ "builds": []map[string]any{+ {"buildID": "build-fresh", "status": "building"},+ },+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, "building", templates[0].Status)+}++// Builds that finished but carry no default tag look exactly like "still+// building" in the template list, while sandbox creation rejects the template+// outright. The catalog has to name that state so the UI stops waiting.+func TestE2BRemoteClientListTemplatesReportsUntaggedBuilds(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-untagged",+ "buildID": "00000000-0000-0000-0000-000000000000",+ "names": []string{"project/weknora"},+ "buildStatus": "waiting",+ "buildCount": 2,+ }})+ case "/templates/template-untagged":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-untagged",+ "builds": []map[string]any{+ {"buildID": "build-1", "status": "success"},+ {"buildID": "build-2", "status": "success"},+ },+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, TemplateStatusUntagged, templates[0].Status)+}++// A template whose first build is genuinely still running has no finished build+// to find, so it must keep reporting the pending status.+func TestE2BRemoteClientListTemplatesKeepsPendingOnFirstBuild(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-first",+ "buildID": "00000000-0000-0000-0000-000000000000",+ "names": []string{"project/weknora"},+ "buildStatus": "building",+ "buildCount": 1,+ }})+ case "/templates/template-first":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-first",+ "builds": []map[string]any{{"buildID": "build-1", "status": "building"}},+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, "building", templates[0].Status)+}++// Past spawns say nothing about the build that is current now, so they must not+// upgrade a pending status either.+func TestE2BRemoteClientListTemplatesIgnoresSpawnCount(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/templates":+ writeJSON(w, http.StatusOK, []map[string]any{{+ "templateID": "template-spawned",+ "buildID": "build-x",+ "names": []string{"weknora"},+ "buildStatus": "waiting",+ "spawnCount": 4,+ }})+ case "/templates/template-spawned/builds/build-x/status":+ writeJSON(w, http.StatusOK, map[string]any{+ "templateID": "template-spawned",+ "buildID": "build-x",+ "status": "waiting",+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(server.Close)++ client, err := NewE2BRemoteClient(&Config{+ E2BAPIKey: "key-test",+ E2BAPIURL: server.URL,+ E2BSandboxTTL: time.Minute,+ })+ require.NoError(t, err)++ templates, err := client.ListTemplates(context.Background())+ require.NoError(t, err)+ require.Len(t, templates, 1)+ require.Equal(t, "waiting", templates[0].Status)+}++func TestNormalizeE2BTemplateBuildStatus(t *testing.T) {+ tests := map[string]string{+ "READY": "ready",+ "success": "ready",+ "completed": "ready",+ "processing": "building",+ "uploaded": "waiting",+ "failed": "error",+ "custom": "custom",+ }+ for raw, want := range tests {+ require.Equalf(t, want, normalizeE2BTemplateBuildStatus(raw), "status %q", raw)+ }+}+func TestE2BRemoteClientCreateWritesMetadataAndPauseLifecycle(t *testing.T) {mock := newE2BMockServer(t)client := newTestE2BRemoteClient(t, mock)diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.goindex d9aa533d0..dfe417a36 100644--- a/internal/sandbox/manager.go+++ b/internal/sandbox/manager.go@@ -51,14 +51,6 @@ func (m *DefaultManager) initializeSandbox(ctx context.Context) error {dockerSandbox := NewDockerSandbox(m.config)if dockerSandbox.IsAvailable(ctx) {m.sandbox = dockerSandbox- // Pre-pull the sandbox image asynchronously so it's ready before first use- go func() {- if err := dockerSandbox.EnsureImage(context.Background()); err != nil {- log.Printf("[sandbox] failed to pre-pull image %s: %v", m.config.DockerImage, err)- } else {- log.Printf("[sandbox] image %s is ready", m.config.DockerImage)- }- }()return nil}@@ -106,9 +98,19 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*Ereturn nil, ErrSandboxDisabled}+ effective := config+ if config != nil && len(m.config.EnvVars) > 0 {+ copy := *config+ copy.Env = cloneMetadata(m.config.EnvVars)+ for key, value := range config.Env {+ copy.Env[key] = value+ }+ effective = ©+ }+// Perform security validation unless explicitly skipped- if !config.SkipValidation {- if err := runScriptValidation(m.validator, config); err != nil {+ if effective != nil && !effective.SkipValidation {+ if err := runScriptValidation(m.validator, effective); err != nil {log.Printf("[sandbox] Security validation failed: %v", err)return &ExecuteResult{ExitCode: -1,@@ -118,7 +120,7 @@ func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*E}}- return sandbox.Execute(ctx, config)+ return sandbox.Execute(ctx, effective)}// runScriptValidation is the package-level helper that DefaultManager anddiff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.goindex 5fdee0bb3..e329e340c 100644--- a/internal/sandbox/remote_client.go+++ b/internal/sandbox/remote_client.go@@ -18,8 +18,7 @@ import ()// RemoteProvider identifies a remote sandbox backend. Values match the-// user-facing WEKNORA_SANDBOX_MODE strings and the existing SandboxType-// aliases so wiring/logging stays uniform.+// stored SandboxType strings so wiring/logging stays uniform.type RemoteProvider = SandboxType// RemoteSandboxHandle is an opaque, provider-issued reference to a livediff --git a/internal/sandbox/remote_errors.go b/internal/sandbox/remote_errors.goindex ec251d02d..439f099b8 100644--- a/internal/sandbox/remote_errors.go+++ b/internal/sandbox/remote_errors.go@@ -82,6 +82,12 @@ type RemoteError struct {// or SDK error strings belong here.Message string+ // StatusCode is the provider's HTTP status when the failure came from an+ // HTTP response, or 0 when it did not. Kind deliberately collapses statuses+ // that call for the same lifecycle decision, so diagnostics that must tell+ // those statuses apart read this instead of re-parsing Message.+ StatusCode int+// Cause is the original provider-side error, retained for// errors.Unwrap so callers can still errors.Is / errors.As it.Cause errordiff --git a/internal/sandbox/runtime_defaults.go b/internal/sandbox/runtime_defaults.gonew file mode 100644index 000000000..458ec782a--- /dev/null+++ b/internal/sandbox/runtime_defaults.go@@ -0,0 +1,27 @@+package sandbox++// Runtime tuning has safe built-in defaults. Unlike endpoints, credentials,+// and templates, these values do not identify an external backend.+func applyCubeRuntimeDefaults(cfg *Config) {+ if cfg == nil {+ return+ }+ if cfg.CubeSandboxTTL <= 0 {+ cfg.CubeSandboxTTL = DefaultCubeSandboxTTL+ }+ if cfg.CubeHTTPTimeout <= 0 {+ cfg.CubeHTTPTimeout = DefaultCubeHTTPTimeout+ }+}++func applyE2BRuntimeDefaults(cfg *Config) {+ if cfg == nil {+ return+ }+ if cfg.E2BSandboxTTL <= 0 {+ cfg.E2BSandboxTTL = DefaultE2BSandboxTTL+ }+ if cfg.E2BHTTPTimeout <= 0 {+ cfg.E2BHTTPTimeout = DefaultE2BHTTPTimeout+ }+}diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex 51647b0e6..4925962ba 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -29,12 +29,11 @@ const ()// IsNamedSandboxBackendType reports whether raw can be stored as a user-facing-// named sandbox backend. Only remote session backends (cube/e2b) support-// per-config credentials and session pinning; docker/local/disabled are-// deployment-level or workspace-policy concerns.+// named sandbox backend. Remote backends are session-persistent; docker/local+// are stateless, but all four share the same workspace configuration surface.func IsNamedSandboxBackendType(raw string) bool {switch SandboxType(raw) {- case SandboxTypeCube, SandboxTypeE2B:+ case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker, SandboxTypeLocal:return truedefault:return false@@ -48,8 +47,8 @@ const (DefaultCPULimit = 1.0 // 1 CPU coreDefaultDockerImage = "wechatopenai/weknora-sandbox:latest"- // DefaultCubeAPIURL is the default CubeAPI endpoint used when- // WEKNORA_SANDBOX_CUBE_API_URL is not configured.+ // DefaultCubeAPIURL is retained for SDK tests and explicit local helpers;+ // workspace configs must still provide their endpoint.DefaultCubeAPIURL = "http://127.0.0.1:33000"// DefaultCubeProxyURL is the default CubeProxy endpoint (HTTP, port 80) used// to reach the in-sandbox envd via host-header routing.@@ -57,8 +56,6 @@ const (// DefaultCubeSandboxDomain is the sandbox routing domain configured on// CubeProxy (matches CUBE_API_SANDBOX_DOMAIN in the Cube deployment).DefaultCubeSandboxDomain = "cube.app"- // DefaultCubeTemplate is the default template ID used to spawn Cube sandboxes.- DefaultCubeTemplate = "tpl-2b7911a5c3bb419a8745957a"// DefaultCubeSandboxTTL is the Cube-side sandbox lifetime hint (in seconds)// requested at creation; the sandbox is torn down by CubeMaster if the// client goes silent for longer than this value.@@ -200,6 +197,10 @@ type Config struct {// DefaultTimeout is the default execution timeoutDefaultTimeout time.Duration+ // AllowPrivateEndpoints is the per-workspace outbound policy for this+ // connection. Link-local addresses are blocked regardless.+ AllowPrivateEndpoints bool+// DockerImage is the Docker image to use (Docker sandbox only)DockerImage string@@ -270,11 +271,9 @@ type Config struct {// DefaultConfig returns a default sandbox configuration.//-// It deliberately carries no Cube or E2B endpoint, credential or template: those-// belong either to the deployment baseline (see applyCubeDeploymentDefaults) or-// to a named config that spelled them out. Presetting them here once meant every-// baseline silently offered a localhost Cube to configs that had never asked for-// one.+// It deliberately carries no Cube or E2B endpoint, credential or template:+// those belong to a named workspace config. Presetting them here once meant an+// incomplete workspace config could silently dial localhost.func DefaultConfig() *Config {return &Config{Type: SandboxTypeLocal,diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.goindex 1e8bb2604..60c424a98 100644--- a/internal/sandbox/sandbox_test.go+++ b/internal/sandbox/sandbox_test.go@@ -122,6 +122,39 @@ echo "Args: $@"t.Logf("Duration: %v", result.Duration)}+func TestManagerMergesWorkspaceEnvironmentVariables(t *testing.T) {+ tmpDir := t.TempDir()+ scriptPath := filepath.Join(tmpDir, "env.sh")+ scriptContent := "#!/bin/sh\nprintf '%s|%s' \"$WORKSPACE_VALUE\" \"$OVERRIDE_VALUE\"\n"+ if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil {+ t.Fatal(err)+ }++ config := DefaultConfig()+ config.Type = SandboxTypeLocal+ config.EnvVars = map[string]string{+ "WORKSPACE_VALUE": "from-workspace",+ "OVERRIDE_VALUE": "workspace-default",+ }+ manager, err := NewManager(config)+ if err != nil {+ t.Fatal(err)+ }++ result, err := manager.Execute(context.Background(), &ExecuteConfig{+ Script: scriptPath,+ ScriptContent: scriptContent,+ Env: map[string]string{"OVERRIDE_VALUE": "per-execution"},+ Timeout: 10 * time.Second,+ })+ if err != nil {+ t.Fatal(err)+ }+ if result.Stdout != "from-workspace|per-execution" {+ t.Fatalf("unexpected environment output %q", result.Stdout)+ }+}+func TestLocalSandboxTimeout(t *testing.T) {// Create a temporary script that sleepstmpDir, err := os.MkdirTemp("", "sandbox-test")@@ -202,8 +235,8 @@ func TestIsNamedSandboxBackendType(t *testing.T) {}{{"cube", true},{"e2b", true},- {"docker", false},- {"local", false},+ {"docker", true},+ {"local", true},{"disabled", false},{"", false},} {diff --git a/internal/sandbox/template_catalog.go b/internal/sandbox/template_catalog.gonew file mode 100644index 000000000..a0444353b--- /dev/null+++ b/internal/sandbox/template_catalog.go@@ -0,0 +1,48 @@+package sandbox++import (+ "context"+ "strings"+)++const StandardTemplateName = "weknora"++// DefaultE2BTemplateTag is the tag E2B resolves when a sandbox is created from a+// bare template name or ID. Builds must carry it to be spawnable at all.+const DefaultE2BTemplateTag = "default"++// TemplateStatusUntagged marks a template whose builds finished but which has no+// build under the tag sandbox creation resolves. It looks identical to "still+// building" in the provider's template list, yet waiting will never help: the+// template needs a new build carrying the default tag.+const TemplateStatusUntagged = "untagged"++// RemoteTemplate is the provider-neutral template projection returned to the+// settings UI. IDs remain opaque; users choose a readable name and status.+type RemoteTemplate struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Status string `json:"status,omitempty"`+ Version string `json:"version,omitempty"`+ Image string `json:"image,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`+ UpdatedAt string `json:"updated_at,omitempty"`+ Standard bool `json:"standard"`+}++// RemoteTemplateCatalog is an optional provider capability used by the+// configuration flow. It stays separate from RemoteSandboxClient because the+// session lifecycle never needs template administration.+type RemoteTemplateCatalog interface {+ ListTemplates(ctx context.Context) ([]RemoteTemplate, error)+ EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error)+}++func isStandardTemplate(name string) bool {+ trimmed := strings.Trim(strings.TrimSpace(name), "/")+ if strings.EqualFold(trimmed, StandardTemplateName) {+ return true+ }+ parts := strings.Split(trimmed, "/")+ return len(parts) > 1 && strings.EqualFold(parts[len(parts)-1], StandardTemplateName)+}diff --git a/internal/sandbox/template_catalog_test.go b/internal/sandbox/template_catalog_test.gonew file mode 100644index 000000000..a255ae6cb--- /dev/null+++ b/internal/sandbox/template_catalog_test.go@@ -0,0 +1,14 @@+package sandbox++import "testing"++func TestIsStandardTemplateRecognizesProviderScopedName(t *testing.T) {+ for _, name := range []string{"weknora", "team/weknora", "project-b89e/WeKnora"} {+ if !isStandardTemplate(name) {+ t.Fatalf("expected %q to identify the WeKnora standard template", name)+ }+ }+ if isStandardTemplate("weknora-custom") {+ t.Fatal("custom template must not be treated as the standard template")+ }+}diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.goindex 24e7892f8..567eddc6d 100644--- a/internal/sandbox/tenant_config.go+++ b/internal/sandbox/tenant_config.go@@ -2,7 +2,7 @@//// ResolveEffectiveConfig turns one stored config into the *Config a manager is// built from. A named config is self-contained: provider fields are never-// inherited from the WEKNORA_SANDBOX_* baseline, they come from the config or+// inherited from process configuration; they come from the workspace config or// they are missing and the config is refused (see config_required.go).//// Field-level inheritance was tried first and removed. It made the stored row an@@ -15,8 +15,8 @@//// What still comes from the baseline is deliberately narrow: the deployment's// script execution timeout, which is an operational guardrail rather than part-// of a backend's identity. A nil tenant config means "the deployment default-// backend" and yields the baseline unchanged.+// of a backend's identity. A nil tenant config is used only by low-level+// callers that explicitly request the supplied baseline.package sandboximport (@@ -58,14 +58,15 @@ func ResolveEffectiveConfig(effective.Type = resolved}overrideSeconds(&effective.DefaultTimeout, tenantCfg.DefaultTimeoutSec)+ effective.AllowPrivateEndpoints = tenantCfg.AllowPrivateEndpointsif tenantCfg.EnvVars != nil {effective.EnvVars = cloneMetadata(tenantCfg.EnvVars)}if cube := tenantCfg.Cube; cube != nil {- if err := overrideURL(&effective.CubeAPIURL, cube.APIURL); err != nil {+ if err := overrideURL(&effective.CubeAPIURL, cube.APIURL, effective.AllowPrivateEndpoints); err != nil {return nil, err}- if err := overrideURL(&effective.CubeProxyURL, cube.ProxyURL); err != nil {+ if err := overrideURL(&effective.CubeProxyURL, cube.ProxyURL, effective.AllowPrivateEndpoints); err != nil {return nil, err}overrideString(&effective.CubeSandboxDomain, cube.SandboxDomain)@@ -76,7 +77,7 @@ func ResolveEffectiveConfig(}if e2bCfg := tenantCfg.E2B; e2bCfg != nil {- if err := overrideURL(&effective.E2BAPIURL, e2bCfg.APIURL); err != nil {+ if err := overrideURL(&effective.E2BAPIURL, e2bCfg.APIURL, effective.AllowPrivateEndpoints); err != nil {return nil, err}overrideString(&effective.E2BSandboxDomain, e2bCfg.SandboxDomain)@@ -110,6 +111,7 @@ func ResolveEffectiveConfig(// default rather than to whatever this deployment happens to run, otherwise// "inherits nothing" would still have an exception to explain.func clearProviderFields(cfg *Config) {+ cfg.DockerImage = ""cfg.CubeAPIURL = ""cfg.CubeProxyURL = ""cfg.CubeSandboxDomain = ""@@ -174,11 +176,11 @@ func overrideString(dst *string, value string) {// overrideURL is overrideString for endpoint fields: a tenant-supplied URL// must pass the SSRF guard before it is accepted into the effective config.-func overrideURL(dst *string, value string) error {+func overrideURL(dst *string, value string, allowPrivate bool) error {if value == "" {return nil}- if err := ValidateOutboundURL(value); err != nil {+ if err := ValidateOutboundURLWithPolicy(value, OutboundURLPolicy{AllowPrivate: allowPrivate}); err != nil {return err}*dst = valuediff --git a/internal/sandbox/tenant_resolver.go b/internal/sandbox/tenant_resolver.goindex 1bcfd5249..5e4c95686 100644--- a/internal/sandbox/tenant_resolver.go+++ b/internal/sandbox/tenant_resolver.go@@ -74,7 +74,7 @@ type TenantSandboxResolver interface {// TenantSandboxResolverDeps bundles the resolver's wiring.type TenantSandboxResolverDeps struct {- // GlobalConfig is the process-wide config built from WEKNORA_SANDBOX_*.+ // GlobalConfig supplies only built-in runtime tuning defaults.GlobalConfig *Config// DefaultManager serves tenants without their own configuration, which@@ -91,12 +91,14 @@ type TenantSandboxResolverDeps struct {}type tenantSandboxResolver struct {- deps TenantSandboxResolverDeps- transport *http.Transport+ deps TenantSandboxResolverDeps+ transport *http.Transport+ privateTransport *http.Transport// cubeTransports must outlive the per-request clients it serves, which is// the whole point of holding it here rather than building it per Resolve.- cubeTransports *CubeTransportPool+ cubeTransports *CubeTransportPool+ privateCubeTransports *CubeTransportPool}// NewTenantSandboxResolver validates the wiring and returns a resolver.@@ -118,9 +120,11 @@ func NewTenantSandboxResolver(deps TenantSandboxResolverDeps) (TenantSandboxResotransport = NewGuardedTransport()}return &tenantSandboxResolver{- deps: deps,- transport: transport,- cubeTransports: NewCubeTransportPool(transport),+ deps: deps,+ transport: transport,+ privateTransport: NewGuardedTransportWithPolicy(OutboundURLPolicy{AllowPrivate: true}),+ cubeTransports: NewCubeTransportPool(transport),+ privateCubeTransports: NewCubeTransportPoolWithPolicy(nil, OutboundURLPolicy{AllowPrivate: true}),}, nil}@@ -128,11 +132,15 @@ func NewTenantSandboxResolver(deps TenantSandboxResolverDeps) (TenantSandboxReso// the outbound policy forbids. This closes the DNS-rebinding window that// save-time URL validation cannot cover.func NewGuardedTransport() *http.Transport {+ return NewGuardedTransportWithPolicy(DefaultOutboundURLPolicy())+}++func NewGuardedTransportWithPolicy(policy OutboundURLPolicy) *http.Transport {return &http.Transport{DialContext: (&net.Dialer{Timeout: 10 * time.Second,KeepAlive: 30 * time.Second,- Control: SafeDialControl,+ Control: SafeDialControlForPolicy(policy),}).DialContext,MaxIdleConns: 100,MaxIdleConnsPerHost: 4,@@ -148,7 +156,7 @@ func (r *tenantSandboxResolver) Resolve() (Manager, error) {if strings.TrimSpace(configID) == "" ||configID == types.SandboxConfigIDGlobalDefault {- return r.deps.DefaultManager, nil+ return NewDisabledManager(), nil}resolved, err := r.deps.Loader.Load(ctx, tenantID, configID)@@ -184,9 +192,15 @@ func (r *tenantSandboxResolver) Resolve(SkipHealthProbe: true,ConfigID: configID,})+ case SandboxTypeDocker, SandboxTypeLocal:+ // Stateless backends still come from the selected workspace row. Docker+ // fallback is deliberately disabled: silently running a configured+ // container workload on the application host would cross an isolation+ // boundary.+ effective.FallbackEnabled = false+ return NewManager(effective)default:- // docker/local have no per-config remote wiring.- return r.deps.DefaultManager, nil+ return NewDisabledManager(), nil}}@@ -195,8 +209,14 @@ func (r *tenantSandboxResolver) Resolve(func (r *tenantSandboxResolver) buildClient(cfg *Config) (RemoteSandboxClient, error) {switch cfg.Type {case SandboxTypeCube:+ if cfg.AllowPrivateEndpoints {+ return NewCubeRemoteClientWithPool(cfg, r.privateCubeTransports)+ }return NewCubeRemoteClientWithPool(cfg, r.cubeTransports)case SandboxTypeE2B:+ if cfg.AllowPrivateEndpoints {+ return NewE2BRemoteClientWithTransport(cfg, r.privateTransport)+ }return NewE2BRemoteClientWithTransport(cfg, r.transport)default:return nil, fmt.Errorf("sandbox: provider %q has no remote client", cfg.Type)@@ -217,9 +237,11 @@ func NewRemoteClientForCheck(cfg *Config) (RemoteSandboxClient, error) {}switch cfg.Type {case SandboxTypeCube:- return NewCubeRemoteClientWithPool(cfg, NewCubeTransportPool(nil))+ return NewCubeRemoteClientWithPool(cfg, NewCubeTransportPoolWithPolicy(nil,+ OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))case SandboxTypeE2B:- return NewE2BRemoteClientWithTransport(cfg, NewGuardedTransport())+ return NewE2BRemoteClientWithTransport(cfg, NewGuardedTransportWithPolicy(+ OutboundURLPolicy{AllowPrivate: cfg.AllowPrivateEndpoints}))default:return nil, fmt.Errorf("sandbox: provider %q cannot be probed", cfg.Type)}diff --git a/internal/sandbox/tenant_resolver_test.go b/internal/sandbox/tenant_resolver_test.goindex ffa6d5553..fce84ecdb 100644--- a/internal/sandbox/tenant_resolver_test.go+++ b/internal/sandbox/tenant_resolver_test.go@@ -43,15 +43,13 @@ func newTestResolver(t *testing.T, loader TenantSandboxConfigLoader) (TenantSandreturn resolver, fallback}-// Existing deployments have no tenant config at all; they must keep using the-// process-wide manager built from WEKNORA_SANDBOX_*.-func TestResolveEmptyConfigIDUsesDefaultManager(t *testing.T) {- resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{})+func TestResolveEmptyConfigIDIsDisabled(t *testing.T) {+ resolver, _ := newTestResolver(t, &stubTenantConfigLoader{})mgr, err := resolver.Resolve(context.Background(), 42, "")require.NoError(t, err)- require.Same(t, fallback, mgr)+ require.Equal(t, SandboxTypeDisabled, mgr.GetType())}// A cordoned config must not produce a manager: the whole point of the cordon@@ -103,6 +101,25 @@ func TestResolveBuildsRemoteManagerWithoutHealthProbe(t *testing.T) {require.Equal(t, SandboxTypeE2B, mgr.GetType())}+func TestResolveBuildsLocalManagerFromWorkspaceConfig(t *testing.T) {+ resolver, fallback := newTestResolver(t, &stubTenantConfigLoader{+ result: ResolvedTenantSandboxConfig{+ Config: &types.TenantSandboxConfig{+ SandboxType: "local",+ DefaultTimeoutSec: 17,+ EnvVars: map[string]string{"WORKSPACE_FLAG": "enabled"},+ },+ Found: true,+ },+ })++ mgr, err := resolver.Resolve(context.Background(), 42, "cfg-local")++ require.NoError(t, err)+ require.NotSame(t, fallback, mgr)+ require.Equal(t, SandboxTypeLocal, mgr.GetType())+}+// No caching: the loader is consulted on every Resolve, which is what makes a// config change take effect on the next request with no invalidation step.func TestResolveBuildsFreshManagerEveryCall(t *testing.T) {diff --git a/internal/sandbox/url_guard.go b/internal/sandbox/url_guard.goindex 8ffa6cd70..838fc67c9 100644--- a/internal/sandbox/url_guard.go+++ b/internal/sandbox/url_guard.go@@ -14,13 +14,9 @@// that actually holds, because a hostname can resolve to a public address// during validation and to 169.254.169.254 at dial time (DNS rebinding).//-// Self-hosted deployments complicate this: CubeAPI's own default endpoint is-// http://127.0.0.1:33000, so a blanket ban on private addresses would make-// per-tenant Cube configuration impossible. The policy is therefore-// deny-by-default with an explicit operator opt-in-// (WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS=true). Even when opted in, the-// link-local range — and with it the cloud metadata address — stays blocked,-// because it is never a legitimate sandbox endpoint.+// Self-hosted deployments complicate this, so private endpoints are an+// explicit field on each workspace config. Even when enabled, link-local+// ranges — including cloud metadata — stay blocked.package sandboximport (@@ -28,8 +24,6 @@ import ("fmt""net""net/url"- "os"- "strconv""strings""syscall")@@ -38,11 +32,6 @@ import (// scheme or resolves to an address the policy forbids.var ErrUnsafeOutboundURL = errors.New("sandbox: unsafe outbound URL")-// AllowPrivateEndpointsEnv opts a deployment into private/loopback sandbox-// endpoints. Required for self-hosted Cube, which listens on 127.0.0.1 by-// default. Link-local addresses remain blocked regardless.-const AllowPrivateEndpointsEnv = "WEKNORA_SANDBOX_ALLOW_PRIVATE_ENDPOINTS"-// OutboundURLPolicy decides which addresses tenant-supplied endpoints may// resolve to.type OutboundURLPolicy struct {@@ -51,14 +40,10 @@ type OutboundURLPolicy struct {AllowPrivate bool}-// DefaultOutboundURLPolicy reads the policy from the environment. Absent or-// unparseable values fail closed.+// DefaultOutboundURLPolicy is the fail-closed policy used by callers that do+// not carry a workspace configuration.func DefaultOutboundURLPolicy() OutboundURLPolicy {- allow, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(AllowPrivateEndpointsEnv)))- if err != nil {- allow = false- }- return OutboundURLPolicy{AllowPrivate: allow}+ return OutboundURLPolicy{}}// ValidateOutboundURL checks raw against the environment's policy.@@ -66,11 +51,21 @@ func ValidateOutboundURL(raw string) error {return DefaultOutboundURLPolicy().Validate(raw)}+func ValidateOutboundURLWithPolicy(raw string, policy OutboundURLPolicy) error {+ return policy.Validate(raw)+}+// SafeDialControl is a net.Dialer.Control hook using the environment's policy.func SafeDialControl(network string, address string, conn syscall.RawConn) error {return DefaultOutboundURLPolicy().DialControl(network, address, conn)}+func SafeDialControlForPolicy(policy OutboundURLPolicy) func(string, string, syscall.RawConn) error {+ return func(network string, address string, conn syscall.RawConn) error {+ return policy.DialControl(network, address, conn)+ }+}+// Validate reports whether raw is an acceptable tenant-supplied endpoint. It// rejects non-HTTP schemes and any host that resolves to a forbidden address.//@@ -103,8 +98,8 @@ func (p OutboundURLPolicy) Validate(raw string) error {if lower == "localhost" || strings.HasSuffix(lower, ".localhost") {if !p.AllowPrivate {return fmt.Errorf(- "%w: host %q is loopback; set %s=true to allow self-hosted endpoints",- ErrUnsafeOutboundURL, host, AllowPrivateEndpointsEnv,+ "%w: host %q is loopback; enable private endpoints for this workspace config",+ ErrUnsafeOutboundURL, host,)}return nil@@ -162,8 +157,8 @@ func (p OutboundURLPolicy) checkIP(ip net.IP) error {if ip.IsLoopback() || ip.IsPrivate() || isCarrierGradeNAT(ip) {if !p.AllowPrivate {return fmt.Errorf(- "%w: address %s is private; set %s=true to allow self-hosted endpoints",- ErrUnsafeOutboundURL, ip, AllowPrivateEndpointsEnv,+ "%w: address %s is private; enable private endpoints for this workspace config",+ ErrUnsafeOutboundURL, ip,)}}diff --git a/internal/sandbox/url_guard_test.go b/internal/sandbox/url_guard_test.goindex 8325e4f4b..304f6a300 100644--- a/internal/sandbox/url_guard_test.go+++ b/internal/sandbox/url_guard_test.go@@ -137,16 +137,7 @@ func TestPolicyDialControlMirrorsValidation(t *testing.T) {}func TestDefaultOutboundURLPolicyFailsClosed(t *testing.T) {- t.Setenv(AllowPrivateEndpointsEnv, "")if DefaultOutboundURLPolicy().AllowPrivate {- t.Fatal("an unset opt-in must fail closed")- }- t.Setenv(AllowPrivateEndpointsEnv, "not-a-bool")- if DefaultOutboundURLPolicy().AllowPrivate {- t.Fatal("an unparseable opt-in must fail closed")- }- t.Setenv(AllowPrivateEndpointsEnv, "true")- if !DefaultOutboundURLPolicy().AllowPrivate {- t.Fatal("an explicit true must enable private endpoints")+ t.Fatal("callers without a workspace config must fail closed")}}diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.goindex 6160c50dc..5273b6ee5 100644--- a/internal/types/custom_agent.go+++ b/internal/types/custom_agent.go@@ -152,8 +152,7 @@ type CustomAgentConfig struct {// ===== Sandbox Settings =====// SandboxConfigID selects which workspace sandbox config this agent's- // skill scripts run on. Empty means the deployment-wide- // WEKNORA_SANDBOX_* defaults.+ // skill scripts run on. Empty means sandbox execution is disabled.//// This references the LOGICAL config, never a specific revision: keeping// the indirection here is what would let credential rotation happendiff --git a/internal/types/tenant.go b/internal/types/tenant.goindex 0a2538bfc..452a26a74 100644--- a/internal/types/tenant.go+++ b/internal/types/tenant.go@@ -620,25 +620,25 @@ func (c *StorageEngineConfig) Scan(value interface{}) error {// TenantSandboxConfig is one named sandbox backend a workspace maintains.//-// It is self-contained: provider fields are NOT inherited from the deployment's-// WEKNORA_SANDBOX_* values, which only back agents that selected no config at-// all. Leaving a required provider field empty is rejected on save rather than-// filled in from the environment — see sandbox.MissingRequiredFields for the-// list and internal/sandbox/tenant_config.go for why inheritance was dropped.+// It is self-contained: provider fields are not inherited from process+// environment. Leaving a required provider field empty is rejected on save.type TenantSandboxConfig struct {- // SandboxType selects the sandbox backend. Named configs must set it to- // "cube" or "e2b"; "docker", "local" and "disabled" appear only on the+ // SandboxType selects the sandbox backend. Named configs may use "cube",+ // "e2b", "docker", or "local". "disabled" is reserved for the hidden// workspace policy row.SandboxType string `json:"sandbox_type,omitempty"`// ── 通用配置(跨后端生效)──────────────────────────────────- // DefaultTimeoutSec is the per-execution timeout in seconds. 0 keeps the- // deployment's WEKNORA_SANDBOX_TIMEOUT: an execution guardrail is operator- // policy rather than part of this backend's identity, so it is the one- // value a named config still takes from the environment.+ // DefaultTimeoutSec is the per-execution timeout in seconds. 0 uses the+ // program's built-in default.DefaultTimeoutSec int `json:"default_timeout_sec,omitempty"`+ // AllowPrivateEndpoints permits this workspace config to reach RFC1918 or+ // loopback cluster endpoints. Link-local/cloud-metadata addresses remain+ // blocked. It is explicit in the UI instead of hidden in process env.+ AllowPrivateEndpoints bool `json:"allow_private_endpoints,omitempty"`+// EnvVars are additional environment variables injected into every// sandbox created for this tenant. 🔒 Values are encrypted at rest.// These become visible to all scripts running in the tenant'sdiff --git a/internal/types/tenant_sandbox_config_entity.go b/internal/types/tenant_sandbox_config_entity.goindex 1f4859a36..07c4775be 100644--- a/internal/types/tenant_sandbox_config_entity.go+++ b/internal/types/tenant_sandbox_config_entity.go@@ -12,8 +12,8 @@ import ("gorm.io/gorm")-// SandboxConfigIDGlobalDefault marks a sandbox created on the deployment-wide-// WEKNORA_SANDBOX_* configuration rather than on a stored config row.+// SandboxConfigIDGlobalDefault is retained for sessions created by older+// versions that used a deployment-wide sandbox configuration.//// A sentinel rather than the empty string, so NULL on sessions.sandbox_config_id// unambiguously means "this session has no live sandbox".diff --git a/website-docs/01-getting-started/02-installation.md b/website-docs/01-getting-started/02-installation.mdindex acae69c14..74ff58bbe 100644--- a/website-docs/01-getting-started/02-installation.md+++ b/website-docs/01-getting-started/02-installation.md@@ -223,7 +223,7 @@ Lite 模式通过编译期 `EDITION=lite` 与运行期 `.env.lite` 环境实现- **队列/流**:`STREAM_MANAGER_TYPE=memory`(`internal/stream/factory.go`),不需要 Redis,Asynq 分布式队列在 Lite 模式下为内存/no-op;- **前端**:`make build-lite` 会把 `frontend/dist` 复制为仓库根的 `web/`,二进制直接内嵌托管静态资源(`WEKNORA_WEB_DIR` 可指定目录,router 的 `serveFrontendStatic` 提供服务);- **文档解析**:仍可选连本地 docreader(`DOCREADER_ADDR=127.0.0.1:50051`);-- **沙箱**:`WEKNORA_SANDBOX_MODE=disabled`。+- **沙箱**:Lite 启动时不预置后端;可在设置页按空间统一配置 Docker、Local、CubeSandbox 或 E2B。```bashcp .env.lite.example .env.lite # 修改 SYSTEM_AES_KEY / JWT_SECRETdiff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.mdindex 019522ebd..2839a5f31 100644--- a/website-docs/01-getting-started/04-configuration.md+++ b/website-docs/01-getting-started/04-configuration.md@@ -250,8 +250,7 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走| 名称 | 默认值 | 说明 || --- | --- | --- |-| `WEKNORA_SANDBOX_MODE` | disabled(代码默认;标准 compose 里设为 docker) | Skills 沙箱:`docker` / `local` / `disabled` |-| `WEKNORA_SANDBOX_TIMEOUT` / `WEKNORA_SANDBOX_DOCKER_IMAGE` | 60 / wechatopenai/weknora-sandbox:latest | 沙箱执行超时与镜像 |+| Sandbox 配置 | 设置页按空间维护 | 后端、凭据、模板、超时和私网访问策略不再读取 `WEKNORA_SANDBOX_*` || `WEKNORA_SKILLS_DIR` | 空(镜像内 /app/skills/preloaded) | 自定义 Skills 目录 || `WEKNORA_AGENT_LLM_TIMEOUT` | 120s | Agent 单次 LLM 调用超时(Go duration 或纯数字秒) || `WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT` / `_FAIL_OPEN` | 600s / fail-close | MCP 工具人工审批等待与失败策略 |diff --git a/website-docs/02-architecture/01-overview.md b/website-docs/02-architecture/01-overview.mdindex 1eab010ca..f67c725c9 100644--- a/website-docs/02-architecture/01-overview.md+++ b/website-docs/02-architecture/01-overview.md@@ -15,7 +15,7 @@ WeKnora 采用"主服务 + 前端 + 文档解析微服务"的三进程核心架| `docreader` | `wechatopenai/weknora-docreader`(`docker/Dockerfile.docreader`,Python) | `50051`(仅 compose 网络内 expose,不映射宿主机) | 文档解析微服务:gRPC 服务端,PDF/DOCX/Excel/EPUB/网页等 25+ 格式解析与页面渲染。健康检查 `grpc_health_probe` || `postgres` | `paradedb/paradedb:v0.22.2-pg17` | `5432`(网络内) | 主数据库。ParadeDB 发行版自带 BM25 全文检索与 pgvector 向量能力,因此**默认部署无需独立向量库**(`RETRIEVE_DRIVER=postgres`) || `redis` | `redis:7.0-alpine`(`appendonly` + `requirepass`) | `6379`(网络内) | Asynq 任务队列、SSE 流管理(跨实例)、system_settings 发布订阅、限流与分布式模型并发闸门 |-| `sandbox` | `wechatopenai/weknora-sandbox`(`docker/Dockerfile.sandbox`) | — | 非常驻服务,仅用于 build/pull 镜像;`app` 执行 Agent Skills 时按需 `docker run` 该镜像(`WEKNORA_SANDBOX_MODE=docker`),用毕即释 |+| `sandbox` | `wechatopenai/weknora-sandbox`(`docker/Dockerfile.sandbox`) | — | WeKnora 标准运行镜像;可直接用于空间 Docker 后端,接入 CubeSandbox/E2B 时则通过模板 API 自动注册并用于 Agent Skills |`app` 与 `docreader` 之间还通过共享卷 `docreader-tmp`(挂载于 `/tmp/docreader`)传递解析产物图片;`app` 的本地文件存储卷为 `data-files`(`/data/files`)。diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.mdindex 56046c966..1182eef37 100644--- a/website-docs/03-features/07-agent.md+++ b/website-docs/03-features/07-agent.md@@ -402,19 +402,13 @@ description: Extract text and tables from PDF files, fill forms, merge documentsAgent 侧的启停在 `configureSkillsFromAgent`(`internal/application/service/session_agent_qa.go`):-- **沙箱关闭(`WEKNORA_SANDBOX_MODE` 为空或 `disabled`)时技能整体不可用**;+- 智能体未选择空间级沙箱配置时,脚本执行工具不可用,但仍可浏览技能说明;- `SkillsSelectionMode`:`all` = 全部预置技能、`selected` = `SelectedSkills` 白名单、`none`/空 = 禁用;- 用户 `@技能` 提及会经 `applyPerRequestSkillScope` 把本轮白名单收窄到提及集合,并作为 `PinnedSkillInfo` 注入 `<must_use>` 块("Must call read_skill(...) before answering")。### 5.3 与沙箱(internal/sandbox)的关系-`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。沙箱由环境变量配置:--| 环境变量 | 含义 | 默认 |-| --- | --- | --- |-| `WEKNORA_SANDBOX_MODE` | `docker` / `local` / `disabled` | `disabled` |-| `WEKNORA_SANDBOX_DOCKER_IMAGE` | Docker 沙箱镜像 | `wechatopenai/weknora-sandbox:latest` |-| `WEKNORA_SANDBOX_TIMEOUT` | 执行超时(秒) | 60 |+`execute_skill_script` → `skills.Manager.ExecuteScript` → `sandbox.Manager.Execute`。Docker、Local、CubeSandbox、E2B 均通过「设置 → 沙箱后端」的同一套空间配置与检查接口维护;远端模板从目标 Cube/E2B 集群实时拉取,缺少 WeKnora 标准模板时自动创建。Docker/Local 每次独立执行,不写入会话沙箱绑定。**Manager 与校验器**(`internal/sandbox/manager.go`、`validator.go`):每次执行前,除非 `SkipValidation`,`ScriptValidator` 会做四类静态校验,任一命中即拒绝执行并返回 `ErrSecurityViolation`: