Skip to content

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

feat(sandbox): pin Cube DNS on templates and freeze skill snapshot configs

wizardchenc170854b89c4
diff --git a/docs/docs.go b/docs/docs.go
index aeeeafc0a..4a9fdc04c 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -17443,6 +17443,13 @@ const docTemplate = `{
"cube_sandbox_ttl_seconds": {
"type": "integer"
},
+ "dns_servers": {
+ "description": "DNSServers are Cube template nameserver IPs. Empty uses Cubelet's default.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"http_timeout_sec": {
"description": "HTTPTimeoutSec bounds each HTTP call to the sandbox control plane.\n0 means use the built-in default (30s), never the deployment's value.",
"type": "integer"
diff --git a/docs/sandbox-cluster.md b/docs/sandbox-cluster.md
index 74a5164dd..e35b362f8 100644
--- a/docs/sandbox-cluster.md
+++ b/docs/sandbox-cluster.md
@@ -62,8 +62,8 @@ Cube 变体只发布 linux/amd64——envd 的来源镜像 `cubesandbox-base`
### 制作模板并对接 WeKnora
1. 按 [CubeSandbox Quick Start](https://github.com/TencentCloud/CubeSandbox/blob/master/docs/zh/guide/quickstart.md) 完成控制面、计算节点、CubeProxy 与域名解析。生产环境还需按官方文档完成鉴权、TLS、网络策略与多节点部署。
-2. 在 WeKnora 的空间设置中填写 CubeAPI、CubeProxy、sandbox domain 和可选 API Key。若这些端点位于 RFC1918/loopback 网络,显式打开“允许访问私网集群地址”。
-3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并调用集群模板列表;如果集群里没有可用的 WeKnora 标准模板,会从 `wechatopenai/weknora-sandbox:latest-cube` 发起一次构建。已有模板按名称 `weknora` 或镜像识别,因此即使集群没有给模板登记别名也不会重复创建;已有模板构建失败时,走的是原地重建而不是新建一个。
+2. 在 WeKnora 的空间设置中填写 CubeAPI、CubeProxy、sandbox domain 和可选 API Key。需要自定义 guest DNS 时填写「DNS 服务器」(须为 IP);留空则使用集群默认。若这些端点位于 RFC1918/loopback 网络,显式打开“允许访问私网集群地址”。
+3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并列出集群模板。**不会自动创建**。没有 WeKnora 标准模板时在占位卡片上点「创建」,会从 `wechatopenai/weknora-sandbox:latest-cube` 发起构建。改 DNS 或需要换镜像时在 weknora 卡片上点「重建」:先删掉现有标准模板再用当前配置新建。已有模板按名称 `weknora` 或镜像识别;失败模板同样用「重建」(CubeMaster 拒绝 redo、错误码 130400 时尤其需要)。
4. 模板构建状态会自动刷新。状态变为 `READY` 后才可选择并进入运行配置;界面显示模板名称、状态和版本,配置内部才保存该集群自己的 `template_id`。
模板镜像必须提供 uid 1000 的 `user` 账号:WeKnora 以该账号执行脚本与文件操作。写权限只保证在 `/workspace/output` 与 `/workspace/input` 下。
@@ -90,9 +90,10 @@ go test -tags=integration ./internal/sandbox -run Integration -count=1 -v
| 连接验证失败 | CubeAPI 地址是否是控制面端口(不是 Dashboard 端口);私网地址是否已打开“允许访问私网集群地址” |
| 连接通过但执行报数据面错误 | CubeProxy 地址与 sandbox domain 是否与集群 `CUBE_API_SANDBOX_DOMAIN` 一致;Proxy 是否对 WeKnora 可达 |
| 模板长期停在构建中 | 镜像体积与网络;用 `cubemastercli tpl watch --job-id <id>` 看真实进度 |
-| 模板构建失败 | 卡片上会显示集群返回的失败原因;点「刷新模板」会就地重建同一个模板,不会新建一个 |
+| 模板构建失败 | 卡片上会显示集群返回的失败原因。未安装 Skill 时可点「重建」删掉失败模板并用当前配置新建;仅刷新列表不会再自动重建。已安装 Skill 的配置会拒绝重建,请新建沙箱 |
+| 失败原因含 `TOOMANYREQUESTS` / Docker Hub 限流 | Cube 节点匿名拉 `wechatopenai/weknora-sandbox` 触发了 Hub 限额。等限额恢复后再刷新,或在节点上 `docker login` 后重试 |
| 失败原因是 `Get "http://<IP>:49983/health": connect: connection refused` | 模板镜像里没有 envd。确认建模板用的是 `-cube` 变体镜像;若已是该变体,再查 Cube 沙箱网段(默认 `192.168.0.0/18`)是否与物理内网冲突 |
-| 沙箱能创建但脚本报权限错误 | 模板缺少 `user` 账号,或脚本写到了 `/workspace` 根目录 |
+| 沙箱能执行但「出网可用」失败 | 先看模板「公网访问」是否开启;WeKnora 标准模板构建会带 `allowInternetAccess`。guest DNS 来自标准模板构建时写入的 `dns`(设置页「DNS 服务器」/`dns_servers`)。留空时 Cubelet 会落到 `119.29.29.29`;私网或云上 UDP 53 到不了公网 DNS 时,填 Cube 宿主机 `/etc/resolv.conf` 里能用的地址,并避开 CubeVS 默认拒绝的 `10/8`、`172.16/12`、`192.168/16`。未安装 Skill 时,已有标准模板改 DNS 后在 weknora 卡片上点「重建」;已装 Skill 的配置请新建沙箱。其次 Cube 把沙箱 80/443 TPROXY 到 `192.168.0.1:8080/8443`,宿主机占用 `0.0.0.0:8080` 时 cube-egress 起不来。探测目标 `1.1.1.1` 在腾讯云也经常不通,国内目标可达即可 |
| 会话重连后状态丢失 | 多副本部署是否配置了 Redis 绑定存储;沙箱是否已被空闲 TTL 回收 |
### 已知限制
@@ -105,14 +106,14 @@ go test -tags=integration ./internal/sandbox -run Integration -count=1 -v
## E2B 及其它 E2B 兼容实现
-E2B 官方托管服务、自建 E2B Infrastructure,以及任意实现 E2B 协议的控制面(例如 Kubernetes 上以容器隔离的 Agent-Sandbox)都通过同一个 E2B 配置接入;自建集群通常还要填写 `proxy_url` 数据面网关,详见 [沙箱协议接入说明](./sandbox-protocol.md)。填写 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) 为准。
+E2B 官方托管服务、自建 E2B Infrastructure,以及任意实现 E2B 协议的控制面(例如 Kubernetes 上以容器隔离的 Agent-Sandbox)都通过同一个 E2B 配置接入;自建集群通常还要填写 `proxy_url` 数据面网关,详见 [沙箱协议接入说明](./sandbox-protocol.md)。填写 API Key 后先执行“连接并继续”,流程与 Cube 相同:验证连接后列出账号可见模板;缺少 `weknora` 时点「创建 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. 等待自动创建的标准模板就绪,或选择集群已有的兼容模板;构建中的模板不可选择,状态会自动刷新。
+4. 没有标准模板时点占位卡片上的「创建」,或选择集群已有的兼容模板;改 DNS / 镜像后在 weknora 卡片上点「重建」。**该配置已安装 Skill 时不能更换或重建模板**——技能环境绑在快照上,新底模不会进去;请新建一份沙箱再装 Skill。构建中的模板不可选择,状态会自动刷新。
5. 配置运行参数;上线前可执行一次“完整验证”。完整验证会真实创建、执行并销毁一个沙箱。
6. 保存后,在智能体 Skills 配置中选择该后端。对配置的修改只影响之后新建的沙箱;已有会话仍固定使用创建时的配置。
diff --git a/docs/swagger.json b/docs/swagger.json
index 36f5256a0..82ec7d4a4 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -17436,6 +17436,13 @@
"cube_sandbox_ttl_seconds": {
"type": "integer"
},
+ "dns_servers": {
+ "description": "DNSServers are Cube template nameserver IPs. Empty uses Cubelet's default.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"http_timeout_sec": {
"description": "HTTPTimeoutSec bounds each HTTP call to the sandbox control plane.\n0 means use the built-in default (30s), never the deployment's value.",
"type": "integer"
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 1847eaa70..d33c6f087 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -697,6 +697,11 @@ definitions:
type: string
cube_sandbox_ttl_seconds:
type: integer
+ dns_servers:
+ description: DNSServers are Cube template nameserver IPs. Empty uses Cubelet's default.
+ items:
+ type: string
+ type: array
http_timeout_sec:
description: |-
HTTPTimeoutSec bounds each HTTP call to the sandbox control plane.
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index 92fb5a410..7c3588cbb 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -737,6 +737,7 @@ export interface SandboxCubeConfig {
template_id?: string
http_timeout_sec?: number
cube_sandbox_ttl_seconds?: number
+ dns_servers?: string[]
}
export interface SandboxE2BConfig {
@@ -812,6 +813,9 @@ export interface SandboxTemplate {
standard: boolean
/** The provider's own explanation for a failed build, when it reports one. */
error?: string
+ instance_type?: string
+ network_type?: string
+ allow_internet_access?: boolean
}
export interface SandboxTemplateCatalog {
@@ -921,12 +925,15 @@ 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.
+ * present. `replace_standard` deletes the existing WeKnora template first so
+ * a new spec (DNS, image) can take effect. The returned building item can be
+ * polled through the same endpoint.
*/
export function querySandboxTemplates(payload: {
config: SandboxConfig
config_id?: string
ensure_standard?: boolean
+ replace_standard?: boolean
}): Promise<{ data: SandboxTemplateCatalog }> {
return post('/api/v1/sandbox-configs/templates/query', payload) as unknown as Promise<{
data: SandboxTemplateCatalog
@@ -960,7 +967,10 @@ export function checkSandboxConfig(payload: {
* `sandbox_inventory_unverifiable` says the backend is unreachable, so nothing
* could be counted — the one case a force delete may override.
*/
-export type SandboxConflictCode = 'sandboxes_still_live' | 'sandbox_inventory_unverifiable'
+export type SandboxConflictCode =
+ | 'sandboxes_still_live'
+ | 'sandbox_inventory_unverifiable'
+ | 'skill_snapshot_blocks_template'
export interface SandboxConflict {
code: SandboxConflictCode
@@ -984,7 +994,8 @@ export function parseSandboxConflict(err: unknown): SandboxConflict | null {
if (!detail || typeof detail !== 'object') return null
if (
detail.code !== 'sandboxes_still_live' &&
- detail.code !== 'sandbox_inventory_unverifiable'
+ detail.code !== 'sandbox_inventory_unverifiable' &&
+ detail.code !== 'skill_snapshot_blocks_template'
) {
return null
}
diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue
index 3999cdd65..34fbb4541 100644
--- a/frontend/src/components/SandboxConfigEditorDrawer.vue
+++ b/frontend/src/components/SandboxConfigEditorDrawer.vue
@@ -60,7 +60,7 @@
Identity-change refusals must sit at the top: the form is long and the
admin otherwise saves, sees nothing, and assumes the click did nothing.
-->
- <div v-if="conflict && currentStepKey === 'runtime'" ref="conflictAlertRef" class="blocked blocked-top">
+ <div v-if="conflict" 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>
@@ -71,6 +71,8 @@
<p>{{ $t('settings.sandbox.blockedHint') }}</p>
</template>
</t-alert>
+ <t-alert v-else-if="conflict.code === 'skill_snapshot_blocks_template'" theme="warning"
+ :message="$t('settings.sandbox.templateLockedBySkills')" />
<t-alert v-else theme="warning" :message="$t('settings.sandbox.unverifiableBlocked')">
<template #description>
<p>{{ $t('settings.sandbox.unverifiableSaveHint') }}</p>
@@ -84,6 +86,7 @@
<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' }"
+ :disabled="hasSkillSnapshot"
@change="(v: any) => selectBackend(String(v))">
<t-option v-for="opt in backendOptions" :key="opt" :value="opt" :label="backendLabel(opt)">
<span class="backend-choice">
@@ -112,29 +115,31 @@
<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"
+ <t-alert v-if="hasSkillSnapshot" theme="info" class="identity-hint compact-alert"
+ :message="$t('settings.sandbox.connectionLockedBySkills')" />
+ <t-alert v-else-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')" />
+ :disabled="hasSkillSnapshot" @input="onConnectionInput('api_url')" />
</t-form-item>
<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')" />
+ :disabled="hasSkillSnapshot" @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')" />
+ :disabled="hasSkillSnapshot" @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" />
+ :disabled="hasSkillSnapshot" @input="invalidateConnection" />
<div class="field-hints">
<p class="section-help">
{{ storedSecrets.cube
@@ -147,13 +152,18 @@
</a>
</div>
</t-form-item>
+ <t-form-item :label="$t('settings.sandbox.cubeDnsServers')"
+ :help="$t('settings.sandbox.cubeDnsServersHelp')">
+ <t-tag-input v-model="cube.dns_servers" :placeholder="$t('settings.sandbox.cubeDnsServersPlaceholder')"
+ :disabled="hasSkillSnapshot" clearable @change="invalidateConnection" />
+ </t-form-item>
</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')" />
+ :disabled="hasSkillSnapshot" @input="onConnectionInput('api_key')" />
<div class="field-hints">
<p class="section-help">
{{ storedSecrets.e2b
@@ -168,15 +178,17 @@
</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-input v-model="e2b.api_url" placeholder="https://api.e2b.app"
+ :disabled="hasSkillSnapshot" @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-input v-model="e2b.sandbox_domain" placeholder="e2b.app"
+ :disabled="hasSkillSnapshot" @input="invalidateConnection" />
</t-form-item>
</div>
<t-form-item :label="$t('settings.sandbox.proxyUrl')" :help="$t('settings.sandbox.e2bProxyUrlOptional')">
<t-input v-model="e2b.proxy_url" placeholder="http://sandbox-gateway.example.com"
- @input="invalidateConnection" />
+ :disabled="hasSkillSnapshot" @input="invalidateConnection" />
</t-form-item>
</template>
<div class="private-endpoint-row">
@@ -184,7 +196,11 @@
<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" />
+ <t-switch
+ v-model="allowPrivateEndpoints"
+ :disabled="hasSkillSnapshot"
+ @change="invalidateConnection"
+ />
</div>
</section>
@@ -204,16 +220,19 @@
<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')" />
+ :disabled="hasSkillSnapshot" @input="onFieldInput('image')" />
+ <p v-if="hasSkillSnapshot" class="section-help section-help--field">
+ {{ $t('settings.sandbox.templateLockedBySkills') }}
+ </p>
</t-form-item>
<t-form-item :label="$t('settings.sandbox.dockerHost')" :help="$t('settings.sandbox.dockerHostHelp')">
<t-input v-model="docker.host" placeholder="unix:///var/run/docker.sock"
- @input="onFieldInput('host')" />
+ :disabled="hasSkillSnapshot" @input="onFieldInput('host')" />
</t-form-item>
<t-form-item :label="$t('settings.sandbox.dockerTlsCertPath')"
:help="$t('settings.sandbox.dockerTlsCertPathHelp')">
<t-input v-model="docker.tls_cert_path" placeholder="/etc/weknora/docker-certs"
- @input="onFieldInput('tls_cert_path')" />
+ :disabled="hasSkillSnapshot" @input="onFieldInput('tls_cert_path')" />
</t-form-item>
</template>
<t-alert v-else theme="warning" class="compact-alert" :message="$t('settings.sandbox.localRuntimeWarning')" />
@@ -222,79 +241,101 @@
<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)">
+ <t-button variant="text" size="small" :loading="templatesLoading" @click="loadTemplates()">
<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>
+ <t-alert v-if="hasSkillSnapshot" theme="info" class="compact-alert"
+ :message="$t('settings.sandbox.templateLockedBySkills')" />
<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">
+ <div v-else class="template-list" role="radiogroup" :aria-label="$t('settings.sandbox.sectionTemplate')">
+ <div v-if="canCreateStandard" class="template-row template-row--offer">
+ <div class="template-row__main">
+ <div class="template-row__head">
+ <span class="template-row__title">{{ $t('settings.sandbox.weknoraStandardTemplate') }}</span>
+ <t-tag theme="primary" variant="outline" 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">
+ <span class="template-row__spacer" />
+ <t-button theme="primary" variant="outline" size="small" :loading="templatesLoading"
+ @click="createStandardTemplate">
+ {{ $t('settings.sandbox.createStandardTemplate') }}
+ </t-button>
+ </div>
+ <p class="template-row__hint">{{ $t('settings.sandbox.createStandardTemplateHint') }}</p>
+ </div>
+ </div>
+ <div
+ v-for="item in templates"
+ :key="item.id"
+ class="template-row"
+ :class="{
+ 'is-active': currentTemplateId === item.id,
+ 'is-pending': isTemplatePending(item),
+ 'is-disabled': !isTemplateSelectable(item) || (hasSkillSnapshot && currentTemplateId !== item.id),
+ }"
+ role="radio"
+ :aria-checked="currentTemplateId === item.id"
+ :aria-disabled="!isTemplateSelectable(item) || (hasSkillSnapshot && currentTemplateId !== item.id)"
+ :tabindex="isTemplateSelectable(item) && !(hasSkillSnapshot && currentTemplateId !== item.id) ? 0 : -1"
+ @click="onTemplateCardClick(item)"
+ @keydown.enter.prevent="onTemplateCardClick(item)"
+ @keydown.space.prevent="onTemplateCardClick(item)"
+ >
+ <span class="template-row__marker" aria-hidden="true" />
+ <div class="template-row__main">
+ <div class="template-row__head">
+ <span class="template-row__title" :title="templateDisplayName(item)">
+ {{ templateDisplayName(item) }}
+ </span>
+ <t-tag v-if="item.standard" theme="primary" variant="outline" size="small">
+ {{ $t('settings.sandbox.recommendedTag') }}
+ </t-tag>
+ <span class="template-row__spacer" />
+ <t-tag :theme="templateStatusTheme(item)" variant="outline" size="small">
+ {{ templateStatusLabel(item) }}
+ </t-tag>
+ <span v-if="canRebuildTemplate(item)" class="template-row__rebuild" @click.stop>
+ <t-popconfirm
+ theme="warning"
+ :content="$t('settings.sandbox.replaceStandardTemplateConfirm')"
+ @confirm="replaceStandardTemplate"
+ >
+ <t-button variant="text" size="small" :loading="templatesLoading">
+ {{ $t('settings.sandbox.replaceStandardTemplate') }}
+ </t-button>
+ </t-popconfirm>
+ </span>
+ </div>
+ <dl v-if="templateFieldRows(item).length" class="template-row__fields">
+ <div v-for="field in templateFieldRows(item)" :key="field.key" class="template-row__field">
+ <dt>{{ field.label }}</dt>
+ <dd :class="{ 'is-mono': field.mono }" :title="field.value">{{ field.value }}</dd>
+ </div>
+ </dl>
+ <p v-if="isTemplateUntagged(item)" class="template-row__hint template-row__hint--error">
{{ $t('settings.sandbox.templateUntaggedHint') }}
- </span>
- <span v-else-if="templateFailureReason(item)" class="template-card__hint template-card__hint--error">
+ </p>
+ <p v-else-if="templateFailureReason(item)" class="template-row__hint template-row__hint--error">
{{ templateFailureReason(item) }}
- </span>
- <span v-else-if="isTemplatePending(item) && item.standard" class="template-card__hint">
+ </p>
+ <p v-else-if="isTemplatePending(item) && item.standard" class="template-row__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>
+ </p>
+ </div>
+ </div>
+ <div
+ v-if="templatesLoaded && !templates.length && !canCreateStandard && !templatesError"
+ class="env-empty"
+ >
+ {{ $t('settings.sandbox.noTemplates') }}
+ </div>
</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') }}
@@ -395,7 +436,12 @@
config whose save was refused.
-->
<template v-if="currentStepKey === 'skills'">
- <SandboxSkillsPanel v-if="effectiveRecord" :record="effectiveRecord" @updated="onSkillsConfigUpdated" />
+ <SandboxSkillsPanel
+ v-if="effectiveRecord"
+ :record="effectiveRecord"
+ @updated="onSkillsConfigUpdated"
+ @skills-changed="emit('skillsChanged')"
+ />
<p v-else class="skills-locked">{{ $t('settings.sandbox.stepSkillsLocked') }}</p>
</template>
@@ -470,6 +516,7 @@ const props = defineProps<{
const emit = defineEmits<{
(e: 'update:visible', value: boolean): void
(e: 'saved'): void
+ (e: 'skillsChanged', record?: SandboxConfigRecord): void
}>()
const { t } = useI18n()
@@ -524,6 +571,10 @@ 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))
+const clusterStandardTemplate = computed(() => templates.value.find((item) => item.standard && item.id))
+const canCreateStandard = computed(() => (
+ isRemoteBackend.value && templatesLoaded.value && !clusterStandardTemplate.value && !hasSkillSnapshot.value
+))
const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() => {
const steps: Array<{ key: SandboxStepKey; title: string }> = [
{ key: 'connection', title: t('settings.sandbox.stepConnection') },
@@ -573,9 +624,13 @@ const primaryDisabled = computed(() => (
// than create another one.
const savedRecord = ref<SandboxConfigRecord | null>(null)
const effectiveRecord = computed(() => savedRecord.value || props.record)
+const hasSkillSnapshot = computed(() => (
+ Boolean(effectiveRecord.value?.config?.skill_image?.snapshot_id?.trim())
+))
function onSkillsConfigUpdated(record: SandboxConfigRecord) {
savedRecord.value = record
+ emit('skillsChanged', record)
}
// Jumping is what separates editing from creating. A config that does not exist
@@ -600,7 +655,7 @@ function goToStep(index: number) {
// step still has to ask the cluster what it offers; a step already loaded
// just resumes its poll, as walking back through it always has.
if (templatesLoaded.value) scheduleTemplatePolling()
- else void loadTemplates(true)
+ else void loadTemplates()
}
const hasPendingTemplates = computed(() => templates.value.some(isTemplatePending))
@@ -711,6 +766,7 @@ function reset() {
Object.assign(cube, cfg.cube || {})
Object.assign(e2b, cfg.e2b || {})
Object.assign(docker, cfg.docker || {})
+ if (!Array.isArray(cube.dns_servers)) cube.dns_servers = []
if (backend.value === 'docker' && !docker.image) {
docker.image = 'wechatopenai/weknora-sandbox:latest'
}
@@ -783,8 +839,71 @@ function clearTemplateSelection() {
delete fieldErrors.value.template_id
}
-function templateMeta(item: SandboxTemplate): string {
- return [item.status, item.version, item.id].filter(Boolean).join(' · ')
+function onTemplateCardClick(item: SandboxTemplate) {
+ if (hasSkillSnapshot.value && item.id !== currentTemplateId.value) return
+ if (!isTemplateSelectable(item)) return
+ selectTemplate(item.id)
+}
+
+function canRebuildTemplate(item: SandboxTemplate): boolean {
+ return Boolean(item.standard && item.id) && !isTemplatePending(item) && !hasSkillSnapshot.value
+}
+
+function templateDisplayName(item: SandboxTemplate): string {
+ const name = item.name?.trim() || ''
+ const id = item.id?.trim() || ''
+ if (!name || name === id) return t('settings.sandbox.templateUnnamed')
+ return name
+}
+
+function formatTemplateTime(value?: string): string {
+ const raw = value?.trim()
+ if (!raw) return ''
+ const ms = Date.parse(raw)
+ if (Number.isNaN(ms)) return raw
+ return new Date(ms).toLocaleString()
+}
+
+function templateFieldRows(item: SandboxTemplate): Array<{ key: string; label: string; value: string; mono?: boolean }> {
+ const rows: Array<{ key: string; label: string; value: string; mono?: boolean }> = []
+ const image = item.image?.trim()
+ if (image) {
+ rows.push({ key: 'image', label: t('settings.sandbox.templateFieldImage'), value: image, mono: true })
+ }
+ const version = item.version?.trim()
+ if (version) {
+ rows.push({ key: 'version', label: t('settings.sandbox.templateFieldVersion'), value: version })
+ }
+ const id = item.id?.trim()
+ if (id) {
+ rows.push({ key: 'id', label: t('settings.sandbox.templateFieldId'), value: id, mono: true })
+ }
+ const created = formatTemplateTime(item.created_at)
+ if (created) {
+ rows.push({ key: 'created', label: t('settings.sandbox.templateFieldCreated'), value: created })
+ }
+ const instanceType = item.instance_type?.trim()
+ if (instanceType) {
+ rows.push({ key: 'instance', label: t('settings.sandbox.templateFieldInstance'), value: instanceType })
+ }
+ const networkType = item.network_type?.trim()
+ if (networkType) {
+ rows.push({ key: 'network', label: t('settings.sandbox.templateFieldNetwork'), value: networkType })
+ }
+ if (item.allow_internet_access === true) {
+ rows.push({
+ key: 'internet',
+ label: t('settings.sandbox.templateFieldInternet'),
+ value: t('settings.sandbox.templateInternetOn'),
+ })
+ } else if (item.allow_internet_access === false) {
+ rows.push({
+ key: 'internet',
+ label: t('settings.sandbox.templateFieldInternet'),
+ value: t('settings.sandbox.templateInternetOff'),
+ })
+ }
+ return rows
}
function isTemplateSelectable(item: SandboxTemplate): boolean {
@@ -795,7 +914,7 @@ function isTemplateSelectable(item: SandboxTemplate): boolean {
function isTemplatePending(item: SandboxTemplate): boolean {
const status = item.status?.trim().toLowerCase()
- return ['building', 'waiting', 'pending', 'queued', 'processing'].includes(status || '')
+ return ['building', 'waiting', 'pending', 'queued', 'processing', 'running'].includes(status || '')
}
// The backend reports this when a template's builds finished without the tag
@@ -847,7 +966,7 @@ function scheduleTemplatePolling() {
}, 3000)
}
-async function loadTemplates(ensureStandard: boolean, silent = false): Promise<boolean> {
+async function loadTemplates(ensureStandard = false, silent = false, replaceStandard = false): Promise<boolean> {
if (!hasImageCatalog.value) return true
if (!connectionReady()) return false
if (!silent) templatesLoading.value = true
@@ -857,17 +976,26 @@ async function loadTemplates(ensureStandard: boolean, silent = false): Promise<b
config: collectPayload(),
config_id: effectiveRecord.value?.id,
ensure_standard: ensureStandard,
+ replace_standard: replaceStandard,
})
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()
+ if (
+ currentTemplateId.value
+ && (!current || !isTemplateSelectable(current))
+ && !hasSkillSnapshot.value
+ ) {
+ 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'))
+ MessagePlugin.info(replaceStandard
+ ? t('settings.sandbox.standardTemplateReplaced')
+ : t('settings.sandbox.standardTemplateProvisioning'))
}
scheduleTemplatePolling()
return true
@@ -879,6 +1007,16 @@ async function loadTemplates(ensureStandard: boolean, silent = false): Promise<b
}
}
+function createStandardTemplate() {
+ return loadTemplates(true)
+}
+
+function replaceStandardTemplate() {
+ if (hasSkillSnapshot.value) return
+ clearTemplateSelection()
+ return loadTemplates(false, false, true)
+}
+
// 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 {
@@ -929,7 +1067,7 @@ async function handlePrimaryAction() {
if (isRemoteBackend.value) {
invalidateCheck()
wizardStep.value += 1
- await loadTemplates(true)
+ await loadTemplates()
return
}
// Docker's template is the image typed on this step. Kick a background
@@ -1174,6 +1312,14 @@ onUnmounted(stopTemplatePolling)
}
.sandbox-editor-form {
+ min-width: 0;
+ max-width: 100%;
+ overflow-x: hidden;
+
+ :deep(.setting-drawer__section) {
+ min-width: 0;
+ }
+
:deep(.t-form__item) {
margin-bottom: 0;
}
@@ -1283,54 +1429,13 @@ onUnmounted(stopTemplatePolling)
align-items: center;
justify-content: space-between;
gap: 12px;
+ min-width: 0;
.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;
@@ -1386,133 +1491,172 @@ onUnmounted(stopTemplatePolling)
display: flex;
flex-direction: column;
gap: 8px;
+ width: 100%;
+ min-width: 0;
+ max-width: 100%;
+ overflow-x: hidden;
}
-.template-card {
+.template-row {
display: flex;
- align-items: center;
- gap: 12px;
+ align-items: flex-start;
+ gap: 10px;
+ box-sizing: border-box;
width: 100%;
- min-height: 72px;
- padding: 12px 14px;
+ max-width: 100%;
+ min-width: 0;
+ padding: 10px 12px;
+ overflow: hidden;
border: 1px solid var(--td-component-stroke);
- border-radius: 10px;
+ border-radius: 8px;
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;
+ cursor: pointer;
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
- &:hover:not(:disabled) {
+ &:hover:not(.is-disabled):not(.template-row--offer) {
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;
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
}
- &.is-pending {
- background: color-mix(in srgb, var(--td-warning-color) 3%, var(--td-bg-color-container));
+ &.is-disabled {
+ cursor: default;
}
}
-.template-card__badge {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 36px;
- height: 36px;
+.template-row--offer {
+ cursor: default;
+ border-style: dashed;
+}
+
+.template-row__marker {
flex-shrink: 0;
- border-radius: 9px;
- background: rgba(0, 82, 217, 0.1);
- color: #0052d9;
- font-size: 16px;
+ width: 14px;
+ height: 14px;
+ margin-top: 3px;
+ box-sizing: border-box;
+ border: 1.5px solid var(--td-border-level-2-color, var(--td-component-stroke));
+ border-radius: 50%;
+ background: var(--td-bg-color-container);
+
+ .is-active & {
+ border-color: var(--td-brand-color);
+ box-shadow: inset 0 0 0 3.5px var(--td-brand-color);
+ }
- .is-pending & {
- background: color-mix(in srgb, var(--td-warning-color) 12%, transparent);
- color: var(--td-warning-color);
+ .is-disabled & {
+ opacity: 0.45;
}
}
-.template-card__body {
+.template-row__main {
display: flex;
flex: 1;
flex-direction: column;
- gap: 5px;
+ gap: 6px;
min-width: 0;
+ max-width: 100%;
}
-.template-card__title-row {
+.template-row__head {
display: flex;
align-items: center;
- gap: 6px;
+ gap: 8px;
min-width: 0;
+ max-width: 100%;
+
+ :deep(.t-tag) {
+ flex-shrink: 0;
+ }
}
-.template-card__title {
+.template-row__title {
+ flex: 0 1 auto;
+ min-width: 0;
overflow: hidden;
font-size: 13px;
font-weight: 600;
+ line-height: 22px;
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-row__spacer {
+ flex: 1 1 8px;
+ min-width: 8px;
}
-.template-card__hint {
- color: var(--td-warning-color);
+.template-row__rebuild {
+ flex-shrink: 0;
- &--error {
- color: var(--td-error-color);
+ :deep(.t-button) {
+ color: var(--td-text-color-secondary);
+ padding-left: 4px;
+ padding-right: 4px;
+
+ &:hover {
+ color: var(--td-text-color-primary);
+ }
}
}
-.template-card__state {
- display: flex;
- align-items: center;
- gap: 8px;
- flex-shrink: 0;
- align-self: flex-start;
- padding-top: 1px;
+.template-row__fields {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 4px 16px;
+ margin: 0;
+ min-width: 0;
}
-.template-card__selected {
- color: var(--td-brand-color);
- font-size: 17px;
+.template-row__field {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ align-items: baseline;
+ gap: 8px;
+ min-width: 0;
+
+ dt {
+ color: var(--td-text-color-placeholder);
+ font-size: 11px;
+ line-height: 18px;
+ white-space: nowrap;
+ }
+
+ dd {
+ margin: 0;
+ min-width: 0;
+ overflow: hidden;
+ color: var(--td-text-color-secondary);
+ font-size: 12px;
+ line-height: 18px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ &.is-mono {
+ font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 11px;
+ }
+ }
}
-.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);
+.template-row__hint {
+ margin: 0;
+ overflow-wrap: anywhere;
+ color: var(--td-text-color-placeholder);
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);
+ &--error {
+ color: var(--td-error-color);
}
}
@@ -1711,6 +1855,10 @@ onUnmounted(stopTemplatePolling)
.sandbox-step__title {
font-size: 12px;
}
+
+ .template-row__fields {
+ grid-template-columns: minmax(0, 1fr);
+ }
}
</style>
diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue
index eda44a441..bde9c006e 100644
--- a/frontend/src/components/SandboxSkillsPanel.vue
+++ b/frontend/src/components/SandboxSkillsPanel.vue
@@ -185,64 +185,92 @@
<t-icon name="folder" size="16px" />
</button>
</t-tooltip>
- <t-popup
- v-if="hasTranscript(skill)"
- :visible="expandedSkillId === skill.id"
- trigger="click"
- placement="bottom-right"
- attach="body"
- destroy-on-close
- overlay-class-name="skill-transcript-popup"
- :z-index="3200"
- :overlay-inner-style="{ padding: '0' }"
- @visible-change="(visible: boolean) => onTranscriptVisible(skill, visible)"
+ <t-tooltip
+ v-if="hasTranscript(skill) || isBusy(skill)"
+ :content="isBusy(skill)
+ ? $t('settings.sandbox.skillTranscriptLiveHint')
+ : $t('settings.sandbox.skillTranscript')"
+ placement="top"
>
+ <t-popup
+ v-if="hasTranscript(skill)"
+ :visible="expandedSkillId === skill.id"
+ trigger="click"
+ placement="bottom-right"
+ attach="body"
+ destroy-on-close
+ overlay-class-name="skill-transcript-popup"
+ :z-index="3200"
+ :overlay-inner-style="{ padding: '0' }"
+ @visible-change="(visible: boolean) => onTranscriptVisible(skill, visible)"
+ >
+ <button
+ type="button"
+ class="skill-item__icon-btn"
+ :class="{
+ 'is-on': expandedSkillId === skill.id,
+ 'is-live': isBusy(skill),
+ 'is-live-chip': isBusy(skill),
+ }"
+ :aria-label="$t('settings.sandbox.skillTranscript')"
+ >
+ <span v-if="isBusy(skill)" class="skill-item__live-dot" aria-hidden="true" />
+ <t-icon name="chat-bubble-history" size="16px" />
+ <span v-if="isBusy(skill)" class="skill-item__live-label">
+ {{ $t('settings.sandbox.skillTranscriptLive') }}
+ </span>
+ </button>
+ <template #content>
+ <div class="skill-transcript-popup__panel">
+ <header class="skill-transcript-popup__head">
+ <div class="skill-transcript-popup__head-text">
+ <div class="skill-transcript-popup__title">{{ skill.name || skill.id }}</div>
+ <div class="skill-transcript-popup__meta">
+ <span
+ class="skill-transcript-popup__status"
+ :data-status="skill.status"
+ >{{ statusLabel(skill) }}</span>
+ <span>{{ $t('settings.sandbox.skillTranscriptTitle') }}</span>
+ </div>
+ </div>
+ <t-button
+ variant="text"
+ shape="square"
+ size="small"
+ class="skill-transcript-popup__close"
+ :title="$t('common.close')"
+ @click.stop="onTranscriptVisible(skill, false)"
+ >
+ <template #icon><t-icon name="close" size="16px" /></template>
+ </t-button>
+ </header>
+ <div class="skill-transcript-popup__body">
+ <SkillInstallTimeline
+ :key="`${skill.id}-${skill.install_session_id || ''}-${transcriptEpoch}`"
+ compact
+ :config-id="record?.id || ''"
+ :skill-id="skill.id"
+ :session-id="skill.install_session_id || ''"
+ :message-id="skill.install_message_id || ''"
+ :live="skill.status === 'installing'"
+ />
+ </div>
+ </div>
+ </template>
+ </t-popup>
<button
+ v-else
type="button"
- class="skill-item__icon-btn"
- :class="{ 'is-on': expandedSkillId === skill.id }"
+ class="skill-item__icon-btn is-live is-live-chip"
:aria-label="$t('settings.sandbox.skillTranscript')"
>
+ <span class="skill-item__live-dot" aria-hidden="true" />
<t-icon name="chat-bubble-history" size="16px" />
+ <span class="skill-item__live-label">
+ {{ $t('settings.sandbox.skillTranscriptLive') }}
+ </span>
</button>
- <template #content>
- <div class="skill-transcript-popup__panel">
- <header class="skill-transcript-popup__head">
- <div class="skill-transcript-popup__head-text">
- <div class="skill-transcript-popup__title">{{ skill.name || skill.id }}</div>
- <div class="skill-transcript-popup__meta">
- <span
- class="skill-transcript-popup__status"
- :data-status="skill.status"
- >{{ statusLabel(skill) }}</span>
- <span>{{ $t('settings.sandbox.skillTranscriptTitle') }}</span>
- </div>
- </div>
- <t-button
- variant="text"
- shape="square"
- size="small"
- class="skill-transcript-popup__close"
- :title="$t('common.close')"
- @click.stop="onTranscriptVisible(skill, false)"
- >
- <template #icon><t-icon name="close" size="16px" /></template>
- </t-button>
- </header>
- <div class="skill-transcript-popup__body">
- <SkillInstallTimeline
- :key="`${skill.id}-${skill.install_session_id || ''}-${transcriptEpoch}`"
- compact
- :config-id="record?.id || ''"
- :skill-id="skill.id"
- :session-id="skill.install_session_id || ''"
- :message-id="skill.install_message_id || ''"
- :live="skill.status === 'installing'"
- />
- </div>
- </div>
- </template>
- </t-popup>
+ </t-tooltip>
<t-popconfirm
theme="warning"
:content="deleteHint"
@@ -335,6 +363,7 @@ const props = defineProps<{
const emit = defineEmits<{
updated: [record: SandboxConfigRecord]
+ skillsChanged: []
}>()
const { t, locale } = useI18n()
@@ -617,19 +646,33 @@ async function refreshImage() {
const res = await getSandboxConfigById(props.record.id)
skillImage.value = res?.data?.config?.skill_image || null
skillRollout.value = normalizeSkillRollout(res?.data?.config?.skill_rollout)
+ if (res?.data) emit('updated', res.data)
} catch {
- skillImage.value = props.record.config?.skill_image || null
+ skillImage.value = skillImage.value || props.record.config?.skill_image || null
+ emit('skillsChanged')
}
}
+function skillsSignature(list: ConfigSkill[]): string {
+ return list.map((skill) => `${skill.id}:${skill.status}:${skill.enabled ? 1 : 0}`).join('|')
+}
+
async function loadSkills(silent = false) {
if (!props.record) return
if (!silent) loading.value = true
+ const previous = skillsSignature(skills.value)
+ const wasBusy = skills.value.some(isBusy)
try {
const res = await listConfigSkills(props.record.id)
skills.value = res?.data || []
followBusySkills()
ensurePoll()
+ if (skillsSignature(skills.value) !== previous) {
+ emit('skillsChanged')
+ }
+ if (wasBusy && !skills.value.some(isBusy)) {
+ void refreshImage()
+ }
} catch (e: any) {
if (!silent) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillLoadFailed'))
@@ -812,6 +855,7 @@ async function removeSkill(skill: ConfigSkill) {
await deleteConfigSkill(props.record.id, skill.id)
MessagePlugin.success(t('settings.sandbox.skillDeleteAccepted'))
await loadSkills()
+ await refreshImage()
followProgress(skill.id)
} catch (e: any) {
MessagePlugin.error(e?.message || t('common.deleteFailed'))
@@ -1205,11 +1249,49 @@ onUnmounted(() => {
color: var(--td-brand-color);
}
+ &.is-live {
+ color: var(--td-brand-color);
+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ }
+
+ &.is-live-chip {
+ width: auto;
+ min-width: 26px;
+ padding: 0 8px;
+ gap: 5px;
+ }
+
&--danger:hover:not(:disabled) {
background: var(--td-error-color-1, var(--td-bg-color-secondarycontainer));
color: var(--td-error-color);
}
}
+
+.skill-item__live-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--td-brand-color);
+ animation: skill-transcript-dot 2.4s ease-in-out infinite;
+}
+
+.skill-item__live-label {
+ font-size: 12px;
+ font-weight: 500;
+ line-height: 1;
+ white-space: nowrap;
+}
+
+@keyframes skill-transcript-dot {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.45;
+ }
+}
</style>
<style lang="less">
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index d3c57991d..bf8cab583 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -1105,6 +1105,7 @@ export default {
sectionEnvironment: 'Environment variables',
noConfigs: 'No sandbox 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.',
+ connectionLockedBySkills: 'This sandbox already has skills. Connection, credentials, and DNS would retarget the skill snapshot, and DNS only applies after a template rebuild. Create a new sandbox instead.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryDrawerDesc: 'Sandboxes this config still holds, plus the sessions and agents affected.',
@@ -1155,18 +1156,35 @@ export default {
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.',
+ templateLoadHint: 'Enter the cluster connection and refresh. If there is no WeKnora standard template, click Create; after changing DNS or the image, click Delete and rebuild.',
templateLoadFailed: 'Failed to load templates',
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
+ standardTemplateReplaced: 'The previous standard template was deleted and a rebuild has started. Wait until it is ready.',
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.',
+ templateStepHint: 'This step only lists templates already on the cluster; it does not create one automatically. Click Create WeKnora standard template if none exists, or Delete and rebuild after changing DNS or the image. 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.',
+ templateBuildingHint: 'The standard template is being built. 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.',
templateFailedReason: 'Build failed: {reason}',
noTemplates: 'No templates were returned by this cluster.',
+ weknoraStandardTemplate: 'WeKnora standard template',
+ createStandardTemplate: 'Create',
+ createStandardTemplateHint: 'Built with the current connection settings, including DNS. After changing those settings, rebuild from the card.',
+ replaceStandardTemplate: 'Rebuild',
+ replaceStandardTemplateConfirm: 'This deletes the WeKnora standard template on the cluster and rebuilds it with the current settings, including DNS. Sandboxes already using that template may no longer start.',
+ templateLockedBySkills: 'This sandbox already has skills. The skill environment is bound to the current snapshot, so the runtime template cannot be changed or rebuilt. Create a new sandbox and install skills from the new template.',
+ templateUnnamed: 'Unnamed template',
+ templateFieldImage: 'Image',
+ templateFieldVersion: 'Version',
+ templateFieldId: 'ID',
+ templateFieldCreated: 'Created',
+ templateFieldInstance: 'Instance type',
+ templateFieldNetwork: 'Network',
+ templateFieldInternet: 'Internet access',
+ templateInternetOn: 'On',
+ templateInternetOff: 'Off',
templateReadyHint: 'Template “{name}” is ready and selected.',
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
templateStatuses: {
@@ -1183,6 +1201,9 @@ export default {
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
cubeApiKeyWhere: 'How to enable auth on a self-hosted cluster',
+ cubeDnsServers: 'DNS servers',
+ cubeDnsServersHelp: 'Optional. Nameserver IPs written into the WeKnora standard template. Leave empty to use the cluster default (commonly 119.29.29.29). If UDP/53 to public resolvers is blocked, use reachable addresses from the Cube host\'s /etc/resolv.conf, excluding 10/8, 172.16/12, and 192.168/16. Existing standard templates take effect only after Rebuild on the template card.',
+ cubeDnsServersPlaceholder: 'e.g. 8.8.8.8, press Enter to add',
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',
@@ -1304,6 +1325,8 @@ export default {
imageInfoEmpty: 'Using the base template',
imageInfoUnset: 'Not set',
skillTranscript: 'View install run',
+ skillTranscriptLive: 'Install log',
+ skillTranscriptLiveHint: 'Installing — click to watch',
skillTranscriptTitle: 'Install run',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 04a6d5076..c0c6f1c16 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -4958,6 +4958,7 @@ export default {
sectionEnvironment: 'Environment variables',
noConfigs: '아직 샌드박스가 없습니다. 워크스페이스 설정을 선택하지 않은 에이전트는 스킬 스크립트를 실행하지 않습니다.',
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
+ connectionLockedBySkills: '이 샌드박스에는 이미 Skill이 있습니다. 연결, 자격 증명, DNS를 바꾸면 스킬 스냅샷의 환경이 달라지고, DNS는 템플릿을 재구축해야 적용됩니다. 새 샌드박스를 만드세요.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryDrawerDesc: '이 설정이 아직 점유한 샌드박스와 영향을 받는 세션·에이전트입니다.',
@@ -5008,18 +5009,35 @@ export default {
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.',
+ templateLoadHint: '클러스터 연결을 입력한 뒤 새로고침하세요. WeKnora 표준 템플릿이 없으면 「만들기」를, DNS나 이미지를 바꾼 뒤에는 「삭제 후 재구축」을 누르세요.',
templateLoadFailed: 'Failed to load templates',
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
+ standardTemplateReplaced: '기존 표준 템플릿을 삭제했고 재구축을 시작했습니다. 준비될 때까지 기다리세요.',
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.',
+ templateStepHint: '이 단계에서는 클러스터에 이미 있는 템플릿만 나열하며 자동으로 만들지 않습니다. 표준 템플릿이 없으면 「WeKnora 표준 템플릿 만들기」를, DNS나 이미지를 바꾼 뒤에는 「삭제 후 재구축」을 누르세요. 템플릿이 준비된 뒤에 계속할 수 있습니다.',
loadingTemplates: 'Loading templates from the cluster...',
- templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',
+ templateBuildingHint: '표준 템플릿을 구축하는 중입니다. 목록이 자동으로 새로고침됩니다.',
templateUntaggedHint: '빌드는 끝났지만 default 태그가 붙은 빌드가 없어 샌드박스 생성 시 이 템플릿을 찾을 수 없습니다. E2B에서 템플릿을 삭제하고 새로고침하면 WeKnora가 다시 빌드합니다.',
templateFailedReason: '빌드 실패: {reason}',
noTemplates: 'No templates were returned by this cluster.',
+ weknoraStandardTemplate: 'WeKnora 표준 템플릿',
+ createStandardTemplate: '만들기',
+ createStandardTemplateHint: '현재 연결 설정(DNS 포함)으로 구축합니다. 설정을 바꾼 뒤에는 카드에서 재구축하세요.',
+ replaceStandardTemplate: '재구축',
+ replaceStandardTemplateConfirm: '클러스터의 WeKnora 표준 템플릿을 삭제한 뒤 현재 설정(DNS 포함)으로 다시 만듭니다. 해당 템플릿을 쓰는 기존 샌드박스는 더 이상 시작되지 않을 수 있습니다.',
+ templateLockedBySkills: '이 샌드박스에는 이미 Skill이 설치되어 있습니다. 스킬 환경이 현재 스냅샷에 묶여 있어 런타임 템플릿을 바꾸거나 재구축할 수 없습니다. 새 샌드박스를 만들고 새 템플릿에서 Skill을 다시 설치하세요.',
+ templateUnnamed: '이름 없는 템플릿',
+ templateFieldImage: '이미지',
+ templateFieldVersion: '버전',
+ templateFieldId: 'ID',
+ templateFieldCreated: '생성 시간',
+ templateFieldInstance: '인스턴스 유형',
+ templateFieldNetwork: '네트워크',
+ templateFieldInternet: '인터넷 접근',
+ templateInternetOn: '켜짐',
+ templateInternetOff: '꺼짐',
templateReadyHint: 'Template “{name}” is ready and selected.',
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
templateStatuses: {
@@ -5036,6 +5054,9 @@ export default {
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
cubeApiKeyWhere: '자체 호스팅 클러스터에서 인증을 켜는 방법',
+ cubeDnsServers: 'DNS 서버',
+ cubeDnsServersHelp: '선택 사항입니다. WeKnora 표준 템플릿에 기록되는 nameserver IP입니다. 비워 두면 클러스터 기본값(보통 119.29.29.29)을 사용합니다. 공용 DNS로 UDP/53이 나가지 않으면 Cube 호스트 /etc/resolv.conf에서 도달 가능한 주소를 넣고, 10/8, 172.16/12, 192.168/16은 피하세요. 이미 있는 표준 템플릿은 카드에서 「재구축」을 눌러야 변경이 적용됩니다.',
+ cubeDnsServersPlaceholder: '예: 8.8.8.8, Enter로 추가',
e2bApiKeyHelp: 'E2B 대시보드의 API Keys 페이지에서 생성하며 보통 e2b_ 로 시작합니다.',
e2bApiKeyWhere: 'E2B 대시보드에서 API 키 발급받기',
apiKeyPlaceholder: 'API 키를 붙여넣으세요',
@@ -5156,7 +5177,9 @@ export default {
imageInfoUsingBase: '아직 설치된 스킬이 없습니다. 세션은 선택한 런타임 템플릿으로 시작됩니다.',
imageInfoEmpty: 'Using the base template',
imageInfoUnset: '설정되지 않음',
- skillTranscript: 'View install run',
+ skillTranscript: '설치 과정 보기',
+ skillTranscriptLive: '설치 과정',
+ skillTranscriptLiveHint: '설치 중입니다. 클릭해서 과정을 보세요',
skillTranscriptTitle: '설치 과정',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 51a2339b9..bb72bb845 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -4958,6 +4958,7 @@ export default {
sectionEnvironment: 'Environment variables',
noConfigs: 'Песочниц пока нет. Агенты без конфигурации пространства не выполняют скрипты навыков.',
identityFieldHint: 'While this config owns sandboxes, these cannot be changed: backend type, API endpoint, API key, sandbox domain, proxy endpoint.',
+ connectionLockedBySkills: 'В этой песочнице уже установлены навыки. Смена подключения, учётных данных или DNS меняет среду снимка, а DNS применяется только после пересборки шаблона. Создайте новую песочницу.',
viewSandboxes: 'View sandbox usage',
inventoryTitle: 'Sandbox usage',
inventoryDrawerDesc: 'Песочницы, которые всё ещё занимает эта конфигурация, а также затронутые сессии и агенты.',
@@ -5008,18 +5009,35 @@ export default {
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.',
+ templateLoadHint: 'Введите подключение к кластеру и обновите список. Если стандартного шаблона WeKnora нет, нажмите «Создать»; после смены DNS или образа — «Удалить и пересобрать».',
templateLoadFailed: 'Failed to load templates',
standardTemplateProvisioning: 'The WeKnora standard template is being created. Refresh shortly to see its status.',
+ standardTemplateReplaced: 'Предыдущий стандартный шаблон удалён, начата пересборка. Дождитесь готовности.',
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.',
+ templateStepHint: 'На этом шаге только перечисляются шаблоны, уже есть в кластере; ничего не создаётся автоматически. Если стандартного шаблона нет, нажмите «Создать стандартный шаблон WeKnora»; после смены DNS или образа — «Удалить и пересобрать». Продолжить можно, когда шаблон готов.',
loadingTemplates: 'Loading templates from the cluster...',
- templateBuildingHint: 'The standard template is being built automatically. This list will refresh.',
+ templateBuildingHint: 'Стандартный шаблон собирается. Список обновится автоматически.',
templateUntaggedHint: 'Сборки завершены, но ни одна не имеет тега default, поэтому при создании песочницы шаблон не находится. Удалите его в E2B и обновите список — WeKnora пересоберёт шаблон.',
templateFailedReason: 'Сборка не удалась: {reason}',
noTemplates: 'No templates were returned by this cluster.',
+ weknoraStandardTemplate: 'Стандартный шаблон WeKnora',
+ createStandardTemplate: 'Создать',
+ createStandardTemplateHint: 'Собирается с текущими настройками подключения, включая DNS. После их изменения пересоберите шаблон на карточке.',
+ replaceStandardTemplate: 'Пересобрать',
+ replaceStandardTemplateConfirm: 'Стандартный шаблон WeKnora будет удалён из кластера и собран заново с текущими настройками, включая DNS. Песочницы, которые уже используют этот шаблон, могут больше не запускаться.',
+ templateLockedBySkills: 'В этой песочнице уже установлены навыки. Среда навыков привязана к текущему снимку, поэтому шаблон нельзя сменить или пересобрать. Создайте новую песочницу и установите навыки с нового шаблона.',
+ templateUnnamed: 'Шаблон без имени',
+ templateFieldImage: 'Образ',
+ templateFieldVersion: 'Версия',
+ templateFieldId: 'ID',
+ templateFieldCreated: 'Создан',
+ templateFieldInstance: 'Тип инстанса',
+ templateFieldNetwork: 'Сеть',
+ templateFieldInternet: 'Доступ в интернет',
+ templateInternetOn: 'Вкл.',
+ templateInternetOff: 'Выкл.',
templateReadyHint: 'Template “{name}” is ready and selected.',
templateProvisioningHint: 'A template is still being built. The status refreshes automatically.',
templateStatuses: {
@@ -5036,6 +5054,9 @@ export default {
fieldRequired: 'Required',
cubeApiKeyOptional: 'Optional — leave empty for an unauthenticated self-hosted CubeSandbox',
cubeApiKeyWhere: 'Как включить аутентификацию в собственном кластере',
+ cubeDnsServers: 'DNS-серверы',
+ cubeDnsServersHelp: 'Необязательно. IP nameserver, которые записываются в стандартный шаблон WeKnora. Пустое значение оставляет значение кластера по умолчанию (обычно 119.29.29.29). Если UDP/53 до публичных резолверов недоступен, укажите достижимые адреса из /etc/resolv.conf хоста Cube, исключая 10/8, 172.16/12 и 192.168/16. Чтобы изменение вступило в силу, на карточке шаблона нажмите «Пересобрать».',
+ cubeDnsServersPlaceholder: 'например 8.8.8.8, Enter чтобы добавить',
e2bApiKeyHelp: 'Создайте ключ на странице API Keys в консоли E2B; обычно он начинается с e2b_.',
e2bApiKeyWhere: 'Получить API-ключ в консоли E2B',
apiKeyPlaceholder: 'Вставьте API-ключ',
@@ -5156,7 +5177,9 @@ export default {
imageInfoUsingBase: 'Навыки ещё не установлены. Сессии запускаются с выбранного шаблона среды.',
imageInfoEmpty: 'Using the base template',
imageInfoUnset: 'Не задано',
- skillTranscript: 'View install run',
+ skillTranscript: 'Смотреть ход установки',
+ skillTranscriptLive: 'Ход установки',
+ skillTranscriptLiveHint: 'Идёт установка — нажмите, чтобы смотреть',
skillTranscriptTitle: 'Ход установки',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index ee14fe139..407179e67 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -4960,6 +4960,7 @@ export default {
sectionEnvironment: '环境变量',
noConfigs: '还没有沙箱配置。智能体未选择空间配置时不会执行技能脚本。',
identityFieldHint: '该配置下有沙箱运行时,以下项无法修改:后端类型、API 端点、API Key、沙箱域名、Proxy 端点。',
+ connectionLockedBySkills: '该沙箱已安装 Skill。连接地址、凭据和 DNS 会改变技能快照所属环境,且 DNS 需重建模板才能生效;请新建一份沙箱。',
viewSandboxes: '查看沙箱占用',
inventoryTitle: '沙箱占用',
inventoryDrawerDesc: '该配置当前占用的沙箱,以及受影响的会话与智能体。',
@@ -5010,18 +5011,35 @@ export default {
refreshTemplates: '刷新模板',
templateSelectHelp: '模板由当前集群实时返回,保存时仅记录模板 ID,无需手工复制。',
templateSelectPlaceholder: '先连接集群并加载模板',
- templateLoadHint: '填写集群连接后刷新模板;若缺少 WeKnora 标准模板,系统会自动创建。',
+ templateLoadHint: '填写集群连接后刷新模板。没有 WeKnora 标准模板时点「创建」;改 DNS 或镜像后点「删除并重建」。',
templateLoadFailed: '模板列表加载失败',
standardTemplateProvisioning: '已开始在集群中创建 WeKnora 标准模板,请稍后刷新查看状态',
+ standardTemplateReplaced: '已删除原标准模板并开始重建,请等待状态就绪',
templateNotReady: '所选模板尚未构建完成,请刷新并等待状态就绪',
connectionPassed: '连接验证通过,以下模板均从当前集群实时加载。',
connectionPassedTitle: '集群连接成功',
- templateStepHint: '集群缺少标准模板时,WeKnora 会自动创建;模板就绪后才能继续。',
+ templateStepHint: '进入此步只会列出集群已有模板,不会自动创建。没有标准模板时点「创建 WeKnora 标准模板」;改 DNS 或镜像后点「删除并重建」。模板就绪后才能继续。',
loadingTemplates: '正在从集群加载模板…',
- templateBuildingHint: '标准模板正在自动构建,列表会自动刷新。',
+ templateBuildingHint: '标准模板正在构建,列表会自动刷新。',
templateUntaggedHint: '构建已完成,但没有构建带 default 标签,创建沙箱时无法解析。请在 E2B 删除该模板,刷新后 WeKnora 会重新构建。',
templateFailedReason: '构建失败:{reason}',
noTemplates: '当前集群未返回可用模板。',
+ weknoraStandardTemplate: 'WeKnora 标准模板',
+ createStandardTemplate: '创建',
+ createStandardTemplateHint: '按当前连接配置构建,包含 DNS。之后改配置可在卡片上重建。',
+ replaceStandardTemplate: '重建',
+ replaceStandardTemplateConfirm: '将删除集群上的 WeKnora 标准模板,并用当前配置(含 DNS)重新构建。使用该模板的存量沙箱可能无法再启动。',
+ templateLockedBySkills: '该沙箱已安装 Skill,技能环境绑在当前快照上,不能更换或重建运行模板。请新建一份沙箱,从新模板再装 Skill。',
+ templateUnnamed: '未命名模板',
+ templateFieldImage: '镜像',
+ templateFieldVersion: '版本',
+ templateFieldId: 'ID',
+ templateFieldCreated: '创建时间',
+ templateFieldInstance: '规格',
+ templateFieldNetwork: '网络',
+ templateFieldInternet: '公网访问',
+ templateInternetOn: '已开启',
+ templateInternetOff: '已关闭',
templateReadyHint: '模板「{name}」已就绪并选中。',
templateProvisioningHint: '模板仍在构建中,状态会自动刷新。',
templateStatuses: {
@@ -5038,6 +5056,9 @@ export default {
fieldRequired: '必填',
cubeApiKeyOptional: '可留空 —— 自建 CubeSandbox 通常无鉴权',
cubeApiKeyWhere: '自建集群如何开启鉴权',
+ cubeDnsServers: 'DNS 服务器',
+ cubeDnsServersHelp: '可选。写入 WeKnora 标准模板的 nameserver(须为 IP)。留空则使用集群默认(常见 119.29.29.29)。私网或云上 UDP 53 出不去时,填 Cube 宿主机 /etc/resolv.conf 里能用的地址,并避开 10/8、172.16/12、192.168/16。已有标准模板需在模板卡片上点「重建」才会生效。',
+ cubeDnsServersPlaceholder: '例如 8.8.8.8,回车添加',
e2bApiKeyHelp: '在 E2B 控制台的 API Keys 页面创建,通常以 e2b_ 开头。',
e2bApiKeyWhere: '前往 E2B 控制台获取 API Key',
apiKeyPlaceholder: '粘贴 API Key',
@@ -5159,6 +5180,8 @@ export default {
imageInfoEmpty: '使用基础模板',
imageInfoUnset: '未设置',
skillTranscript: '查看安装过程',
+ skillTranscriptLive: '安装过程',
+ skillTranscriptLiveHint: '正在安装,点击查看过程',
skillTranscriptTitle: '安装过程',
skillTranscriptHide: '收起安装过程',
skillTranscriptEmpty: '这次安装没有留下记录。',
diff --git a/frontend/src/views/settings/SandboxSettings.vue b/frontend/src/views/settings/SandboxSettings.vue
index b54be1780..31ffb1613 100644
--- a/frontend/src/views/settings/SandboxSettings.vue
+++ b/frontend/src/views/settings/SandboxSettings.vue
@@ -139,7 +139,8 @@
</t-loading>
<SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"
- :preset-type="activeType === 'all' ? '' : activeType" :initial-step="editorStep" @saved="load" />
+ :preset-type="activeType === 'all' ? '' : activeType" :initial-step="editorStep"
+ @saved="load" @skills-changed="onSkillsChanged" />
<!--
Occupancy is a list of sessions and agents, not a one-line status, and it
@@ -484,6 +485,13 @@ async function load() {
await loadSkills(records.value)
}
+async function onSkillsChanged(record?: SandboxConfigRecord) {
+ if (record?.id) {
+ records.value = records.value.map((item) => (item.id === record.id ? { ...item, ...record } : item))
+ }
+ await loadSkills(records.value)
+}
+
async function setScriptsDisabled(disabled: boolean) {
policySaving.value = true
try {
diff --git a/internal/application/service/tenant_sandbox_config.go b/internal/application/service/tenant_sandbox_config.go
index 3db673715..56c44b67a 100644
--- a/internal/application/service/tenant_sandbox_config.go
+++ b/internal/application/service/tenant_sandbox_config.go
@@ -71,6 +71,68 @@ func SandboxIdentityChanged(oldCfg, newCfg *types.TenantSandboxConfig) bool {
return sandbox.IdentityOf(oldCfg) != sandbox.IdentityOf(newCfg)
}
+func configHasSkillSnapshot(cfg *types.TenantSandboxConfig) bool {
+ return cfg != nil && cfg.SkillImage != nil && strings.TrimSpace(cfg.SkillImage.SnapshotID) != ""
+}
+
+// spawnTemplateID is the template/image this config would boot without a
+// skill snapshot. Cube and E2B store it as template_id; Docker as the image.
+func spawnTemplateID(cfg *types.TenantSandboxConfig) string {
+ if cfg == nil {
+ return ""
+ }
+ switch sandbox.SandboxType(cfg.SandboxType) {
+ case sandbox.SandboxTypeCube:
+ if cfg.Cube != nil {
+ return strings.TrimSpace(cfg.Cube.TemplateID)
+ }
+ case sandbox.SandboxTypeE2B:
+ if cfg.E2B != nil {
+ return strings.TrimSpace(cfg.E2B.TemplateID)
+ }
+ case sandbox.SandboxTypeDocker:
+ if cfg.Docker != nil {
+ return strings.TrimSpace(cfg.Docker.Image)
+ }
+ }
+ return ""
+}
+
+func cubeDNSServers(cfg *types.TenantSandboxConfig) []string {
+ if cfg == nil || cfg.Cube == nil {
+ return nil
+ }
+ return cfg.Cube.DNSServers
+}
+
+func sameStrings(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+// skillSnapshotBlocksConnectionChange reports edits that would retarget the
+// environment a skill snapshot was built from: identity, spawn template, or
+// Cube DNS (which only applies if the template is rebuilt).
+func skillSnapshotBlocksConnectionChange(stored, merged *types.TenantSandboxConfig) bool {
+ if !configHasSkillSnapshot(stored) {
+ return false
+ }
+ if SandboxIdentityChanged(stored, merged) {
+ return true
+ }
+ if spawnTemplateID(stored) != spawnTemplateID(merged) {
+ return true
+ }
+ return !sameStrings(cubeDNSServers(stored), cubeDNSServers(merged))
+}
+
// ErrSandboxesStillLive is returned when an identity change or deletion is
// refused because the current credentials still own provider resources.
var ErrSandboxesStillLive = stderrors.New("sandbox config still owns live sandboxes")
@@ -109,6 +171,14 @@ var ErrNamedSandboxBackendUnsupported = stderrors.New(
"named sandbox configs only support cube, e2b, docker and local backends",
)
+// ErrSkillSnapshotBlocksTemplateChange is returned when this config already
+// has a skill snapshot and the caller tries to retarget its connection, DNS,
+// or spawn template, or to rebuild the cluster's WeKnora template. Sessions
+// boot the snapshot, so those edits would not reach them. The way out is a
+// second config.
+var ErrSkillSnapshotBlocksTemplateChange = stderrors.New(
+ "sandbox connection cannot change while this config has a skill snapshot")
+
// ErrSkillSnapshotReleaseFailed is returned when deleting a sandbox config
// cannot destroy every provider snapshot on that config's ledger. Leaving the
// row is recoverable; leaking a billable snapshot is not.
@@ -190,9 +260,10 @@ type UpdateSandboxConfigInput struct {
// 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
+ Config *types.TenantSandboxConfig
+ ConfigID string
+ EnsureStandard bool
+ ReplaceStandard bool
}
type SandboxTemplateCatalog struct {
@@ -266,6 +337,13 @@ func SanitizeSandboxConfig(
return nil, err
}
}
+ if merged.Cube != nil {
+ dns, err := sandbox.NormalizeCubeDNSServers(merged.Cube.DNSServers)
+ if err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
+ merged.Cube.DNSServers = dns
+ }
for _, endpoint := range sandboxConfigEndpoints(merged) {
if err := sandbox.ValidateOutboundURLWithPolicy(endpoint, sandbox.OutboundURLPolicy{
AllowPrivate: merged.AllowPrivateEndpoints,
@@ -456,6 +534,9 @@ func (s *TenantSandboxConfigService) QueryTemplates(
}
existing = entity.Config
}
+ if in.ReplaceStandard && configHasSkillSnapshot(existing) {
+ return nil, ErrSkillSnapshotBlocksTemplateChange
+ }
merged := types.MergeSandboxConfigForUpdate(in.Config, existing)
if merged == nil {
merged = types.MergeSandboxConfigForUpdate(existing, nil)
@@ -526,12 +607,17 @@ func (s *TenantSandboxConfigService) QueryTemplates(
if usable != nil {
result.StandardTemplateID = usable.ID
}
- // A template whose build failed cannot spawn anything, so it does not count
- // as "this cluster already has one" — leaving it at that is what kept a
- // broken cluster broken no matter how often the admin hit refresh.
- if in.EnsureStandard && usable == nil {
+ // Listing is read-only. Creating or replacing the WeKnora template is an
+ // explicit settings-page action: auto-ensure on every refresh made DNS
+ // and image changes impossible to apply, and left admins unsure whether
+ // they had asked for a build.
+ wantStandard := in.ReplaceStandard || (in.EnsureStandard && usable == nil)
+ if wantStandard {
key := ensureTemplateKey(tenantID, sandbox.IdentityOf(merged))
ensured, ensureErr, _ := s.ensureTemplate.Do(key, func() (any, error) {
+ if in.ReplaceStandard {
+ return catalog.ReplaceStandardTemplate(ctx)
+ }
return catalog.EnsureStandardTemplate(ctx)
})
if ensureErr != nil {
@@ -541,9 +627,23 @@ func (s *TenantSandboxConfigService) QueryTemplates(
if !ok || standard == nil {
return nil, fmt.Errorf("sandbox: provider %q returned no standard template", effective.Type)
}
- result.Provisioned = true
- result.StandardTemplateID = standard.ID
+ if in.ReplaceStandard {
+ // The listing above still contains the template we just deleted.
+ kept := result.Templates[:0]
+ for _, item := range result.Templates {
+ if !item.Standard {
+ kept = append(kept, item)
+ }
+ }
+ result.Templates = kept
+ }
result.Templates = deduplicateSandboxTemplates(append(result.Templates, *standard))
+ if !sandbox.IsTemplateBuildFailed(standard.Status) {
+ result.Provisioned = true
+ result.StandardTemplateID = standard.ID
+ } else if in.ReplaceStandard {
+ result.StandardTemplateID = ""
+ }
}
sort.SliceStable(result.Templates, func(i, j int) bool {
if result.Templates[i].Standard != result.Templates[j].Standard {
@@ -620,7 +720,7 @@ 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":
+ case "building", "waiting", "pending", "queued", "processing", "running":
return 2
case "failed", "error", "cancelled", "canceled":
return 1
@@ -691,6 +791,9 @@ func (s *TenantSandboxConfigService) Update(
if err := validateNamedSandboxBackend(merged); err != nil {
return nil, err
}
+ if skillSnapshotBlocksConnectionChange(entity.Config, merged) {
+ return nil, ErrSkillSnapshotBlocksTemplateChange
+ }
if !SandboxIdentityChanged(entity.Config, merged) {
return s.writeConfig(ctx, entity, in, merged)
}
diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go
index 1ff3db1cb..10de726d8 100644
--- a/internal/application/service/tenant_sandbox_config_test.go
+++ b/internal/application/service/tenant_sandbox_config_test.go
@@ -113,6 +113,16 @@ func TestSandboxIdentityChanged(t *testing.T) {
new: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
want: false,
},
+ {
+ name: "cube dns change only affects future templates",
+ old: cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app"),
+ new: func() *types.TenantSandboxConfig {
+ cfg := cubeCfg("key-a", "https://cube.example.com", "https://proxy.example.com", "cube.app")
+ cfg.Cube.DNSServers = []string{"192.0.2.53"}
+ return cfg
+ }(),
+ want: false,
+ },
{
name: "private endpoint policy changes transport identity",
old: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
@@ -294,11 +304,14 @@ type stubProviderClient struct {
// overlap, which is the only way to observe whether they were collapsed.
ensureDelay time.Duration
- ensureCalls atomic.Int32
+ ensureCalls atomic.Int32
+ replaceCalls atomic.Int32
- listCalls int
- deleted []string
- deleteCtxErr error
+ listCalls int
+ deleted []string
+ deletedTemplates []string
+ deleteCtxErr error
+ replaced *sandbox.RemoteTemplate
}
func (s *stubProviderClient) ListTemplates(context.Context) ([]sandbox.RemoteTemplate, error) {
@@ -317,6 +330,20 @@ func (s *stubProviderClient) EnsureStandardTemplate(context.Context) (*sandbox.R
return &sandbox.RemoteTemplate{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true}, nil
}
+func (s *stubProviderClient) ReplaceStandardTemplate(ctx context.Context) (*sandbox.RemoteTemplate, error) {
+ s.replaceCalls.Add(1)
+ for _, item := range s.templates {
+ if item.Standard && item.ID != "" {
+ s.deletedTemplates = append(s.deletedTemplates, item.ID)
+ }
+ }
+ if s.replaced != nil {
+ copyTpl := *s.replaced
+ return &copyTpl, nil
+ }
+ return s.EnsureStandardTemplate(ctx)
+}
+
func (s *stubProviderClient) List(
ctx context.Context, _ sandbox.RemoteListFilter,
) ([]sandbox.RemoteSandboxSummary, error) {
@@ -459,6 +486,178 @@ func TestQueryTemplatesReportsFailedStandardTemplateWithoutEnsure(t *testing.T)
require.Equal(t, "no space left", result.Templates[0].Error)
}
+// EnsureStandard that cannot recover must still return the catalog: a 500
+// would hide the provider's lastError and stop the wizard from polling.
+func TestQueryTemplatesSurfacesFailedEnsureWithoutProvisioning(t *testing.T) {
+ client := &stubProviderClient{
+ templates: []sandbox.RemoteTemplate{
+ {ID: "tpl-broken", Name: "weknora", Status: "failed", Standard: true, Error: "TOOMANYREQUESTS"},
+ },
+ ensured: &sandbox.RemoteTemplate{
+ ID: "tpl-broken", Name: "weknora", Status: "failed", Standard: true, Error: "TOOMANYREQUESTS",
+ },
+ }
+ 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.Equal(t, int32(1), client.ensureCalls.Load())
+ require.False(t, result.Provisioned)
+ require.Empty(t, result.StandardTemplateID)
+ require.Equal(t, "TOOMANYREQUESTS", result.Templates[0].Error)
+}
+
+func TestQueryTemplatesReplaceStandardDeletesExisting(t *testing.T) {
+ client := &stubProviderClient{
+ templates: []sandbox.RemoteTemplate{
+ {ID: "tpl-old", Name: "weknora", Status: "ready", Standard: true},
+ {ID: "tpl-custom", Name: "custom", Status: "ready"},
+ },
+ replaced: &sandbox.RemoteTemplate{
+ ID: "tpl-new", 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),
+ ReplaceStandard: true,
+ })
+
+ require.NoError(t, err)
+ require.Equal(t, int32(1), client.replaceCalls.Load())
+ require.Equal(t, int32(0), client.ensureCalls.Load())
+ require.Equal(t, []string{"tpl-old"}, client.deletedTemplates)
+ require.True(t, result.Provisioned)
+ require.Equal(t, "tpl-new", result.StandardTemplateID)
+ require.Len(t, result.Templates, 2)
+ require.Equal(t, "tpl-new", result.Templates[0].ID)
+ require.Equal(t, "tpl-custom", result.Templates[1].ID)
+}
+
+func TestQueryTemplatesReplaceStandardRefusesWhenSkillSnapshotExists(t *testing.T) {
+ stored := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
+ stored.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a", TenantID: 7, SandboxType: "e2b", Config: stored,
+ }}
+ client := &stubProviderClient{
+ templates: []sandbox.RemoteTemplate{
+ {ID: "t1", Name: "weknora", Status: "ready", Standard: true},
+ },
+ replaced: &sandbox.RemoteTemplate{
+ ID: "tpl-new", Name: "weknora", Status: "building", Standard: true,
+ },
+ }
+ svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, sandbox.DefaultConfig(), nil, nil)
+ svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
+ return client, nil
+ }
+
+ _, err := svc.QueryTemplates(context.Background(), 7, SandboxTemplateQueryInput{
+ ConfigID: "cfg-a",
+ Config: e2bCfg(types.RedactedSecretPlaceholder, "https://api.e2b.app", "e2b.app", "t1", 300),
+ ReplaceStandard: true,
+ })
+ require.ErrorIs(t, err, ErrSkillSnapshotBlocksTemplateChange)
+ require.Equal(t, int32(0), client.replaceCalls.Load())
+}
+
+func TestUpdateRefusesTemplateChangeWhenSkillSnapshotExists(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ stored := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
+ stored.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: stored,
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{}, stubAgentRepo{})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t2", 300),
+ })
+ require.ErrorIs(t, err, ErrSkillSnapshotBlocksTemplateChange)
+ require.Nil(t, repo.updated)
+}
+
+func TestUpdateRefusesIdentityChangeWhenSkillSnapshotExists(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ stored := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
+ stored.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: stored,
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{}, stubAgentRepo{})
+
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: e2bCfg("key-b", "https://api.e2b.app", "e2b.app", "t1", 300),
+ })
+ require.ErrorIs(t, err, ErrSkillSnapshotBlocksTemplateChange)
+ require.Nil(t, repo.updated)
+}
+
+func TestUpdateRefusesDNSChangeWhenSkillSnapshotExists(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ stored := cubeCfg("key-a", "https://203.0.113.10", "https://203.0.113.11", "cube.app")
+ stored.Cube.TemplateID = "tpl-1"
+ stored.Cube.DNSServers = []string{"8.8.8.8"}
+ stored.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "cube",
+ Config: stored,
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{}, stubAgentRepo{})
+
+ next := cubeCfg("key-a", "https://203.0.113.10", "https://203.0.113.11", "cube.app")
+ next.Cube.TemplateID = "tpl-1"
+ next.Cube.DNSServers = []string{"1.1.1.1"}
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: next,
+ })
+ require.ErrorIs(t, err, ErrSkillSnapshotBlocksTemplateChange)
+ require.Nil(t, repo.updated)
+}
+
+func TestUpdateRefusesPrivateEndpointChangeWhenSkillSnapshotExists(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ stored := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
+ stored.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
+ repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
+ ID: "cfg-a",
+ TenantID: 7,
+ Name: "prod",
+ SandboxType: "e2b",
+ Config: stored,
+ }}
+ svc := newTestConfigService(t, repo, &stubProviderClient{}, stubAgentRepo{})
+
+ next := e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300)
+ next.AllowPrivateEndpoints = true
+ _, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
+ Name: "prod",
+ Config: next,
+ })
+ require.ErrorIs(t, err, ErrSkillSnapshotBlocksTemplateChange)
+ require.Nil(t, repo.updated)
+}
+
func TestQueryTemplatesDeduplicatesSameProviderTemplateID(t *testing.T) {
client := &stubProviderClient{templates: []sandbox.RemoteTemplate{
{ID: "tpl-weknora", Name: "weknora", Status: "building", Standard: true},
@@ -936,6 +1135,23 @@ func TestSanitizeSandboxConfigCountsRedactedSecretAsPresent(t *testing.T) {
require.Equal(t, "t2", out.E2B.TemplateID)
}
+func TestSanitizeSandboxConfigRejectsInvalidCubeDNS(t *testing.T) {
+ t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
+ incoming := &types.TenantSandboxConfig{
+ SandboxType: "cube",
+ Cube: &types.CubeSandboxConfig{
+ APIURL: "https://203.0.113.20", DNSServers: []string{"dns.google"},
+ },
+ }
+
+ _, err := SanitizeSandboxConfig(incoming, nil)
+
+ var appErr *apperrors.AppError
+ require.ErrorAs(t, err, &appErr)
+ require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
+ require.Contains(t, err.Error(), "dns.google")
+}
+
func TestSanitizeSandboxConfigRejectsUnsafeURL(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
incoming := &types.TenantSandboxConfig{
diff --git a/internal/handler/sandbox_config.go b/internal/handler/sandbox_config.go
index a6fc8ba96..aac83956b 100644
--- a/internal/handler/sandbox_config.go
+++ b/internal/handler/sandbox_config.go
@@ -28,14 +28,16 @@ type sandboxConfigService interface {
}
type sandboxTemplateQueryRequest struct {
- Config *types.TenantSandboxConfig `json:"config"`
- ConfigID string `json:"config_id,omitempty"`
- EnsureStandard bool `json:"ensure_standard"`
+ Config *types.TenantSandboxConfig `json:"config"`
+ ConfigID string `json:"config_id,omitempty"`
+ EnsureStandard bool `json:"ensure_standard"`
+ ReplaceStandard bool `json:"replace_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.
+// connection. ensure_standard starts a build only when the cluster has no
+// usable WeKnora template; replace_standard deletes that template first so
+// a new spec (DNS, image) can take effect.
func (h *SandboxConfigHandler) QueryTemplates(c *gin.Context) {
var req sandboxTemplateQueryRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -44,11 +46,15 @@ func (h *SandboxConfigHandler) QueryTemplates(c *gin.Context) {
}
result, err := h.service.QueryTemplates(c.Request.Context(), sandboxConfigTenantID(c),
service.SandboxTemplateQueryInput{
- Config: req.Config,
- ConfigID: req.ConfigID,
- EnsureStandard: req.EnsureStandard,
+ Config: req.Config,
+ ConfigID: req.ConfigID,
+ EnsureStandard: req.EnsureStandard,
+ ReplaceStandard: req.ReplaceStandard,
})
if err != nil {
+ if respondSandboxConfigRefusal(c, err) {
+ return
+ }
respondSandboxConfigServiceError(c, err)
return
}
@@ -136,6 +142,16 @@ func respondSkillSnapshotReleaseFailed(c *gin.Context, remaining []string) {
})
}
+func respondSkillSnapshotBlocksTemplate(c *gin.Context) {
+ c.JSON(http.StatusConflict, gin.H{
+ "success": false,
+ "error": gin.H{
+ "code": "skill_snapshot_blocks_template",
+ "message": "该配置已安装 Skill,不能更换连接、DNS 或重建运行模板。请新建一份沙箱后再装 Skill。",
+ },
+ })
+}
+
func respondSandboxConfigCordoned(c *gin.Context) {
c.JSON(http.StatusLocked, gin.H{
"success": false,
@@ -165,6 +181,10 @@ func respondSandboxConfigRefusal(c *gin.Context, err error) bool {
respondSkillSnapshotReleaseFailed(c, nil)
return true
}
+ if stderrors.Is(err, service.ErrSkillSnapshotBlocksTemplateChange) {
+ respondSkillSnapshotBlocksTemplate(c)
+ return true
+ }
if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
respondSandboxConfigCordoned(c)
return true
diff --git a/internal/handler/sandbox_config_test.go b/internal/handler/sandbox_config_test.go
index 4a6755f34..1e88b207d 100644
--- a/internal/handler/sandbox_config_test.go
+++ b/internal/handler/sandbox_config_test.go
@@ -136,6 +136,32 @@ func TestSkillSnapshotReleaseFailedMapsTo409WithRemaining(t *testing.T) {
require.Equal(t, []string{"snap-2"}, payload.Error.Data.SnapshotIDs)
}
+func TestSkillSnapshotBlocksTemplateMapsTo409(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.POST("/sandbox-configs/templates/query", func(c *gin.Context) {
+ if !respondSandboxConfigRefusal(c, service.ErrSkillSnapshotBlocksTemplateChange) {
+ t.Fatal("expected skill snapshot template lock to map as a refusal")
+ }
+ })
+
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/templates/query", nil)
+ router.ServeHTTP(w, req)
+
+ require.Equal(t, http.StatusConflict, w.Code)
+
+ var payload struct {
+ Error struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ } `json:"error"`
+ }
+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
+ require.Equal(t, "skill_snapshot_blocks_template", payload.Error.Code)
+ require.Contains(t, payload.Error.Message, "不能更换连接")
+}
+
func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {
gin.SetMode(gin.TestMode)
diff --git a/internal/sandbox/cube_dns.go b/internal/sandbox/cube_dns.go
new file mode 100644
index 000000000..43ad1bc6f
--- /dev/null
+++ b/internal/sandbox/cube_dns.go
@@ -0,0 +1,38 @@
+package sandbox
+
+import (
+ "fmt"
+ "net"
+ "strings"
+)
+
+// NormalizeCubeDNSServers trims, drops empties, rejects non-IP values, and
+// de-duplicates. Cube's template `dns` field is a list of nameserver IPs —
+// hostnames are not accepted. An empty result means "leave Cubelet's default".
+func NormalizeCubeDNSServers(raw []string) ([]string, error) {
+ if len(raw) == 0 {
+ return nil, nil
+ }
+ out := make([]string, 0, len(raw))
+ seen := make(map[string]struct{}, len(raw))
+ for _, item := range raw {
+ ip := strings.TrimSpace(item)
+ if ip == "" {
+ continue
+ }
+ parsed := net.ParseIP(ip)
+ if parsed == nil {
+ return nil, fmt.Errorf("sandbox: invalid cube DNS server %q (need an IP address)", item)
+ }
+ canonical := parsed.String()
+ if _, dup := seen[canonical]; dup {
+ continue
+ }
+ seen[canonical] = struct{}{}
+ out = append(out, canonical)
+ }
+ if len(out) == 0 {
+ return nil, nil
+ }
+ return out, nil
+}
diff --git a/internal/sandbox/cube_dns_test.go b/internal/sandbox/cube_dns_test.go
new file mode 100644
index 000000000..36293f601
--- /dev/null
+++ b/internal/sandbox/cube_dns_test.go
@@ -0,0 +1,27 @@
+package sandbox
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestNormalizeCubeDNSServers(t *testing.T) {
+ got, err := NormalizeCubeDNSServers(nil)
+ require.NoError(t, err)
+ require.Nil(t, got)
+
+ got, err = NormalizeCubeDNSServers([]string{"", " "})
+ require.NoError(t, err)
+ require.Nil(t, got)
+
+ got, err = NormalizeCubeDNSServers([]string{
+ " 8.8.8.8 ", "8.8.8.8", "1.1.1.1",
+ })
+ require.NoError(t, err)
+ require.Equal(t, []string{"8.8.8.8", "1.1.1.1"}, got)
+
+ _, err = NormalizeCubeDNSServers([]string{"dns.google"})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "dns.google")
+}
diff --git a/internal/sandbox/cube_egress_integration_test.go b/internal/sandbox/cube_egress_integration_test.go
new file mode 100644
index 000000000..01c54f21f
--- /dev/null
+++ b/internal/sandbox/cube_egress_integration_test.go
@@ -0,0 +1,60 @@
+//go:build integration
+
+package sandbox
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestIntegrationCubeClient_PublicEgress is the same check the settings
+// wizard runs as "出网可用". It needs cube-egress listening on the cube-dev
+// gateway and FORWARD/MASQUERADE for sandbox DNS.
+func TestIntegrationCubeClient_PublicEgress(t *testing.T) {
+ cfg := integrationConfig(t)
+ client, err := NewCubeRemoteClient(cfg)
+ if err != nil {
+ t.Fatalf("NewCubeRemoteClient: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ handle, err := client.Create(ctx, RemoteCreateRequest{
+ TemplateID: cfg.CubeTemplate,
+ Timeout: RemoteTimeoutPolicy{
+ Mode: RemoteTimeoutExplicit,
+ Value: integrationSandboxTTL,
+ Action: RemoteOnTimeoutKill,
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := client.Delete(cleanupCtx, handle.ID()); err != nil {
+ t.Logf("cleanup delete sandbox %s: %v", handle.ID(), err)
+ }
+ })
+
+ result, err := client.Exec(ctx, handle, RemoteExecRequest{
+ Command: `if curl -fsS -o /dev/null -m 8 -I 'https://www.baidu.com'; then echo 'cn:baidu'; exit 0; fi; echo "all probes failed" >&2; exit 1`,
+ Shell: true,
+ User: DefaultSandboxExecUser,
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("egress Exec: %v", err)
+ }
+ if result.ExitCode != 0 {
+ t.Fatalf("sandbox egress failed exit=%d stdout=%q stderr=%q",
+ result.ExitCode, result.Stdout, result.Stderr)
+ }
+ if !strings.Contains(result.Stdout, "cn:baidu") {
+ t.Fatalf("egress stdout missing marker: %q", result.Stdout)
+ }
+}
diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go
index 671ebdc6b..a17d253b0 100644
--- a/internal/sandbox/cube_remote_client.go
+++ b/internal/sandbox/cube_remote_client.go
@@ -172,14 +172,17 @@ func (c *CubeRemoteClient) ListTemplates(ctx context.Context) ([]RemoteTemplate,
}
}
result = append(result, RemoteTemplate{
- ID: item.TemplateID,
- Name: name,
- Status: item.Status,
- Version: item.Version,
- Image: item.ImageInfo,
- CreatedAt: item.CreatedAt,
- Standard: standard,
- Error: strings.TrimSpace(item.LastError),
+ ID: item.TemplateID,
+ Name: name,
+ Status: normalizeCubeTemplateStatus(item.Status),
+ Version: item.Version,
+ Image: item.ImageInfo,
+ CreatedAt: item.CreatedAt,
+ Standard: standard,
+ Error: strings.TrimSpace(item.LastError),
+ InstanceType: item.InstanceType,
+ NetworkType: item.NetworkType,
+ AllowInternetAccess: item.AllowInternetAccess,
})
}
return result, nil
@@ -217,8 +220,9 @@ func cubeTemplateIsSnapshot(templateID string, snapshotIDs map[string]struct{})
// EnsureStandardTemplate makes the cluster hold exactly one WeKnora template.
// A healthy or still-building one is returned as is; a failed one is rebuilt in
-// place, because building a second template would leave the failed one behind
-// and repeat on every refresh.
+// place. If CubeMaster refuses the redo, the failed card is returned as-is;
+// ReplaceStandardTemplate (the settings-page "delete and rebuild" action) is
+// what actually replaces it.
func (c *CubeRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
items, err := c.ListTemplates(ctx)
if err != nil {
@@ -239,21 +243,30 @@ func (c *CubeRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteT
if failed != nil {
return c.rebuildStandardTemplate(ctx, *failed)
}
- job, err := c.client.BuildTemplate(ctx, cubesandbox.BuildTemplateOptions{
- Image: DefaultCubeTemplateImage,
- Extra: cubeStandardTemplateSpec(),
- })
+ return c.buildStandardTemplate(ctx)
+}
+
+// ReplaceStandardTemplate deletes every WeKnora template on the cluster and
+// builds a fresh one from the current spec. Cube bakes DNS and
+// allowInternetAccess into the template at create time, so a READY template
+// cannot pick up a settings change any other way.
+func (c *CubeRemoteClient) ReplaceStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
+ items, err := c.ListTemplates(ctx)
if err != nil {
- return nil, normalizeCubeError("EnsureStandardTemplate", err)
+ return nil, err
}
- return &RemoteTemplate{
- ID: job.TemplateID,
- Name: StandardTemplateName,
- Status: job.Status,
- Image: DefaultCubeTemplateImage,
- Standard: true,
- Error: strings.TrimSpace(job.ErrorMessage),
- }, nil
+ for _, item := range items {
+ if !item.Standard || strings.TrimSpace(item.ID) == "" {
+ continue
+ }
+ logger.Infof(ctx, "cube replacing standard template %s", item.ID)
+ if err := c.client.DeleteTemplate(ctx, item.ID); err != nil {
+ if normalized := normalizeCubeError("DeleteTemplate", err); !IsRemoteNotFound(normalized) {
+ return nil, normalized
+ }
+ }
+ }
+ return c.buildStandardTemplate(ctx)
}
// rebuildStandardTemplate restarts the build of a template that already exists,
@@ -264,12 +277,18 @@ func (c *CubeRemoteClient) rebuildStandardTemplate(
) (*RemoteTemplate, error) {
logger.Infof(ctx, "cube standard template %s failed (%s), rebuilding in place",
current.ID, current.Status)
- job, err := c.client.RebuildTemplate(ctx, current.ID, cubeStandardTemplateSpec())
+ job, err := c.client.RebuildTemplate(ctx, current.ID, c.standardTemplateSpec())
if err != nil {
- return nil, normalizeCubeError("EnsureStandardTemplate", err)
+ // The failed template is still in the catalog; returning it lets the
+ // settings page show lastError instead of 500ing the whole query.
+ logger.Warnf(ctx, "cube rebuild of standard template %s failed: %v", current.ID, err)
+ return &current, nil
}
rebuilt := current
- rebuilt.Status = job.Status
+ rebuilt.Status = normalizeCubeTemplateStatus(job.Status)
+ if rebuilt.Status == "" {
+ rebuilt.Status = "building"
+ }
rebuilt.Error = strings.TrimSpace(job.ErrorMessage)
if strings.TrimSpace(job.TemplateID) != "" {
rebuilt.ID = job.TemplateID
@@ -277,12 +296,68 @@ func (c *CubeRemoteClient) rebuildStandardTemplate(
return &rebuilt, nil
}
+func (c *CubeRemoteClient) buildStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
+ job, err := c.client.BuildTemplate(ctx, cubesandbox.BuildTemplateOptions{
+ Image: DefaultCubeTemplateImage,
+ Extra: c.standardTemplateSpec(),
+ })
+ if err != nil {
+ // Creating is best-effort from the settings query: a 500 here would
+ // hide the catalog, including any other templates the admin could pick.
+ logger.Warnf(ctx, "cube standard template create failed: %v", err)
+ return &RemoteTemplate{
+ Name: StandardTemplateName,
+ Status: "failed",
+ Image: DefaultCubeTemplateImage,
+ Standard: true,
+ Error: err.Error(),
+ }, nil
+ }
+ status := normalizeCubeTemplateStatus(job.Status)
+ if status == "" {
+ status = "building"
+ }
+ return &RemoteTemplate{
+ ID: job.TemplateID,
+ Name: StandardTemplateName,
+ Status: status,
+ Image: DefaultCubeTemplateImage,
+ Standard: true,
+ Error: strings.TrimSpace(job.ErrorMessage),
+ }, nil
+}
+
+// normalizeCubeTemplateStatus projects Cube's catalog verbs onto the same
+// ready/building/failed set the settings UI and the other backends already use.
+// Cube reports an in-progress create-from-image as RUNNING, which would
+// otherwise render as "unknown" and stop the wizard from polling.
+func normalizeCubeTemplateStatus(status string) string {
+ switch strings.ToLower(strings.TrimSpace(status)) {
+ case "ready", "available", "complete", "completed", "success", "succeeded":
+ return "ready"
+ case "running", "building", "waiting", "pending", "queued", "processing":
+ return "building"
+ case "failed", "failure", "error", "cancelled", "canceled":
+ return "failed"
+ default:
+ return strings.ToLower(strings.TrimSpace(status))
+ }
+}
+
+func (c *CubeRemoteClient) standardTemplateSpec() map[string]any {
+ var dns []string
+ if c != nil && c.config != nil {
+ dns, _ = NormalizeCubeDNSServers(c.config.CubeDNSServers)
+ }
+ return cubeStandardTemplateSpec(dns)
+}
+
// cubeStandardTemplateSpec is the single definition of how the WeKnora template
// is built. Both the first build and every rebuild send it verbatim — the
// rebuild endpoint takes a raw payload rather than BuildTemplateOptions, and
// two hand-kept copies of the spec would eventually disagree.
-func cubeStandardTemplateSpec() map[string]any {
- return map[string]any{
+func cubeStandardTemplateSpec(dns []string) map[string]any {
+ spec := map[string]any{
"image": DefaultCubeTemplateImage,
"name": StandardTemplateName,
"writableLayerSize": "1G",
@@ -291,7 +366,14 @@ func cubeStandardTemplateSpec() map[string]any {
// this image must ship envd visible at the call site.
"probePort": uint16(CubeEnvdPort),
"probePath": CubeEnvdHealthPath,
+ // Without this the template's "公网访问" stays empty and sandboxes
+ // boot with no outbound route, even if Create sets the same flag.
+ "allowInternetAccess": true,
+ }
+ if len(dns) > 0 {
+ spec["dns"] = append([]string(nil), dns...)
}
+ return spec
}
func (c *CubeRemoteClient) Create(
@@ -966,7 +1048,7 @@ func normalizeCubeError(op string, err error) error {
case errors.Is(err, cubesandbox.ErrAuthentication):
kind = RemoteErrorKindAuthentication
case errors.Is(err, cubesandbox.ErrTemplateNotFound):
- if op == "DeleteSnapshot" {
+ if op == "DeleteSnapshot" || op == "DeleteTemplate" {
kind = RemoteErrorKindNotFound
} else {
kind = RemoteErrorKindInvalidRequest
diff --git a/internal/sandbox/cube_template_catalog_test.go b/internal/sandbox/cube_template_catalog_test.go
index e4853dfe9..b8c2626de 100644
--- a/internal/sandbox/cube_template_catalog_test.go
+++ b/internal/sandbox/cube_template_catalog_test.go
@@ -63,6 +63,37 @@ func TestCubeRemoteClientListTemplatesRecognisesStandardByImage(t *testing.T) {
require.Equal(t, "tpl-other", templates[1].Name)
}
+func TestCubeRemoteClientListTemplatesMapsCatalogMetadata(t *testing.T) {
+ allowInternet := true
+ client := newCubeTemplateClient(t, cubeCatalogHandler(
+ []map[string]any{{
+ "templateID": "tpl-full",
+ "name": "custom",
+ "status": "READY",
+ "version": "v2",
+ "imageInfo": "python:3.11",
+ "createdAt": "2026-08-01T12:00:00Z",
+ "instanceType": "small",
+ "networkType": "tap",
+ "allowInternetAccess": allowInternet,
+ }},
+ nil,
+ ))
+
+ templates, err := client.ListTemplates(context.Background())
+ require.NoError(t, err)
+ require.Len(t, templates, 1)
+ require.Equal(t, "tpl-full", templates[0].ID)
+ require.Equal(t, "custom", templates[0].Name)
+ require.Equal(t, "v2", templates[0].Version)
+ require.Equal(t, "python:3.11", templates[0].Image)
+ require.Equal(t, "2026-08-01T12:00:00Z", templates[0].CreatedAt)
+ require.Equal(t, "small", templates[0].InstanceType)
+ require.Equal(t, "tap", templates[0].NetworkType)
+ require.NotNil(t, templates[0].AllowInternetAccess)
+ require.True(t, *templates[0].AllowInternetAccess)
+}
+
func TestCubeRemoteClientListTemplatesSurfacesLastError(t *testing.T) {
client := newCubeTemplateClient(t, cubeCatalogHandler(
[]map[string]any{{
@@ -224,6 +255,7 @@ func TestCubeRemoteClientEnsureStandardTemplateRebuildsFailedTemplate(t *testing
require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
require.Equal(t, DefaultCubeTemplateImage, payload["image"])
require.Equal(t, StandardTemplateName, payload["name"])
+ require.Equal(t, true, payload["allowInternetAccess"])
writeJSON(w, http.StatusAccepted, map[string]any{
"templateID": "tpl-failed",
"status": "PENDING",
@@ -236,11 +268,75 @@ func TestCubeRemoteClientEnsureStandardTemplateRebuildsFailedTemplate(t *testing
template, err := client.EnsureStandardTemplate(context.Background())
require.NoError(t, err)
require.Equal(t, "tpl-failed", template.ID)
- require.Equal(t, "PENDING", template.Status)
+ require.Equal(t, "building", template.Status)
require.Equal(t, int32(1), rebuilt.Load())
require.Equal(t, int32(0), created.Load(), "a rebuild must not add a template")
}
+func TestCubeRemoteClientListTemplatesNormalizesRunningStatus(t *testing.T) {
+ client := newCubeTemplateClient(t, cubeCatalogHandler(
+ []map[string]any{{
+ "templateID": "tpl-pulling",
+ "status": "RUNNING",
+ "imageInfo": DefaultCubeTemplateImage,
+ }},
+ nil,
+ ))
+
+ templates, err := client.ListTemplates(context.Background())
+ require.NoError(t, err)
+ require.Len(t, templates, 1)
+ require.Equal(t, "building", templates[0].Status)
+ require.True(t, templates[0].Standard)
+ require.False(t, IsTemplateBuildFailed(templates[0].Status))
+}
+
+// CubeMaster may refuse redo (for example when the source image never
+// landed). The failed card stays in the catalog so the operator can delete
+// it by hand; Ensure must not 500 or spawn a replacement.
+func TestCubeRemoteClientEnsureStandardTemplateKeepsFailedWhenRedoBlocked(t *testing.T) {
+ var created atomic.Int32
+ var deleted atomic.Int32
+ client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/templates" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, []map[string]any{{
+ "templateID": "tpl-failed",
+ "status": "FAILED",
+ "imageInfo": DefaultCubeTemplateImage,
+ "lastError": "TOOMANYREQUESTS: You have reached your unauthenticated pull rate limit",
+ }})
+ case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, []map[string]any{})
+ case r.URL.Path == "/templates/tpl-failed" && r.Method == http.MethodPost:
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": 400,
+ "message": "CubeMaster returned error code 130400: " +
+ "template redo is not allowed before source image has been pulled successfully",
+ })
+ case r.URL.Path == "/templates/tpl-failed" && r.Method == http.MethodDelete:
+ deleted.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+ case r.URL.Path == "/templates" && r.Method == http.MethodPost:
+ created.Add(1)
+ writeJSON(w, http.StatusAccepted, map[string]any{
+ "templateID": "tpl-fresh",
+ "status": "PENDING",
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ })
+
+ template, err := client.EnsureStandardTemplate(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, "tpl-failed", template.ID)
+ require.Equal(t, "failed", template.Status)
+ require.Contains(t, template.Error, "TOOMANYREQUESTS")
+ require.Equal(t, int32(0), deleted.Load())
+ require.Equal(t, int32(0), created.Load())
+}
+
func TestCubeRemoteClientEnsureStandardTemplateBuildsWhenAbsent(t *testing.T) {
var payload map[string]any
client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
@@ -267,6 +363,69 @@ func TestCubeRemoteClientEnsureStandardTemplateBuildsWhenAbsent(t *testing.T) {
require.Equal(t, "1G", payload["writableLayerSize"])
require.EqualValues(t, CubeEnvdPort, payload["probePort"])
require.Equal(t, CubeEnvdHealthPath, payload["probePath"])
+ require.Equal(t, true, payload["allowInternetAccess"])
+ _, hasDNS := payload["dns"]
+ require.False(t, hasDNS, "empty DNS config must omit the field so Cubelet keeps its default")
+}
+
+func TestCubeRemoteClientEnsureStandardTemplateIncludesConfiguredDNS(t *testing.T) {
+ var payload map[string]any
+ client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ writeJSON(w, http.StatusOK, []map[string]any{})
+ case http.MethodPost:
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
+ writeJSON(w, http.StatusAccepted, map[string]any{
+ "templateID": "tpl-dns",
+ "status": "PENDING",
+ })
+ }
+ })
+ client.config.CubeDNSServers = []string{"8.8.8.8", "1.1.1.1"}
+
+ template, err := client.EnsureStandardTemplate(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, "tpl-dns", template.ID)
+ require.Equal(t, []any{"8.8.8.8", "1.1.1.1"}, payload["dns"])
+}
+
+func TestCubeRemoteClientReplaceStandardTemplateDeletesThenBuilds(t *testing.T) {
+ var deleted atomic.Int32
+ var payload map[string]any
+ client := newCubeTemplateClient(t, func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/templates" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, []map[string]any{{
+ "templateID": "tpl-old",
+ "status": "READY",
+ "imageInfo": DefaultDockerImage,
+ "aliases": []string{StandardTemplateName},
+ }})
+ case r.URL.Path == "/templates/tpl-old" && r.Method == http.MethodDelete:
+ deleted.Add(1)
+ w.WriteHeader(http.StatusNoContent)
+ case r.URL.Path == "/templates" && r.Method == http.MethodPost:
+ require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
+ writeJSON(w, http.StatusAccepted, map[string]any{
+ "templateID": "tpl-new",
+ "status": "PENDING",
+ })
+ case r.URL.Path == "/snapshots" && r.Method == http.MethodGet:
+ writeJSON(w, http.StatusOK, []map[string]any{})
+ default:
+ http.NotFound(w, r)
+ }
+ })
+ client.config.CubeDNSServers = []string{"192.0.2.53"}
+
+ template, err := client.ReplaceStandardTemplate(context.Background())
+ require.NoError(t, err)
+ require.Equal(t, "tpl-new", template.ID)
+ require.Equal(t, "building", template.Status)
+ require.Equal(t, int32(1), deleted.Load())
+ require.Equal(t, []any{"192.0.2.53"}, payload["dns"])
+ require.Equal(t, true, payload["allowInternetAccess"])
}
// The plain and Cube images share a repository, so a template built from either
diff --git a/internal/sandbox/docker_template_catalog.go b/internal/sandbox/docker_template_catalog.go
index 91fcc30bf..6eeb6d0d5 100644
--- a/internal/sandbox/docker_template_catalog.go
+++ b/internal/sandbox/docker_template_catalog.go
@@ -159,6 +159,13 @@ func (c *DockerRemoteClient) EnsureStandardTemplate(ctx context.Context) (*Remot
return &pending, nil
}
+// ReplaceStandardTemplate is a pull of the configured image. Docker has no
+// cluster-side template object to delete; a missing image is fetched, a
+// present one is left as-is.
+func (c *DockerRemoteClient) ReplaceStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
+ return c.EnsureStandardTemplate(ctx)
+}
+
func (c *DockerRemoteClient) pullInBackground(ctx context.Context, key, image string) {
pullCtx, cancel := context.WithTimeout(ctx, dockerImagePullBudget)
defer cancel()
diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go
index 0a804297a..8d97a61a3 100644
--- a/internal/sandbox/e2b_remote_client.go
+++ b/internal/sandbox/e2b_remote_client.go
@@ -331,6 +331,33 @@ func (c *E2BRemoteClient) EnsureStandardTemplate(ctx context.Context) (*RemoteTe
return &items[i], nil
}
}
+ return c.buildStandardTemplate(ctx)
+}
+
+// ReplaceStandardTemplate deletes the WeKnora template and starts a new build
+// so a later image (or an untagged leftover) can actually replace what is
+// already READY.
+func (c *E2BRemoteClient) ReplaceStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
+ items, err := c.ListTemplates(ctx)
+ if err != nil {
+ return nil, err
+ }
+ for _, item := range items {
+ if !item.Standard || strings.TrimSpace(item.ID) == "" {
+ continue
+ }
+ logger.Infof(ctx, "e2b replacing standard template %s", item.ID)
+ if err := c.client.DeleteTemplate(ctx, item.ID); err != nil {
+ var notFound *e2b.TemplateNotFoundError
+ if !errors.As(err, &notFound) {
+ return nil, normalizeE2BError("DeleteTemplate", err)
+ }
+ }
+ }
+ return c.buildStandardTemplate(ctx)
+}
+
+func (c *E2BRemoteClient) buildStandardTemplate(ctx context.Context) (*RemoteTemplate, error) {
builder := e2b.NewTemplate().FromImage(DefaultDockerImage)
build, err := builder.BuildInBackground(ctx, c.client, e2b.BuildConfig{
Name: StandardTemplateName,
diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go
index 70bdeeb41..4abdf6157 100644
--- a/internal/sandbox/sandbox.go
+++ b/internal/sandbox/sandbox.go
@@ -312,6 +312,11 @@ type Config struct {
// CubeHTTPTimeout bounds each HTTP call to CubeAPI. Zero uses the default.
CubeHTTPTimeout time.Duration
+ // CubeDNSServers are nameserver IPs included when WeKnora builds the
+ // standard Cube template. Empty omits the field so Cubelet uses its
+ // cluster default.
+ CubeDNSServers []string
+
// E2BAPIKey is the E2B API key sent via X-API-Key. Only used when
// Type == SandboxTypeE2B.
E2BAPIKey string
diff --git a/internal/sandbox/template_catalog.go b/internal/sandbox/template_catalog.go
index 7e7c00447..f059570e4 100644
--- a/internal/sandbox/template_catalog.go
+++ b/internal/sandbox/template_catalog.go
@@ -32,6 +32,12 @@ type RemoteTemplate struct {
// it a failed template is a red badge with no way to tell a registry
// credential problem from an out-of-disk node.
Error string `json:"error,omitempty"`
+
+ // Cube reports these on GET /templates; other backends leave them empty
+ // and the settings list simply omits the corresponding rows.
+ InstanceType string `json:"instance_type,omitempty"`
+ NetworkType string `json:"network_type,omitempty"`
+ AllowInternetAccess *bool `json:"allow_internet_access,omitempty"`
}
// RemoteTemplateCatalog is an optional provider capability used by the
@@ -40,6 +46,10 @@ type RemoteTemplate struct {
type RemoteTemplateCatalog interface {
ListTemplates(ctx context.Context) ([]RemoteTemplate, error)
EnsureStandardTemplate(ctx context.Context) (*RemoteTemplate, error)
+ // ReplaceStandardTemplate deletes the cluster's WeKnora template and
+ // builds a new one from the current spec. Changing DNS or the image
+ // otherwise has no effect on an already-READY template.
+ ReplaceStandardTemplate(ctx context.Context) (*RemoteTemplate, error)
}
func isStandardTemplate(name string) bool {
diff --git a/internal/sandbox/tenant_config.go b/internal/sandbox/tenant_config.go
index 39730ef5d..a9e99b96d 100644
--- a/internal/sandbox/tenant_config.go
+++ b/internal/sandbox/tenant_config.go
@@ -74,6 +74,11 @@ func ResolveEffectiveConfig(
overrideString(&effective.CubeTemplate, cube.TemplateID)
overrideSeconds(&effective.CubeHTTPTimeout, cube.HTTPTimeoutSec)
overrideSeconds(&effective.CubeSandboxTTL, cube.CubeSandboxTTLSeconds)
+ dns, err := NormalizeCubeDNSServers(cube.DNSServers)
+ if err != nil {
+ return nil, err
+ }
+ effective.CubeDNSServers = dns
}
if e2bCfg := tenantCfg.E2B; e2bCfg != nil {
@@ -198,6 +203,7 @@ func clearProviderFields(cfg *Config) {
cfg.CubeTemplate = ""
cfg.CubeSandboxTTL = 0
cfg.CubeHTTPTimeout = 0
+ cfg.CubeDNSServers = nil
cfg.E2BAPIURL = ""
cfg.E2BProxyURL = ""
diff --git a/internal/sandbox/tenant_config_test.go b/internal/sandbox/tenant_config_test.go
index c78282e7b..161334c82 100644
--- a/internal/sandbox/tenant_config_test.go
+++ b/internal/sandbox/tenant_config_test.go
@@ -101,6 +101,38 @@ func TestResolveEffectiveConfigRejectsIncompleteCube(t *testing.T) {
require.Contains(t, err.Error(), "template_id")
}
+func TestResolveEffectiveConfigCopiesCubeDNSServers(t *testing.T) {
+ got, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
+ SandboxType: "cube",
+ AllowPrivateEndpoints: true,
+ Cube: &types.CubeSandboxConfig{
+ APIKey: "cube-key", APIURL: "https://203.0.113.20",
+ ProxyURL: "https://203.0.113.21", SandboxDomain: "cube.example",
+ TemplateID: "cube-template",
+ DNSServers: []string{" 8.8.8.8 ", "8.8.8.8", "1.1.1.1"},
+ },
+ }, globalTestConfig())
+
+ require.NoError(t, err)
+ require.Equal(t, []string{"8.8.8.8", "1.1.1.1"}, got.CubeDNSServers)
+}
+
+func TestResolveEffectiveConfigRejectsInvalidCubeDNS(t *testing.T) {
+ _, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
+ SandboxType: "cube",
+ AllowPrivateEndpoints: true,
+ Cube: &types.CubeSandboxConfig{
+ APIKey: "cube-key", APIURL: "https://203.0.113.20",
+ ProxyURL: "https://203.0.113.21", SandboxDomain: "cube.example",
+ TemplateID: "cube-template",
+ DNSServers: []string{"dns.google"},
+ },
+ }, globalTestConfig())
+
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "dns.google")
+}
+
func TestResolveEffectiveConfigRejectsIncompleteE2B(t *testing.T) {
_, err := ResolveEffectiveConfig(&types.TenantSandboxConfig{
SandboxType: "e2b",
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index d6d2ccb1b..8d8e4d476 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -689,6 +689,9 @@ type CubeSandboxConfig struct {
HTTPTimeoutSec int `json:"http_timeout_sec,omitempty"`
CubeSandboxTTLSeconds int `json:"cube_sandbox_ttl_seconds,omitempty"`
+
+ // DNSServers are Cube template nameserver IPs. Empty uses Cubelet's default.
+ DNSServers []string `json:"dns_servers,omitempty"`
}
// E2BSandboxConfig addresses one E2B-protocol control plane: E2B Cloud, a