feat(sandbox): expose tenant skill management over HTTP and in the console (#2789)

* feat(sandbox): enhance skill management in sandbox configurations

Updated the skill management system to allow listing, installing, and removing skills within sandbox configurations. The ListSkills function now accepts a sandboxConfigID to filter skills based on the selected configuration. Introduced a new SandboxSkillsDrawer component for managing skills through the UI, along with necessary updates to the API and localization files to support these features.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: keep skill maintenance sessions out of the console session list

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: store and expose the installer transcript locators

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: record the skill installer agent's conversation

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: stream and persist the installer transcript during a skill install

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: expose install transcript locators on the skill type

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: add the floating skill install transcript window

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat: open the install transcript from the sandbox skills drawer

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sandbox): 重构技能安装体验,支持内联时间线、编辑第4步及保留镜像指针

- 替换右下角浮窗为内联安装时间线 (SkillInstallTimeline.vue)
  - 新增 GET /api/v1/sandbox-configs/:id/skills/:skillId/transcript 接口,支持回放与追尾
  - 移除 /sessions/continue-stream 依赖,避免 404 问题
  - 事件日志以 install_prompt 开头,不再将工具调用 preamble 拼入最终答案
  - 删除 SkillInstallTranscript.vue,技能条目下可展开/折叠时间线

- 编辑向导新增第 4 步「管理技能」
  - Cube/E2B 环境:连接 → 模板 → 运行配置 → 技能(第4步)
  - Docker/Local 环境:无第4步(无快照镜像)
  - 首次创建必须按 1→2→3 顺序,第3步保存成功后自动进入第4步
  - 已有配置支持步骤条数字跳转,可直接访问任意步骤
  - 卡片菜单「管理技能」打开同一抽屉并定位至第4步
  - SandboxSkillsDrawer.vue 重命名为 SandboxSkillsPanel.vue,去除独立抽屉壳

- 修复保存运行配置时冲掉 skill_image 的问题
  - 顶部展示信息(基础模板/快照ID/版本/构建时间)读取 config.skill_image
  - 编辑器保存 payload 不再包含 skill_image,合并时保留已有 SkillImage 和 VolumeMount
  - MergeSandboxConfigForUpdate 增加对 SkillImage 和 VolumeMount 的保护
  - 已冲掉的配置需重新安装技能才能恢复镜像指针

- 「查看安装过程」在安装开始时即显示
  - 技能列表中出现「正在安装」状态即展示按钮
  - 若记录尚未写入,展示等待提示并自动重试,避免误报「没有留下记录」

* 沙盒内技能目录从 UUID 改成 SKILL.md 的 name。

* fix(sandbox): heal stuck skill rows and block planted maintenance sessions

The reaper left a mid-upgrade install spinning forever when the old snapshot was still live, and restored removals to ready after the pointer had already moved. Client session create/update can no longer hide chats behind the skill_maintenance: prefix.

* style: gofumpt the skill reaper test stubs

* style: satisfy golangci on the tenant skill admin API

* feat(sandbox): rebuild skill images at turn boundaries, not mid-exec

Hold a session turn lease through AgentQA so an install cannot tear down
the live sandbox between tool calls; the next turn's first resolve picks
up the new image. Configs can instead keep existing sandboxes and boot
the new snapshot only for new sessions.

* fix(sandbox): judge stuck skill runs from the snapshot chain

InstalledSnapshotID only records the generation that installed a skill; later
installs of other skills advance the live pointer without rewriting older rows.
Comparing those IDs made the reaper fail healthy installs and delete live
skills whose removal had stalled.

---------

Co-authored-by: hailongzhao <hailongzhao@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
nullptr-error 2026-08-25 11:28:12 +08:00 committed by GitHub
parent fc9d6f8c34
commit 18d22b014b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
88 changed files with 9597 additions and 161 deletions

View File

@ -3,6 +3,7 @@ package client
import (
"context"
"net/http"
"net/url"
)
// SkillInfo represents skill metadata
@ -15,12 +16,17 @@ type SkillInfo struct {
type SkillListResponse struct {
Success bool `json:"success"`
Data []SkillInfo `json:"data"`
SkillsAvailable bool `json:"skills_available"`
SkillsAvailable bool `json:"skills_available"`
}
// ListSkills lists all preloaded agent skills
func (c *Client) ListSkills(ctx context.Context) ([]SkillInfo, bool, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/skills", nil, nil)
// ListSkills lists the installed skills a chat turn can invoke on one sandbox
// config. An empty sandboxConfigID returns an empty list.
func (c *Client) ListSkills(ctx context.Context, sandboxConfigID string) ([]SkillInfo, bool, error) {
query := url.Values{}
if sandboxConfigID != "" {
query.Set("sandbox_config_id", sandboxConfigID)
}
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/skills", nil, query)
if err != nil {
return nil, false, err
}

View File

@ -23,13 +23,28 @@ COPY --from=node-base /usr/local/lib/node_modules /usr/local/lib/node_modules
RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
ln -s /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
# Python package manager: uv (fast pip replacement). Preinstalled because each
# skill gets its own venv at install time, and building that from a cold pip is
# what dominates an install's wall clock.
COPY --from=ghcr.io/astral-sh/uv:0.12.4 /uv /usr/local/bin/uv
RUN ln -s /usr/local/bin/uv /usr/local/bin/uvx
# Node package manager: pnpm
RUN npm install -g pnpm
# Install minimal CLI tools (bash/grep/sed/coreutils/findutils already in slim
# image). curl is not optional: the sandbox connectivity check probes egress
# with it, and skills that fetch a URL expect it to be there.
# with it, and skills that fetch a URL expect it to be there. The compression
# tools are here because skill bundles and their assets arrive archived.
RUN apt-get update && apt-get install -y --no-install-recommends \
jq \
curl \
ca-certificates \
zip \
unzip \
bzip2 \
xz-utils \
zstd \
&& rm -rf /var/lib/apt/lists/* /var/cache/apt/*
# Note: Current preloaded skills only use Python stdlib

View File

@ -65,6 +65,11 @@ export interface CustomAgentConfig {
skills_selection_mode?: 'all' | 'selected' | 'none';
selected_skills?: string[]; // 选择的Skill名称列表
// ===== 沙盒设置 =====
// 该智能体的技能脚本运行在哪个沙盒配置上;为空表示不启用沙盒执行。
// 指向逻辑配置而非某个具体版本,凭据轮换时无需重新指派每个智能体。
sandbox_config_id?: string;
// ===== 知识库设置 =====
// 知识库选择模式:all=全部知识库, selected=指定知识库, none=不使用知识库
kb_selection_mode?: 'all' | 'selected' | 'none';

View File

@ -6,7 +6,10 @@ export interface SkillInfo {
description: string;
}
// 获取预装Skills列表;skills_available 为 false 表示沙箱未启用,前端应隐藏/禁用 Skills 配置
export function listSkills() {
return get<{ data: SkillInfo[]; skills_available?: boolean }>('/api/v1/skills');
// 获取当前沙盒配置上可执行的 Skills;未传 sandboxConfigId 或
// skills_available 为 false 时,前端应隐藏/禁用 Skills 配置
export function listSkills(sandboxConfigId?: string) {
return get<{ data: SkillInfo[]; skills_available?: boolean }>('/api/v1/skills', {
params: sandboxConfigId ? { sandbox_config_id: sandboxConfigId } : {},
});
}

View File

@ -1,4 +1,4 @@
import { get, post, put, del } from '@/utils/request'
import { get, post, put, del, patch, postUpload } from '@/utils/request'
import type { CreatedTenantAPIKey, TenantAPIKey, TenantAPIKeyCapability } from '@/api/tenant'
export interface CreatePlatformAPIKeyPayload {
@ -749,12 +749,22 @@ export interface SandboxE2BConfig {
e2b_sandbox_ttl_seconds?: number
}
export interface SandboxSkillImage {
snapshot_id?: string
generation?: number
built_at?: string
base_template_id?: string
owner_fingerprint?: string
}
export interface SandboxConfig {
sandbox_type?: string
default_timeout_sec?: number
allow_private_endpoints?: boolean
env_vars?: Record<string, string>
volume_mount?: SandboxVolumeMountConfig
skill_image?: SandboxSkillImage
skill_rollout?: 'next_turn' | 'new_session'
cube?: SandboxCubeConfig
e2b?: SandboxE2BConfig
docker?: SandboxDockerConfig
@ -980,3 +990,88 @@ export function parseSandboxConflict(err: unknown): SandboxConflict | null {
}
return { code: detail.code, message: detail.message, inventory: detail.data }
}
// --- Agent skills installed onto a sandbox config's image ---
export type ConfigSkillStatus = 'installing' | 'ready' | 'failed' | 'removing' | 'removed'
export interface ConfigSkill {
id: string
name: string
version?: string
description?: string
enabled: boolean
status: ConfigSkillStatus | string
error?: string
bundle_sha256?: string
installed_snapshot_id?: string
// Locators for this skill's most recent install conversation. Absent for
// skills installed before transcripts existed, which is how the drawer
// decides whether to offer the "view install" entry point.
install_session_id?: string
install_message_id?: string
created_at: string
updated_at: string
}
export interface ConfigSkillInstallEvent {
percent: number
stage: string
log?: string
status?: string
done: boolean
}
export function listConfigSkills(configId: string): Promise<{ data: ConfigSkill[] }> {
return get(`/api/v1/sandbox-configs/${configId}/skills`) as unknown as Promise<{ data: ConfigSkill[] }>
}
export function uploadConfigSkill(
configId: string, file: File, onProgress?: (percent: number) => void,
): Promise<{ data: { skill_id: string } }> {
const form = new FormData()
form.append('file', file)
return postUpload(`/api/v1/sandbox-configs/${configId}/skills`, form, (e: any) => {
if (e.total) onProgress?.(Math.round((e.loaded * 100) / e.total))
}, { timeout: 5 * 60 * 1000 })
}
export function patchConfigSkill(
configId: string,
skillId: string,
payload: { enabled: boolean },
): Promise<{ data: ConfigSkill }> {
return patch(`/api/v1/sandbox-configs/${configId}/skills/${skillId}`, payload) as unknown as Promise<{
data: ConfigSkill
}>
}
export function deleteConfigSkill(
configId: string,
skillId: string,
): Promise<{ data: { skill_id: string } }> {
return del(`/api/v1/sandbox-configs/${configId}/skills/${skillId}`) as unknown as Promise<{
data: { skill_id: string }
}>
}
export function getConfigSkill(
configId: string,
skillId: string,
): Promise<{ data: ConfigSkill }> {
return get(`/api/v1/sandbox-configs/${configId}/skills/${skillId}`) as unknown as Promise<{
data: ConfigSkill
}>
}
export function configSkillInstallEventsUrl(configId: string, skillId: string): string {
return `/api/v1/sandbox-configs/${configId}/skills/${skillId}/install-events`
}
// The installer agent's own transcript: its prompt, thinking, commands and
// their output, replayed from the start and then followed live. Answers 404
// once the event log has expired, which is the signal to read the durable
// message history instead.
export function configSkillTranscriptUrl(configId: string, skillId: string): string {
return `/api/v1/sandbox-configs/${configId}/skills/${skillId}/transcript`
}

View File

@ -1328,7 +1328,7 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
const skillsMode = agentSkillsSelectionMode.value;
if (skillsMode !== 'none') {
await editorResources.ensureSkills();
await editorResources.ensureSkills(currentAgentConfig.value?.sandbox_config_id);
skillItems = editorResources.skills
.filter(skill => isSkillAllowedByAgent(skill.name))
.map(skill => ({

View File

@ -23,15 +23,26 @@
</template>
<nav class="sandbox-steps" :aria-label="$t('settings.sandbox.setupProgress')">
<div v-for="(item, index) in wizardSteps" :key="item.key"
:class="['sandbox-step', { 'is-active': wizardStep === index, 'is-done': wizardStep > index }]">
<component
:is="canJumpTo(index) ? 'button' : 'div'"
v-for="(item, index) in wizardSteps"
:key="item.key"
:type="canJumpTo(index) ? 'button' : undefined"
:class="['sandbox-step', {
'is-active': wizardStep === index,
'is-done': wizardStep > index,
'is-clickable': canJumpTo(index),
}]"
:aria-current="wizardStep === index ? 'step' : undefined"
@click="goToStep(index)"
>
<span class="sandbox-step__marker">
<t-icon v-if="wizardStep > index" name="check" />
<template v-else>{{ index + 1 }}</template>
</span>
<span class="sandbox-step__title">{{ item.title }}</span>
<span v-if="index < wizardSteps.length - 1" class="sandbox-step__line" aria-hidden="true" />
</div>
</component>
</nav>
<!--
@ -366,7 +377,19 @@
</section>
</t-form>
<div v-if="checkResult && currentStepKey !== 'template'" ref="checkResultRef" class="check-result">
<!--
Skills need an image to be installed into, so this step is only reachable
once the config exists. During creation the wizard walks into it right
after the first successful save; the hint covers the one case left, a
config whose save was refused.
-->
<template v-if="currentStepKey === 'skills'">
<SandboxSkillsPanel v-if="effectiveRecord" :record="effectiveRecord" @updated="onSkillsConfigUpdated" />
<p v-else class="skills-locked">{{ $t('settings.sandbox.stepSkillsLocked') }}</p>
</template>
<div v-if="checkResult && currentStepKey !== 'template' && currentStepKey !== 'skills'"
ref="checkResultRef" class="check-result">
<div :class="['check-result__summary', checkResult.ok ? 'is-success' : 'is-error']">
<span class="check-result__summary-icon">
<t-icon :name="checkResult.ok ? 'check-circle-filled' : 'close-circle-filled'" />
@ -433,6 +456,7 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import SandboxBackendBadge from '@/components/settings/SandboxBackendBadge.vue'
import SandboxSkillsPanel from '@/components/SandboxSkillsPanel.vue'
import {
checkSandboxConfig,
createSandboxConfig,
@ -452,10 +476,15 @@ import {
NAMED_SANDBOX_BACKEND_TYPES,
} from '@/api/system'
type SandboxStepKey = 'connection' | 'template' | 'runtime' | 'skills'
const props = defineProps<{
visible: boolean
record: SandboxConfigRecord | null
presetType?: string
// Which page to land on when opening an existing config, e.g. 'skills' from
// the card's 管理技能 entry. Ignored while creating, where order is enforced.
initialStep?: SandboxStepKey
}>()
const emit = defineEmits<{
@ -515,7 +544,6 @@ const currentTemplateId = computed(() => (
backend.value === 'cube' ? cube.template_id : backend.value === 'e2b' ? e2b.template_id : ''
)?.trim() || '')
const selectedTemplate = computed(() => templates.value.find((item) => item.id === currentTemplateId.value))
type SandboxStepKey = 'connection' | 'template' | 'runtime'
const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() => {
const steps: Array<{ key: SandboxStepKey; title: string }> = [
{ key: 'connection', title: t('settings.sandbox.stepConnection') },
@ -524,6 +552,12 @@ const wizardSteps = computed<Array<{ key: SandboxStepKey; title: string }>>(() =
steps.push({ key: 'template', title: t('settings.sandbox.stepTemplate') })
}
steps.push({ key: 'runtime', title: t('settings.sandbox.stepRuntime') })
// Skills are baked into the config's snapshot image, which only the remote
// backends have. Docker and local configs therefore end at runtime rather
// than showing a step that could never do anything.
if (isRemoteBackend.value) {
steps.push({ key: 'skills', title: t('settings.sandbox.stepSkills') })
}
return steps
})
const currentStepKey = computed<SandboxStepKey>(() => wizardSteps.value[wizardStep.value]?.key || 'connection')
@ -531,12 +565,51 @@ const stepDescription = computed(() => t(`settings.sandbox.stepDescriptions.${cu
const primaryText = computed(() => {
if (currentStepKey.value === 'connection') return t('settings.sandbox.connectAndContinue')
if (currentStepKey.value === 'template') return t('common.next')
// Nothing on the skills step is pending a save — each install, toggle and
// removal already went to the server on its own.
if (currentStepKey.value === 'skills') return t('common.finish')
return t('common.save')
})
const primaryDisabled = computed(() => (
currentStepKey.value === 'template'
&& (!selectedTemplate.value || !isTemplateSelectable(selectedTemplate.value))
))
// savedRecord is the config this drawer is editing, including one it just
// created: after the first save the wizard keeps going into the skills step,
// which needs an ID, and a second press of save must update that config rather
// than create another one.
const savedRecord = ref<SandboxConfigRecord | null>(null)
const effectiveRecord = computed(() => savedRecord.value || props.record)
function onSkillsConfigUpdated(record: SandboxConfigRecord) {
savedRecord.value = record
}
// Jumping is what separates editing from creating. A config that does not exist
// yet has to be built in order — its connection has to check out before there
// are templates to choose from, and it has no image to install skills into. Once
// it exists, every step is just a page of its settings, so all of them open
// directly; steps already visited stay clickable during creation so the rail
// works as a way back.
function canJumpTo(index: number): boolean {
if (index === wizardStep.value) return false
return Boolean(effectiveRecord.value) || index < wizardStep.value
}
function goToStep(index: number) {
if (!canJumpTo(index)) return
wizardStep.value = index
if (currentStepKey.value !== 'template') {
stopTemplatePolling()
return
}
// Landing on the template step without having passed through the connection
// 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)
}
const hasPendingTemplates = computed(() => templates.value.some(isTemplatePending))
const backendLabel = (value: string) => t(`settings.sandbox.backends.${value}`)
@ -663,7 +736,14 @@ function reset() {
templates.value = []
templatesLoaded.value = false
templatesError.value = ''
savedRecord.value = null
wizardStep.value = 0
// "管理技能" opens this drawer straight on the skills step. It is a jump like
// any other, so it only holds for a config that already exists.
if (props.initialStep && props.record) {
const index = wizardSteps.value.findIndex((step) => step.key === props.initialStep)
if (index >= 0) wizardStep.value = index
}
}
function selectBackend(value: string) {
@ -783,7 +863,7 @@ async function loadTemplates(ensureStandard: boolean, silent = false): Promise<b
try {
const res = await querySandboxTemplates({
config: collectPayload(),
config_id: props.record?.id,
config_id: effectiveRecord.value?.id,
ensure_standard: ensureStandard,
})
templates.value = res.data?.templates || []
@ -826,6 +906,7 @@ function collectPayload(): SandboxConfig {
default_timeout_sec: defaultTimeoutSec.value || undefined,
allow_private_endpoints: allowPrivateEndpoints.value || undefined,
env_vars: envVars,
skill_rollout: effectiveRecord.value?.config?.skill_rollout,
}
// Send only the selected backend's block so an unused one cannot fail
// validation (e.g. a stale private URL left in the other tab).
@ -875,6 +956,10 @@ async function handlePrimaryAction() {
wizardStep.value += 1
return
}
if (currentStepKey.value === 'skills') {
close()
return
}
await save()
}
@ -897,13 +982,23 @@ async function save() {
conflict.value = null
try {
const payload = { name: trimmed, description: description.value, config: collectPayload() }
if (props.record) {
await updateSandboxConfigById(props.record.id, payload)
} else {
await createSandboxConfig(payload)
}
const existing = effectiveRecord.value
const res = existing
? await updateSandboxConfigById(existing.id, payload)
: await createSandboxConfig(payload)
MessagePlugin.success(t('common.saveSuccess'))
// The list behind the drawer refreshes either way, so closing here is only
// about whether the wizard has anything left to offer.
emit('saved')
const saved = res?.data
if (saved) savedRecord.value = saved
const skillsStep = wizardSteps.value.findIndex((step) => step.key === 'skills')
if (!existing && skillsStep >= 0 && savedRecord.value) {
// A config created a moment ago has an empty image; walking into the
// skills step is the whole reason the wizard has a fourth page.
wizardStep.value = skillsStep
return
}
close()
} catch (e: any) {
const refusal = parseSandboxConflict(e)
@ -932,7 +1027,7 @@ async function runCheck(deep: boolean): Promise<boolean> {
// so an edited form can be probed without retyping the API key.
const res = await checkSandboxConfig({
config: collectPayload(),
config_id: props.record?.id,
config_id: effectiveRecord.value?.id,
deep,
})
checkResult.value = res?.data || null
@ -1007,6 +1102,30 @@ onUnmounted(stopTemplatePolling)
&.is-done {
color: var(--td-text-color-secondary);
}
/*
Reachable steps render as <button>, so the browser's own control styling has
to be undone to keep the rail looking identical either way. Only the cursor
and hover state give the affordance away.
*/
&.is-clickable {
padding: 0;
font: inherit;
text-align: left;
background: none;
border: 0;
cursor: pointer;
&:hover:not(.is-active) {
color: var(--td-brand-color);
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
border-radius: 4px;
}
}
}
.sandbox-step__marker {
@ -1055,6 +1174,13 @@ onUnmounted(stopTemplatePolling)
}
}
.skills-locked {
margin: 24px 0;
color: var(--td-text-color-placeholder);
font-size: 13px;
text-align: center;
}
.sandbox-editor-form {
:deep(.t-form__item) {
margin-bottom: 0;

View File

@ -0,0 +1,943 @@
<template>
<div class="sandbox-skills-panel">
<t-loading :loading="loading" size="small">
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.imageInfoTitle') }}</h4>
<ul class="image-info">
<li>
<span class="image-info__label">{{ $t('settings.sandbox.imageInfoBaseTemplate') }}</span>
<span class="image-info__value image-info__value--id">
{{ skillImage?.base_template_id || $t('settings.sandbox.imageInfoEmpty') }}
</span>
</li>
<li>
<span class="image-info__label">{{ $t('settings.sandbox.imageInfoSnapshot') }}</span>
<span class="image-info__value image-info__value--id">
{{ skillImage?.snapshot_id || $t('settings.sandbox.imageInfoEmpty') }}
</span>
</li>
<li>
<span class="image-info__label">{{ $t('settings.sandbox.imageInfoGeneration') }}</span>
<span class="image-info__value">
{{ skillImage?.generation ? String(skillImage.generation) : $t('settings.sandbox.imageInfoEmpty') }}
</span>
</li>
<li>
<span class="image-info__label">{{ $t('settings.sandbox.imageInfoBuiltAt') }}</span>
<span class="image-info__value">{{ formatBuiltAt(skillImage?.built_at) }}</span>
</li>
</ul>
</section>
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillInstallerModel') }}</h4>
<p class="installer-model-hint">{{ $t('settings.sandbox.skillInstallerModelHint') }}</p>
<ModelSelector
model-type="KnowledgeQA"
:selected-model-id="installerModelId"
:disabled="savingInstallerModel"
@update:selected-model-id="onInstallerModelChange"
/>
</section>
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillRollout') }}</h4>
<p class="installer-model-hint">{{ $t('settings.sandbox.skillRolloutHint') }}</p>
<t-radio-group
:value="skillRollout"
:disabled="savingRollout"
class="skill-rollout-group"
@change="onSkillRolloutChange"
>
<t-radio value="next_turn">{{ $t('settings.sandbox.skillRolloutNextTurn') }}</t-radio>
<t-radio value="new_session">{{ $t('settings.sandbox.skillRolloutNewSession') }}</t-radio>
</t-radio-group>
</section>
<section class="setting-drawer__section">
<input
ref="fileInputRef"
type="file"
accept=".zip,application/zip"
class="file-input-hidden"
@change="onFileInputChange"
/>
<div
class="file-upload-area"
:class="{ 'has-file': uploading }"
@click="fileInputRef?.click()"
@dragover.prevent
@dragenter.prevent
@drop.prevent="onFileDrop"
>
<div class="file-upload-content">
<t-icon name="upload" size="32px" class="upload-icon" />
<div class="upload-text">
<span v-if="uploading" class="upload-file-name">
{{ $t('settings.sandbox.skillUploading', { percent: uploadPercent }) }}
</span>
<template v-else>
<span class="upload-primary-text">{{ $t('settings.sandbox.skillUploadClick') }}</span>
<span class="upload-secondary-text">{{ $t('settings.sandbox.skillUploadDrag') }}</span>
</template>
</div>
<t-progress v-if="uploading" :percentage="uploadPercent" size="small" />
</div>
</div>
<p class="upload-hint">{{ uploadHint }}</p>
<p v-if="!loading && skills.length === 0" class="skill-empty">
{{ $t('settings.sandbox.skillEmpty') }}
</p>
<ul class="skill-list">
<li v-for="skill in skills" :key="skill.id" class="skill-item">
<div class="skill-status-ring" :title="statusLabel(skill)">
<t-progress
v-if="isBusy(skill)"
theme="circle"
:percentage="progressOf(skill)"
:size="32"
/>
<t-icon
v-else-if="skill.status === 'failed'"
name="close-circle-filled"
class="skill-status-ring__failed"
/>
<t-icon
v-else
name="check-circle-filled"
class="skill-status-ring__ready"
/>
</div>
<div class="skill-item__body">
<div class="skill-item__title">{{ skill.name || skill.id }}</div>
<p v-if="skill.description" class="skill-item__desc">{{ skill.description }}</p>
<p class="skill-item__meta">
<span>{{ statusLabel(skill) }}</span>
<span v-if="isBusy(skill)"> · {{ progressOf(skill) }}%</span>
</p>
<p v-if="skill.status === 'failed' && (skill.error || progressLog(skill))" class="skill-item__error">
{{ skill.error || progressLog(skill) }}
</p>
</div>
<div class="skill-item__actions">
<t-tooltip :content="$t('settings.sandbox.skillDisableHint')" placement="top">
<t-switch
:value="skill.enabled"
:disabled="isBusy(skill)"
:loading="togglingId === skill.id"
@change="(v: any) => toggleEnabled(skill, Boolean(v))"
/>
</t-tooltip>
<t-tooltip
v-if="hasTranscript(skill)"
:content="
expandedSkillId === skill.id
? $t('settings.sandbox.skillTranscriptHide')
: $t('settings.sandbox.skillTranscript')
"
placement="top"
>
<t-button
variant="text"
shape="square"
size="small"
:class="{ 'skill-transcript-toggle--on': expandedSkillId === skill.id }"
@click="toggleTranscript(skill)"
>
<template #icon>
<t-icon :name="expandedSkillId === skill.id ? 'chevron-up' : 'chat-bubble-history'" />
</template>
</t-button>
</t-tooltip>
<t-tooltip :content="$t('settings.sandbox.skillView')" placement="top">
<t-button
variant="text"
shape="square"
size="small"
@click="openView(skill)"
>
<template #icon><t-icon name="browse" /></template>
</t-button>
</t-tooltip>
<t-popconfirm
theme="warning"
:content="deleteHint"
:confirm-btn="{ content: $t('common.delete'), theme: 'danger' }"
:cancel-btn="{ content: $t('common.cancel') }"
placement="top-right"
@confirm="removeSkill(skill)"
>
<t-tooltip :content="$t('common.delete')" placement="top">
<t-button
theme="danger"
variant="text"
shape="square"
size="small"
:disabled="isBusy(skill)"
:loading="deletingId === skill.id"
>
<template #icon><t-icon name="delete" /></template>
</t-button>
</t-tooltip>
</t-popconfirm>
</div>
<SkillInstallTimeline
v-if="expandedSkillId === skill.id"
:key="`${skill.id}-${skill.install_session_id || ''}-${transcriptEpoch}`"
class="skill-item__timeline"
:config-id="record?.id || ''"
:skill-id="skill.id"
:session-id="skill.install_session_id || ''"
:message-id="skill.install_message_id || ''"
:live="skill.status === 'installing'"
/>
</li>
</ul>
</section>
</t-loading>
<t-dialog
v-model:visible="showView"
:header="viewing?.name || $t('settings.sandbox.skillView')"
:footer="false"
width="520px"
attach="body"
>
<ul v-if="viewing" class="skill-view">
<li>
<span class="skill-view__label">{{ $t('settings.sandbox.skillVersion') }}</span>
<span class="skill-view__value">{{ viewing.version || $t('settings.sandbox.skillVersionEmpty') }}</span>
</li>
<li>
<span class="skill-view__label">{{ $t('settings.sandbox.skillStatusLabel') }}</span>
<span class="skill-view__value">{{ statusLabel(viewing) }}</span>
</li>
<li v-if="viewing.description">
<span class="skill-view__label">{{ $t('settings.sandbox.configDescription') }}</span>
<span class="skill-view__value">{{ viewing.description }}</span>
</li>
<li v-if="viewing.error">
<span class="skill-view__label">{{ $t('settings.sandbox.skillError') }}</span>
<span class="skill-view__value skill-view__error">{{ viewing.error }}</span>
</li>
</ul>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import ModelSelector from '@/components/ModelSelector.vue'
import SkillInstallTimeline from '@/components/SkillInstallTimeline.vue'
import {
getAgentById,
updateAgent,
type CustomAgent,
} from '@/api/agent'
import {
configSkillInstallEventsUrl,
deleteConfigSkill,
getSandboxConfigById,
updateSandboxConfigById,
listConfigSkills,
patchConfigSkill,
uploadConfigSkill,
type ConfigSkill,
type ConfigSkillInstallEvent,
type SandboxConfigRecord,
type SandboxSkillImage,
} from '@/api/system'
import { getApiBaseUrl } from '@/utils/api-base'
import { generateRandomString } from '@/utils/index'
import i18n from '@/i18n'
// Skills are installed into the config's snapshot image, so the panel needs a
// config that already exists. The editor only renders it on a saved config.
const props = defineProps<{
record: SandboxConfigRecord | null
}>()
const emit = defineEmits<{
updated: [record: SandboxConfigRecord]
}>()
const { t, locale } = useI18n()
const loading = ref(false)
const uploading = ref(false)
const uploadPercent = ref(0)
const skills = ref<ConfigSkill[]>([])
const skillImage = ref<SandboxSkillImage | null>(null)
const togglingId = ref('')
const deletingId = ref('')
const showView = ref(false)
const viewing = ref<ConfigSkill | null>(null)
// Only one install timeline is open at a time: each one holds an SSE
// connection, and two runs' worth of agent steps in a drawer is unreadable.
const expandedSkillId = ref('')
const transcriptEpoch = ref(0)
const fileInputRef = ref<HTMLInputElement | null>(null)
const progressById = ref<Record<string, ConfigSkillInstallEvent>>({})
const abortBySkill = new Map<string, AbortController>()
let pollTimer: number | null = null
const INSTALLER_AGENT_ID = 'builtin-skill-installer'
const LAST_CHAT_MODEL_KEY = 'weknora_last_chat_model_id'
const installerAgent = ref<CustomAgent | null>(null)
const installerModelId = ref('')
const savingInstallerModel = ref(false)
const skillRollout = ref<'next_turn' | 'new_session'>('next_turn')
const savingRollout = ref(false)
function normalizeSkillRollout(value?: string): 'next_turn' | 'new_session' {
return value === 'new_session' ? 'new_session' : 'next_turn'
}
const uploadHint = computed(() =>
skillRollout.value === 'new_session'
? t('settings.sandbox.skillUploadHintNewSession')
: t('settings.sandbox.skillUploadHint'),
)
const deleteHint = computed(() =>
skillRollout.value === 'new_session'
? t('settings.sandbox.skillDeleteHintNewSession')
: t('settings.sandbox.skillDeleteHint'),
)
function readLastChatModelID(): string {
try {
return localStorage.getItem(LAST_CHAT_MODEL_KEY) || ''
} catch {
return ''
}
}
function formatBuiltAt(value?: string): string {
if (!value) return t('settings.sandbox.imageInfoEmpty')
const date = new Date(value)
if (Number.isNaN(date.getTime()) || date.getFullYear() <= 1) {
return t('settings.sandbox.imageInfoEmpty')
}
return date.toLocaleString(locale.value)
}
const STATUS_I18N: Record<string, string> = {
installing: 'settings.sandbox.skillStatusInstalling',
ready: 'settings.sandbox.skillStatusReady',
failed: 'settings.sandbox.skillStatusFailed',
removing: 'settings.sandbox.skillStatusRemoving',
}
function statusLabel(skill: ConfigSkill): string {
const key = STATUS_I18N[skill.status]
return key ? t(key) : skill.status
}
function isBusy(skill: ConfigSkill): boolean {
return skill.status === 'installing' || skill.status === 'removing'
}
// The locators are written only after the installer sandbox is up and the
// agent has a message to stream into. The row itself is already "installing"
// the moment the upload is accepted, and that is when the button has to
// appear — waiting for the locators would hide it for the first minute.
function hasTranscript(skill: ConfigSkill): boolean {
if (skill.status === 'installing') return true
return Boolean(skill.install_session_id && skill.install_message_id)
}
function toggleTranscript(skill: ConfigSkill) {
if (expandedSkillId.value === skill.id) {
expandedSkillId.value = ''
return
}
expandedSkillId.value = skill.id
// A run that finished while the timeline was open was tailed from the event
// log; reopening it should read the run again from the top rather than show
// whatever the closed stream left behind.
transcriptEpoch.value += 1
}
function progressOf(skill: ConfigSkill): number {
const percent = progressById.value[skill.id]?.percent
if (typeof percent === 'number' && Number.isFinite(percent)) {
return Math.max(0, Math.min(100, percent))
}
return skill.status === 'ready' || skill.status === 'failed' ? 100 : 0
}
function progressLog(skill: ConfigSkill): string {
return progressById.value[skill.id]?.log || ''
}
function stopFollow(skillId: string) {
const controller = abortBySkill.get(skillId)
if (controller) {
controller.abort()
abortBySkill.delete(skillId)
}
}
function stopAllFollows() {
for (const skillId of [...abortBySkill.keys()]) {
stopFollow(skillId)
}
}
function stopPoll() {
if (pollTimer != null) {
window.clearInterval(pollTimer)
pollTimer = null
}
}
function ensurePoll() {
const busy = skills.value.some(isBusy)
if (busy && pollTimer == null) {
pollTimer = window.setInterval(() => {
void loadSkills(true)
}, 2000)
} else if (!busy) {
stopPoll()
}
}
function followBusySkills() {
if (!props.record) return
const busyIds = new Set(skills.value.filter(isBusy).map((skill) => skill.id))
for (const skillId of [...abortBySkill.keys()]) {
if (!busyIds.has(skillId)) stopFollow(skillId)
}
for (const skill of skills.value) {
if (isBusy(skill)) followProgress(skill.id)
}
}
function followProgress(skillId: string) {
if (!props.record || abortBySkill.has(skillId)) return
const configId = props.record.id
const controller = new AbortController()
abortBySkill.set(skillId, controller)
const token = localStorage.getItem('weknora_token')
const tenantId = localStorage.getItem('weknora_selected_tenant_id')
const url = `${getApiBaseUrl()}${configSkillInstallEventsUrl(configId, skillId)}`
void fetchEventSource(url, {
method: 'GET',
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Accept-Language': i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
'X-Request-ID': generateRandomString(12),
...(tenantId ? { 'X-Tenant-ID': tenantId } : {}),
},
signal: controller.signal,
openWhenHidden: true,
onmessage(ev) {
if (!ev.data) return
let parsed: ConfigSkillInstallEvent
try {
parsed = JSON.parse(ev.data) as ConfigSkillInstallEvent
} catch {
return
}
progressById.value = { ...progressById.value, [skillId]: parsed }
if (parsed.done) {
stopFollow(skillId)
void loadSkills()
void refreshImage()
}
},
onerror() {
stopFollow(skillId)
throw new Error('skill install stream closed')
},
}).catch(() => {
stopFollow(skillId)
})
}
async function refreshImage() {
if (!props.record) return
try {
const res = await getSandboxConfigById(props.record.id)
skillImage.value = res?.data?.config?.skill_image || null
skillRollout.value = normalizeSkillRollout(res?.data?.config?.skill_rollout)
} catch {
skillImage.value = props.record.config?.skill_image || null
}
}
async function loadSkills(silent = false) {
if (!props.record) return
if (!silent) loading.value = true
try {
const res = await listConfigSkills(props.record.id)
skills.value = res?.data || []
followBusySkills()
ensurePoll()
} catch (e: any) {
if (!silent) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillLoadFailed'))
}
} finally {
if (!silent) loading.value = false
}
}
async function loadAll() {
skillImage.value = props.record?.config?.skill_image || null
skillRollout.value = normalizeSkillRollout(props.record?.config?.skill_rollout)
await Promise.all([loadSkills(), refreshImage(), loadInstallerModel()])
}
async function loadInstallerModel() {
try {
const res = await getAgentById(INSTALLER_AGENT_ID)
installerAgent.value = res?.data || null
const configured = installerAgent.value?.config?.model_id?.trim() || ''
installerModelId.value = configured || readLastChatModelID()
} catch {
installerAgent.value = null
installerModelId.value = readLastChatModelID()
}
}
async function persistInstallerModel(modelId: string) {
const id = modelId.trim()
if (!id) {
throw new Error(t('settings.sandbox.skillInstallerModelRequired'))
}
const current = installerAgent.value
const config = { ...(current?.config || {}), model_id: id }
const res = await updateAgent(INSTALLER_AGENT_ID, {
name: current?.name || '',
description: current?.description || '',
avatar: current?.avatar || '',
config,
})
installerAgent.value = res?.data || { ...(current as CustomAgent), config }
installerModelId.value = id
}
async function onSkillRolloutChange(value: string) {
const next = normalizeSkillRollout(value)
if (!props.record || next === skillRollout.value) return
const previous = skillRollout.value
skillRollout.value = next
savingRollout.value = true
try {
const res = await getSandboxConfigById(props.record.id)
const current = res?.data
const saved = await updateSandboxConfigById(props.record.id, {
name: current?.name || props.record.name,
description: current?.description || props.record.description,
config: { ...(current?.config || props.record.config || {}), skill_rollout: next },
})
if (saved?.data) emit('updated', saved.data)
} catch (e: any) {
skillRollout.value = previous
MessagePlugin.error(e?.message || t('settings.sandbox.skillRolloutSaveFailed'))
} finally {
savingRollout.value = false
}
}
async function onInstallerModelChange(modelId: string) {
if (!modelId || modelId === '__add_model__') return
installerModelId.value = modelId
savingInstallerModel.value = true
try {
await persistInstallerModel(modelId)
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillInstallerModelSaveFailed'))
} finally {
savingInstallerModel.value = false
}
}
function isZipFile(file: File): boolean {
return file.name.toLowerCase().endsWith('.zip') || file.type === 'application/zip'
}
async function uploadFile(file: File) {
if (!props.record || uploading.value) return
if (!installerModelId.value) {
MessagePlugin.warning(t('settings.sandbox.skillInstallerModelRequired'))
return
}
if (!isZipFile(file)) {
MessagePlugin.error(t('settings.sandbox.skillUploadFailed'))
return
}
uploading.value = true
uploadPercent.value = 0
try {
await persistInstallerModel(installerModelId.value)
const res = await uploadConfigSkill(props.record.id, file, (percent) => {
uploadPercent.value = percent
})
MessagePlugin.success(t('settings.sandbox.skillUploadAccepted'))
const skillId = res?.data?.skill_id
await loadSkills()
await refreshImage()
if (skillId) followProgress(skillId)
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed'))
} finally {
uploading.value = false
uploadPercent.value = 0
if (fileInputRef.value) fileInputRef.value.value = ''
}
}
function onFileInputChange(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
if (file) void uploadFile(file)
}
function onFileDrop(event: DragEvent) {
const file = event.dataTransfer?.files?.[0]
if (file) void uploadFile(file)
}
async function toggleEnabled(skill: ConfigSkill, enabled: boolean) {
if (!props.record) return
togglingId.value = skill.id
try {
const res = await patchConfigSkill(props.record.id, skill.id, { enabled })
const updated = res?.data
skills.value = skills.value.map((item) => (item.id === skill.id ? (updated || { ...item, enabled }) : item))
MessagePlugin.success(
enabled ? t('settings.sandbox.skillEnabled') : t('settings.sandbox.skillDisabled'),
)
} catch (e: any) {
MessagePlugin.error(e?.message || t('settings.sandbox.skillToggleFailed'))
} finally {
togglingId.value = ''
}
}
async function removeSkill(skill: ConfigSkill) {
if (!props.record) return
deletingId.value = skill.id
try {
await deleteConfigSkill(props.record.id, skill.id)
MessagePlugin.success(t('settings.sandbox.skillDeleteAccepted'))
await loadSkills()
followProgress(skill.id)
} catch (e: any) {
MessagePlugin.error(e?.message || t('common.deleteFailed'))
} finally {
deletingId.value = ''
}
}
function openView(skill: ConfigSkill) {
viewing.value = skill
showView.value = true
}
// The panel is mounted only while its wizard step is showing, so switching
// steps tears the follows down and coming back re-reads the list.
watch(
() => props.record?.id,
(configID) => {
if (configID) {
void loadAll()
return
}
stopAllFollows()
stopPoll()
skills.value = []
progressById.value = {}
showView.value = false
viewing.value = null
installerAgent.value = null
installerModelId.value = ''
},
{ immediate: true },
)
onUnmounted(() => {
stopAllFollows()
stopPoll()
})
</script>
<style lang="less" scoped>
.image-info {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 8px;
}
.image-info li {
display: grid;
grid-template-columns: 88px minmax(0, 1fr);
gap: 12px;
align-items: start;
}
.installer-model-hint {
margin: 0 0 10px;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-secondary);
}
.skill-rollout-group {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.image-info__label {
color: var(--td-text-color-secondary);
font-size: 12px;
line-height: 1.45;
padding-top: 1px;
}
.image-info__value {
color: var(--td-text-color-primary);
font-size: 13px;
font-weight: 500;
line-height: 1.45;
min-width: 0;
}
.image-info__value--id {
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
font-weight: 400;
overflow-wrap: anywhere;
word-break: break-all;
user-select: all;
}
.file-input-hidden {
display: none;
}
.file-upload-area {
position: relative;
width: 100%;
min-height: 120px;
border: 2px dashed var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-secondarycontainer);
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
&:hover {
border-color: var(--td-brand-color);
background: var(--td-success-color-light);
}
&.has-file {
border-color: var(--td-brand-color);
background: var(--td-success-color-light);
border-style: solid;
}
}
.file-upload-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
text-align: center;
padding: 16px;
width: 100%;
}
.upload-icon {
color: var(--td-brand-color);
transition: transform 0.2s ease;
}
.file-upload-area:hover .upload-icon {
transform: translateY(-2px);
}
.upload-text {
display: flex;
flex-direction: column;
gap: 4px;
}
.upload-primary-text {
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
}
.upload-secondary-text {
font-size: 12px;
color: var(--td-text-color-secondary);
}
.upload-file-name {
font-size: 14px;
font-weight: 500;
color: var(--td-brand-color);
}
.upload-hint {
margin: 8px 0 0;
font-size: 12px;
color: var(--td-text-color-placeholder);
line-height: 1.5;
}
.skill-empty {
margin: 12px 0 0;
font-size: 13px;
color: var(--td-text-color-placeholder);
}
.skill-list {
margin: 12px 0 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 8px;
}
// A grid rather than a flex row so the expanded install timeline can span the
// full width underneath the three columns of the row it belongs to.
.skill-item {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: flex-start;
gap: 12px;
padding: 12px;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
background: var(--td-bg-color-container);
}
.skill-item__timeline {
grid-column: 1 / -1;
}
.skill-transcript-toggle--on {
color: var(--td-brand-color);
}
.skill-status-ring {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: var(--td-text-color-secondary);
:deep(.t-progress) {
width: 32px;
height: 32px;
}
&__ready {
color: var(--td-success-color);
font-size: 22px;
}
&__failed {
color: var(--td-error-color);
font-size: 22px;
}
}
.skill-item__body {
flex: 1;
min-width: 0;
}
.skill-item__title {
font-size: 14px;
font-weight: 600;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.skill-item__desc,
.skill-item__meta {
margin: 2px 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-secondary);
}
.skill-item__desc {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.skill-item__error {
margin: 4px 0 0;
font-size: 12px;
line-height: 1.45;
color: var(--td-error-color);
}
.skill-item__actions {
display: flex;
align-items: center;
gap: 2px;
flex-shrink: 0;
}
.skill-view {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 10px;
}
.skill-view li {
display: flex;
flex-direction: column;
gap: 2px;
}
.skill-view__label {
font-size: 12px;
color: var(--td-text-color-secondary);
}
.skill-view__value {
font-size: 13px;
color: var(--td-text-color-primary);
white-space: pre-wrap;
word-break: break-word;
}
.skill-view__error {
color: var(--td-error-color);
}
</style>

View File

@ -0,0 +1,223 @@
<template>
<section class="skill-timeline" :aria-busy="loading">
<t-loading v-if="loading && messages.length === 0" size="small" />
<p v-else-if="messages.length === 0" class="skill-timeline__empty">
{{ live
? $t('settings.sandbox.skillTranscriptWaiting')
: $t('settings.sandbox.skillTranscriptEmpty') }}
</p>
<template v-else>
<div v-for="(msg, index) in messages" :key="msg.id || index" class="skill-timeline__turn">
<pre v-if="msg.role === 'user'" class="skill-timeline__prompt">{{ msg.content }}</pre>
<AgentStreamDisplay
v-else
:session="msg"
:session-id="sessionId"
:user-query="''"
/>
</div>
</template>
</section>
</template>
<script setup lang="ts">
import { onUnmounted, reactive, ref, watch } from 'vue'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { useChatStreamHandler } from '@/composables/useChatStreamHandler'
import { getMessageList } from '@/api/chat'
import { configSkillTranscriptUrl } from '@/api/system'
import { getApiBaseUrl } from '@/utils/api-base'
import { generateRandomString } from '@/utils/index'
import AgentStreamDisplay from '@/views/chat/components/AgentStreamDisplay.vue'
import i18n from '@/i18n'
const props = defineProps<{
configId: string
skillId: string
// The durable rows behind the run, used when the event log has aged out.
sessionId: string
messageId: string
// True while this skill is still installing. The locators are written only
// after the installer sandbox is up, so a 404 here means "not yet" rather
// than "gone" and the stream is retried.
live?: boolean
}>()
const messages = reactive<any[]>([])
const loading = ref(false)
const isReplying = ref(false)
const currentAssistantMessageId = ref('')
const fullContent = ref('')
let controller: AbortController | null = null
let closed = false
// The timeline grows inside the drawer's own scroll container, so following the
// tail would mean scrolling the whole drawer under a reader who is inspecting
// an earlier command. The stream handler requires the hook, so it is a no-op.
function scrollToBottom() {}
const { handleMsgList, processStreamChunk } = useChatStreamHandler({
messagesList: messages,
loading,
isReplying,
currentAssistantMessageId,
fullContent,
isAgentStreamSession: () => true,
scrollToBottom,
})
// install_prompt is the installer's opening line. It is not an assistant
// event, so it becomes the user turn here rather than going through the chat
// stream handler.
function applyPrompt(content: string) {
if (!content) return
if (messages.some((msg) => msg.role === 'user')) return
messages.unshift({ id: `${props.messageId}-prompt`, role: 'user', content })
}
async function loadPersisted() {
const res: any = await getMessageList({
session_id: props.sessionId,
limit: 100,
created_at: '',
})
handleMsgList(res?.data || [])
}
function stop() {
closed = true
if (controller) {
controller.abort()
controller = null
}
}
// follow tails the transcript endpoint. It resolves when the stream ends, and
// reports whether it ever produced anything: a 404 means the event log has
// expired and the durable history is the only remaining source.
async function follow(): Promise<boolean> {
const url = `${getApiBaseUrl()}${configSkillTranscriptUrl(props.configId, props.skillId)}`
const token = localStorage.getItem('weknora_token')
const tenantId = localStorage.getItem('weknora_selected_tenant_id')
controller = new AbortController()
let served = false
await fetchEventSource(url, {
method: 'GET',
headers: {
Authorization: token ? `Bearer ${token}` : '',
'Accept-Language': i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN',
'X-Request-ID': generateRandomString(12),
...(tenantId ? { 'X-Tenant-ID': tenantId } : {}),
},
signal: controller.signal,
openWhenHidden: true,
onopen: async (response) => {
if (response.ok) {
served = true
return
}
// Anything else is terminal for this attempt; fetchEventSource must not
// retry, so the error is thrown for the caller to fall back on.
throw new Error(`transcript stream refused: ${response.status}`)
},
onmessage(ev) {
if (!ev.data) return
let frame: any
try {
frame = JSON.parse(ev.data)
} catch {
return
}
if (frame.response_type === 'install_prompt') {
applyPrompt(frame.content || '')
return
}
processStreamChunk(frame)
},
onerror(err) {
// Rethrowing stops fetchEventSource's own retry loop.
throw err
},
})
return served
}
function wait(ms: number): Promise<void> {
return new Promise((resolve) => {
window.setTimeout(resolve, ms)
})
}
async function open() {
closed = false
messages.splice(0, messages.length)
loading.value = true
try {
// Locators land after the installer sandbox is up. Keep asking until the
// stream answers or this run is no longer live; falling through to the
// empty state on the first 404 would flash "no record" during setup.
for (;;) {
const served = await follow().catch(() => false)
if (closed || served) return
if (props.sessionId && props.messageId) {
await loadPersisted()
if (messages.length > 0 || closed) return
}
if (!props.live || closed) return
await wait(1000)
if (!props.live || closed) return
}
} catch {
// Both sources are gone; the empty state says so.
} finally {
loading.value = false
}
}
watch(
() => [props.configId, props.skillId, props.sessionId, props.live] as const,
() => {
stop()
if (props.configId && props.skillId) void open()
},
{ immediate: true },
)
onUnmounted(stop)
</script>
<style scoped lang="less">
.skill-timeline {
padding: 12px;
background: var(--td-bg-color-secondarycontainer, #f7f7f7);
border: 1px solid var(--td-component-stroke, #e7e7e7);
border-radius: 8px;
}
.skill-timeline__turn + .skill-timeline__turn {
margin-top: 12px;
}
.skill-timeline__prompt {
max-height: 140px;
margin: 0;
padding: 8px 10px;
overflow-y: auto;
color: var(--td-text-color-secondary, #666);
font-size: 12px;
line-height: 1.6;
background: var(--td-bg-color-container, #fff);
border-radius: 6px;
white-space: pre-wrap;
word-break: break-word;
}
.skill-timeline__empty {
margin: 8px 0;
color: var(--td-text-color-placeholder, #999);
font-size: 13px;
}
</style>

View File

@ -1064,11 +1064,14 @@ export default {
stepConnection: 'Connect',
stepTemplate: 'Template',
stepRuntime: 'Runtime',
stepSkills: 'Skills',
stepSkillsLocked: 'Skills are installed into this config\'s image. Save the config first, then come back to this step.',
setupProgress: 'Sandbox setup progress',
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
connectAndContinue: 'Connect and continue',
@ -1257,6 +1260,51 @@ export default {
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
manageSkills: 'Manage skills',
skillInstallerModel: 'Installer model',
skillInstallerModelHint: 'Used by the built-in installer agent. Choose a chat model that supports tool calls.',
skillInstallerModelRequired: 'Select an installer model first',
skillInstallerModelSaveFailed: 'Failed to save the installer model',
skillRollout: 'How the new skill image takes effect',
skillRolloutHint: 'Installing or removing a skill builds a new image. This controls whether already-open sessions switch to it.',
skillRolloutNextTurn: 'Rebuild open sessions on the next chat turn',
skillRolloutNewSession: 'Keep open sessions on their current sandbox; only new sessions use the new image',
skillRolloutSaveFailed: 'Failed to save the rollout setting',
skillUploadClick: 'Click to upload a skill bundle',
skillUploadDrag: 'or drop a .zip file here',
skillUploadHint: 'Upload installs the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillUploadHintNewSession: 'Upload installs the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
skillUploadFailed: 'Failed to upload the skill',
skillUploading: 'Uploading {percent}%',
skillUploadAccepted: 'Skill install started',
skillStatusInstalling: 'Installing',
skillStatusReady: 'Ready',
skillStatusFailed: 'Failed',
skillStatusRemoving: 'Removing',
skillStatusLabel: 'Status',
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: 'Delete removes the skill directory from the image and takes a new snapshot. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
skillDeleteHintNewSession: 'Delete removes the skill directory from the image and takes a new snapshot. Already-open sessions keep their current sandbox until they end; only newly started sessions lose this skill.',
imageInfoTitle: 'Current image',
imageInfoSnapshot: 'Snapshot ID',
imageInfoGeneration: 'Version',
imageInfoBuiltAt: 'Built at',
imageInfoBaseTemplate: 'Base template',
imageInfoEmpty: 'Using the base template',
skillView: 'View',
skillTranscript: 'View install run',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
skillLoadFailed: 'Failed to load skills',
skillToggleFailed: 'Failed to update the skill',
skillDeleteAccepted: 'Skill removal started',
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
skillVersion: 'Version',
skillVersionEmpty: 'Not specified',
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
},
mcpService: 'MCP Service',
versionInfo: 'Version Info',

View File

@ -4903,11 +4903,14 @@ export default {
stepConnection: 'Connect',
stepTemplate: 'Template',
stepRuntime: 'Runtime',
stepSkills: 'Skills',
stepSkillsLocked: 'Skills are installed into this config\'s image. Save the config first, then come back to this step.',
setupProgress: 'Sandbox setup progress',
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
connectAndContinue: 'Connect and continue',
@ -5096,6 +5099,51 @@ export default {
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
manageSkills: 'Manage skills',
skillInstallerModel: 'Installer model',
skillInstallerModelHint: 'Used by the built-in installer agent. Choose a chat model that supports tool calls.',
skillInstallerModelRequired: 'Select an installer model first',
skillInstallerModelSaveFailed: 'Failed to save the installer model',
skillRollout: '새 스킬 이미지가 적용되는 방식',
skillRolloutHint: '스킬을 설치하거나 삭제하면 새 이미지가 만들어집니다. 이미 열린 세션을 새 이미지로 바꿀지 여기서 정합니다.',
skillRolloutNextTurn: '이미 열린 세션은 다음 대화 턴에서 샌드박스를 다시 만듭니다',
skillRolloutNewSession: '이미 열린 세션은 기존 샌드박스를 유지하고, 새 세션만 새 이미지를 사용합니다',
skillRolloutSaveFailed: '적용 방식 저장에 실패했습니다',
skillUploadClick: 'Click to upload a skill bundle',
skillUploadDrag: 'or drop a .zip file here',
skillUploadHint: '업로드하면 현재 이미지에 스킬을 설치하고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillUploadHintNewSession: '업로드하면 현재 이미지에 스킬을 설치하고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
skillUploadFailed: 'Failed to upload the skill',
skillUploading: 'Uploading {percent}%',
skillUploadAccepted: 'Skill install started',
skillStatusInstalling: 'Installing',
skillStatusReady: 'Ready',
skillStatusFailed: 'Failed',
skillStatusRemoving: 'Removing',
skillStatusLabel: 'Status',
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: '삭제하면 이미지에서 스킬 디렉터리를 제거하고 새 스냅샷을 만듭니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
skillDeleteHintNewSession: '삭제하면 이미지에서 스킬 디렉터리를 제거하고 새 스냅샷을 만듭니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이 스킬은 새로 시작한 세션에서만 빠집니다.',
imageInfoTitle: 'Current image',
imageInfoSnapshot: 'Snapshot ID',
imageInfoGeneration: 'Version',
imageInfoBuiltAt: 'Built at',
imageInfoBaseTemplate: 'Base template',
imageInfoEmpty: 'Using the base template',
skillView: 'View',
skillTranscript: 'View install run',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
skillLoadFailed: 'Failed to load skills',
skillToggleFailed: 'Failed to update the skill',
skillDeleteAccepted: 'Skill removal started',
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
skillVersion: 'Version',
skillVersionEmpty: 'Not specified',
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
},
mcpService: 'MCP 서비스',
versionInfo: '버전 정보',

View File

@ -4903,11 +4903,14 @@ export default {
stepConnection: 'Connect',
stepTemplate: 'Template',
stepRuntime: 'Runtime',
stepSkills: 'Skills',
stepSkillsLocked: 'Skills are installed into this config\'s image. Save the config first, then come back to this step.',
setupProgress: 'Sandbox setup progress',
stepDescriptions: {
connection: 'Configure the backend and verify the connection before loading templates.',
template: 'Choose a ready template returned by the connected cluster.',
runtime: 'Configure execution settings and environment variables, then save.',
skills: 'Install skills into this config\'s sandbox image. Once the config is saved you can come back any time.',
},
back: 'Back',
connectAndContinue: 'Connect and continue',
@ -5096,6 +5099,51 @@ export default {
sandbox_exec: 'In-sandbox execution',
egress_available: 'Outbound network',
},
manageSkills: 'Manage skills',
skillInstallerModel: 'Installer model',
skillInstallerModelHint: 'Used by the built-in installer agent. Choose a chat model that supports tool calls.',
skillInstallerModelRequired: 'Select an installer model first',
skillInstallerModelSaveFailed: 'Failed to save the installer model',
skillRollout: 'Как вступает в силу новый образ навыка',
skillRolloutHint: 'Установка или удаление навыка собирает новый образ. Здесь задаётся, переключать ли на него уже открытые сессии.',
skillRolloutNextTurn: 'Пересоздать песочницу открытых сессий на следующем ходе диалога',
skillRolloutNewSession: 'Оставить открытые сессии на текущей песочнице; новый образ только у новых сессий',
skillRolloutSaveFailed: 'Не удалось сохранить способ применения',
skillUploadClick: 'Click to upload a skill bundle',
skillUploadDrag: 'or drop a .zip file here',
skillUploadHint: 'Загрузка устанавливает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillUploadHintNewSession: 'Загрузка устанавливает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
skillUploadFailed: 'Failed to upload the skill',
skillUploading: 'Uploading {percent}%',
skillUploadAccepted: 'Skill install started',
skillStatusInstalling: 'Installing',
skillStatusReady: 'Ready',
skillStatusFailed: 'Failed',
skillStatusRemoving: 'Removing',
skillStatusLabel: 'Status',
skillDisableHint: 'Disable = the skill is invisible to the agent, files stay in the image. Changes take effect on the session\'s next execution.',
skillDeleteHint: 'Удаление убирает каталог навыка из образа и создаёт новый снимок. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
skillDeleteHintNewSession: 'Удаление убирает каталог навыка из образа и создаёт новый снимок. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык исчезнет только у новых сессий.',
imageInfoTitle: 'Current image',
imageInfoSnapshot: 'Snapshot ID',
imageInfoGeneration: 'Version',
imageInfoBuiltAt: 'Built at',
imageInfoBaseTemplate: 'Base template',
imageInfoEmpty: 'Using the base template',
skillView: 'View',
skillTranscript: 'View install run',
skillTranscriptHide: 'Hide install run',
skillTranscriptEmpty: 'This install left no transcript.',
skillTranscriptWaiting: 'Install has started. Waiting for the process log…',
skillLoadFailed: 'Failed to load skills',
skillToggleFailed: 'Failed to update the skill',
skillDeleteAccepted: 'Skill removal started',
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
skillVersion: 'Version',
skillVersionEmpty: 'Not specified',
skillError: 'Error',
skillEnabled: 'Skill enabled',
skillDisabled: 'Skill disabled',
},
mcpService: 'Сервис MCP',
versionInfo: 'Информация о версии',

View File

@ -4905,11 +4905,14 @@ export default {
stepConnection: '连接',
stepTemplate: '模板',
stepRuntime: '运行配置',
stepSkills: '技能',
stepSkillsLocked: '技能需要装进这份配置的镜像,先保存配置再回到这一步。',
setupProgress: '沙箱配置进度',
stepDescriptions: {
connection: '先配置后端并验证连接,通过后再从集群加载模板。',
template: '选择当前集群返回且已经就绪的运行模板。',
runtime: '配置执行参数和环境变量,然后保存。',
skills: '把技能装进这份配置的沙箱镜像;配置已保存后可随时回来增删。',
},
back: '上一步',
connectAndContinue: '连接并继续',
@ -5098,6 +5101,51 @@ export default {
sandbox_exec: '沙箱内执行',
egress_available: '出网可用',
},
manageSkills: '管理技能',
skillInstallerModel: '安装模型',
skillInstallerModelHint: '安装技能时由内置安装智能体调用。请选择支持工具调用的对话模型。',
skillInstallerModelRequired: '请先选择安装模型',
skillInstallerModelSaveFailed: '保存安装模型失败',
skillRollout: '技能镜像如何生效',
skillRolloutHint: '安装或删除技能会生成新镜像。这里决定已经打开的会话要不要换到新镜像。',
skillRolloutNextTurn: '已有会话在下一轮提问时重建沙盒',
skillRolloutNewSession: '已有会话保持原沙盒,仅新会话使用新镜像',
skillRolloutSaveFailed: '保存生效方式失败',
skillUploadClick: '点击上传技能压缩包',
skillUploadDrag: '或将 .zip 拖到此处',
skillUploadHint: '上传后会在当前镜像上安装该技能并生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙盒,会话工作区草稿会在那时清空。',
skillUploadHintNewSession: '上传后会在当前镜像上安装该技能并生成新快照,可能需要数分钟。已打开的会话继续使用原沙盒,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
skillUploadFailed: '技能上传失败',
skillUploading: '正在上传 {percent}%',
skillUploadAccepted: '已开始安装技能',
skillStatusInstalling: '安装中',
skillStatusReady: '已就绪',
skillStatusFailed: '安装失败',
skillStatusRemoving: '删除中',
skillStatusLabel: '状态',
skillDisableHint: '禁用后该技能对智能体不可见,文件仍保留在镜像中。变更将在会话下一次执行时生效。',
skillDeleteHint: '删除会从镜像中移除该技能目录并生成新快照。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙盒,会话工作区草稿会在那时清空。',
skillDeleteHintNewSession: '删除会从镜像中移除该技能目录并生成新快照。已打开的会话继续使用原沙盒,直到该会话结束;只有新打开的会话才会去掉该技能。',
imageInfoTitle: '当前镜像',
imageInfoSnapshot: '快照 ID',
imageInfoGeneration: '版本',
imageInfoBuiltAt: '构建时间',
imageInfoBaseTemplate: '基础模板',
imageInfoEmpty: '使用基础模板',
skillView: '查看',
skillTranscript: '查看安装过程',
skillTranscriptHide: '收起安装过程',
skillTranscriptEmpty: '这次安装没有留下记录。',
skillTranscriptWaiting: '安装已开始,正在等待过程记录…',
skillLoadFailed: '加载技能列表失败',
skillToggleFailed: '更新技能状态失败',
skillDeleteAccepted: '已开始删除技能',
skillEmpty: '尚未安装技能。上传压缩包即可安装。',
skillVersion: '版本',
skillVersionEmpty: '未填写',
skillError: '错误',
skillEnabled: '已启用技能',
skillDisabled: '已禁用技能',
},
mcpService: 'MCP服务',
versionInfo: '版本信息',

View File

@ -56,7 +56,8 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
const storageAllowedProviders = ref<string[]>([])
const mcpServices = ref<MCPService[]>([])
const skills = ref<SkillInfo[]>([])
const skillsAvailable = ref(true)
const skillsAvailable = ref(false)
const skillsConfigId = ref('')
const agentTypePresets = ref<AgentTypePreset[]>([])
const promptTemplates = ref<PromptTemplatesConfig | null>(null)
const placeholders = ref<PlaceholdersResponse | null>(null)
@ -110,10 +111,21 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
})
}
async function ensureSkills(force = false): Promise<void> {
async function ensureSkills(sandboxConfigId?: string, force = false): Promise<void> {
const configId = sandboxConfigId?.trim() || ''
if (configId !== skillsConfigId.value) {
force = true
}
return runOnce('skills', force, async () => {
skillsConfigId.value = configId
if (!configId) {
skillsAvailable.value = false
skills.value = []
loadedAt.value.skills = Date.now()
return
}
try {
const skillsRes = await listSkills()
const skillsRes = await listSkills(configId)
skillsAvailable.value = skillsRes.skills_available !== false
skills.value = skillsRes.data && skillsRes.data.length > 0 ? skillsRes.data : []
} catch {
@ -176,7 +188,6 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
async function prefetchAgentEditorDeps(force = false): Promise<void> {
await Promise.all([
ensureMcpServices(force),
ensureSkills(force),
ensureAgentTypePresets(force),
ensurePromptTemplates(force),
ensureStorageEngine(force),
@ -193,6 +204,8 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
storageAllowedProviders.value = []
mcpServices.value = []
skills.value = []
skillsAvailable.value = false
skillsConfigId.value = ''
agentTypePresets.value = []
promptTemplates.value = null
placeholders.value = null

View File

@ -291,6 +291,10 @@ export function put<T = any>(url: string, data = {}, config?: any): Promise<T> {
return instance.put<T>(url, data, config) as unknown as Promise<T>;
}
export function patch<T = any>(url: string, data = {}, config?: any): Promise<T> {
return instance.patch<T>(url, data, config) as unknown as Promise<T>;
}
export function del<T = any>(url: string, data?: any): Promise<T> {
return instance.delete<T>(url, { data }) as unknown as Promise<T>;
}

View File

@ -1942,8 +1942,15 @@ const showMcpServiceSelect = computed(() =>
);
const webSearchProviderList = ref<WebSearchProviderEntity[]>([]);
const skillOptions = ref<{ name: string; description: string }[]>([]);
// 是否允许启用 Skills(取决于后端沙箱是否启用,disabled 时为 false;未请求前为 false 避免闪显)
// 是否允许启用 Skills(当前沙盒配置上有可执行技能时为 true;未选配置前为 false)
const skillsAvailable = ref(false);
async function syncInstalledSkills() {
const configId = formData.value.config.sandbox_config_id || ''
await editorResources.ensureSkills(configId)
skillsAvailable.value = editorResources.skillsAvailable
skillOptions.value = [...editorResources.skills]
}
// 空间内的具名沙箱后端配置。始终包含当前已选中的那份,即使它已被删除——
// 否则下拉会静默显示为“不启用沙箱”,看不出该智能体其实指着一份不存在的配置。
const sandboxConfigOptions = computed(() => {
@ -2315,11 +2322,7 @@ const navItems = computed(() => {
if (isAgentMode.value) {
items.push({ key: 'tools', icon: 'tools', label: t('agent.editor.toolsConfig') });
items.push({ key: 'mcp', icon: 'server', label: t('agentEditor.mcp.label') });
}
if (isAgentMode.value && skillsAvailable.value) {
items.push({ key: 'skills', icon: 'lightbulb', label: t('agent.editor.skillsConfig') });
// 沙箱是技能脚本的运行环境:先选跑哪些技能,再选跑在哪份后端上。
// 与 skills 同门控——部署级沙箱关闭时技能整体不可用,选后端也就无从谈起。
items.push({ key: 'sandbox', icon: 'cloud', label: t('agent.editor.sandboxConfig') });
}
// 发布(仅编辑模式)
@ -3139,6 +3142,8 @@ watch(() => props.visible, async (val) => {
applyDefaultModelsIfEmpty()
}
await syncInstalledSkills()
if (props.initialHighlightField) {
await applyInitialFieldHighlight(props.initialHighlightField);
}
@ -3249,6 +3254,11 @@ watch(mcpSelectionMode, (mode) => {
// selected 模式保持 mcp_services 不变
});
watch(() => formData.value.config.sandbox_config_id, async () => {
if (!props.visible) return
await syncInstalledSkills()
})
// 监听 Skills 选择模式变化
watch(skillsSelectionMode, (mode) => {
formData.value.config.skills_selection_mode = mode;
@ -3446,9 +3456,6 @@ const loadDependencies = async () => {
.map((shared: any) => mapKbToOption(shared.knowledge_base, true, shared.org_name));
kbOptions.value = [...myKbs, ...sharedKbs];
skillsAvailable.value = editorResources.skillsAvailable;
skillOptions.value = editorResources.skills;
agentTypePresets.value = editorResources.agentTypePresets as AgentTypePreset[];
applyPromptTemplateDefaults(editorResources.promptTemplates);

View File

@ -137,7 +137,7 @@
</t-loading>
<SandboxConfigEditorDrawer v-model:visible="showEditor" :record="editingRecord"
:preset-type="activeType === 'all' ? '' : activeType" @saved="load" />
:preset-type="activeType === 'all' ? '' : activeType" :initial-step="editorStep" @saved="load" />
<!--
Occupancy is a list of sessions and agents, not a one-line status, and it
@ -235,6 +235,9 @@ const activeType = ref<string>('all')
const showEditor = ref(false)
const editingRecord = ref<SandboxConfigRecord | null>(null)
// Which page of the editor to open on. Skills live there as the last step, so
// "管理技能" is the same drawer opened further along.
const editorStep = ref<'skills' | undefined>(undefined)
const showInventory = ref(false)
const inventoryLoading = ref(false)
@ -268,6 +271,7 @@ const cardMenu = (record: SandboxConfigRecord) => {
]
if (record.sandbox_type === 'cube' || record.sandbox_type === 'e2b') {
options.push({ content: t('settings.sandbox.viewSandboxes'), value: 'inventory' })
options.push({ content: t('settings.sandbox.manageSkills'), value: 'skills' })
}
return options
}
@ -311,12 +315,14 @@ async function onDeleteConfirmOpen(visible: boolean, record: SandboxConfigRecord
function openCreate() {
editingRecord.value = null
editorStep.value = undefined
showEditor.value = true
}
function openEdit(record: SandboxConfigRecord) {
if (isLegacyRecord(record)) return
editingRecord.value = record
editorStep.value = undefined
showEditor.value = true
}
@ -479,6 +485,12 @@ async function onMenuAction(action: string, record: SandboxConfigRecord) {
}
if (action === 'inventory') {
await openInventory(record)
return
}
if (action === 'skills') {
editingRecord.value = record
editorStep.value = 'skills'
showEditor.value = true
}
}

View File

@ -32,6 +32,12 @@ const sessionInputEnvVar = "WEKNORA_SESSION_INPUT_DIR"
// chain without LLM mediation.
const artifactHistoryEnvVar = "WEKNORA_SKILL_HISTORY_ROOT"
// skillDirEnvVar points a script at its own directory inside the sandbox
// image. Installed skills run with /workspace as WorkDir, so this is how a
// script reaches the data and helpers that were installed beside it. The
// install-time smoke run exports the same name.
const skillDirEnvVar = "WEKNORA_SKILL_DIR"
// defaultArtifactOutputDir is used when neither the environment variable
// (WEKNORA_SKILL_OUTPUT_DIR) nor the ExecuteConfig.Env has an override.
// /workspace/output sits inside the base sandbox image's writable tree and
@ -70,6 +76,11 @@ type Manager struct {
loader *Loader
sandboxMgr sandbox.Manager
// tenantSource holds the skills installed into this run's sandbox image.
// It is nil for every run whose workspace has none, which is why the
// preloaded path below is untouched by its existence.
tenantSource SkillSource
// Configuration
skillDirs []string
allowedSkills []string // Empty means all skills are allowed
@ -109,6 +120,81 @@ func (m *Manager) IsEnabled() bool {
return m.enabled
}
// WithTenantSource attaches the skills an administrator installed into the
// sandbox config this run booted from. It is part of construction - callers
// must invoke it before Initialize, i.e. before the engine can reach the
// manager - so it takes no lock.
func (m *Manager) WithTenantSource(source SkillSource) *Manager {
m.tenantSource = source
return m
}
// resolveSource decides which source owns one skill name. An installed skill
// shadows a preloaded one of the same name, because the sandbox boots the
// image the install produced and that is the copy a script would run.
func (m *Manager) resolveSource(skillName string) SkillSource {
if m.tenantSource != nil {
if _, err := m.tenantSource.GetSkillBasePath(skillName); err == nil {
return m.tenantSource
}
}
return m.loader
}
// discoverAllSkills merges the two sources into the set the model is told
// about.
func (m *Manager) discoverAllSkills() ([]*SkillMetadata, error) {
preloaded, err := m.loader.DiscoverSkills()
if err != nil {
return nil, err
}
return m.mergeWithTenantSkills(preloaded)
}
// mergeWithTenantSkills overlays the installed skills on a freshly discovered
// preloaded set.
func (m *Manager) mergeWithTenantSkills(preloaded []*SkillMetadata) ([]*SkillMetadata, error) {
if m.tenantSource == nil {
return preloaded, nil
}
tenant, err := m.tenantSource.DiscoverSkills()
if err != nil {
return nil, err
}
return mergeSkillMetadata(preloaded, tenant), nil
}
// mergeSkillMetadata overlays the installed skills on the preloaded ones,
// keeping the preloaded ordering for the names both sources carry so the
// system prompt does not reshuffle when a skill is installed.
func mergeSkillMetadata(preloaded, tenant []*SkillMetadata) []*SkillMetadata {
byName := make(map[string]*SkillMetadata, len(tenant))
for _, meta := range tenant {
if meta != nil {
byName[meta.Name] = meta
}
}
merged := make([]*SkillMetadata, 0, len(preloaded)+len(tenant))
overridden := make(map[string]bool, len(tenant))
for _, meta := range preloaded {
if meta == nil {
continue
}
if installed, ok := byName[meta.Name]; ok {
merged = append(merged, installed)
overridden[meta.Name] = true
continue
}
merged = append(merged, meta)
}
for _, meta := range tenant {
if meta != nil && !overridden[meta.Name] {
merged = append(merged, meta)
}
}
return merged
}
// Initialize discovers all skills and caches their metadata
// This should be called at startup
func (m *Manager) Initialize(ctx context.Context) error {
@ -116,7 +202,7 @@ func (m *Manager) Initialize(ctx context.Context) error {
return nil
}
metadata, err := m.loader.DiscoverSkills()
metadata, err := m.discoverAllSkills()
if err != nil {
return fmt.Errorf("failed to discover skills: %w", err)
}
@ -180,7 +266,7 @@ func (m *Manager) LoadSkill(ctx context.Context, skillName string) (*Skill, erro
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
return m.loader.LoadSkillInstructions(skillName)
return m.resolveSource(skillName).LoadSkillInstructions(skillName)
}
// isSkillAllowed checks if a skill is in the allowed list
@ -206,7 +292,7 @@ func (m *Manager) ReadSkillFile(ctx context.Context, skillName, filePath string)
return "", fmt.Errorf("skill not allowed: %s", skillName)
}
file, err := m.loader.LoadSkillFile(skillName, filePath)
file, err := m.resolveSource(skillName).LoadSkillFile(skillName, filePath)
if err != nil {
return "", err
}
@ -224,7 +310,7 @@ func (m *Manager) ListSkillFiles(ctx context.Context, skillName string) ([]strin
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
return m.loader.ListSkillFiles(skillName)
return m.resolveSource(skillName).ListSkillFiles(skillName)
}
// ExecuteScript executes a script from a skill in the sandbox
@ -242,22 +328,14 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
return nil, fmt.Errorf("sandbox is not configured")
}
source := m.resolveSource(skillName)
// Get the skill base path
basePath, err := m.loader.GetSkillBasePath(skillName)
basePath, err := source.GetSkillBasePath(skillName)
if err != nil {
return nil, err
}
// Load the script file to verify it exists and is a script
file, err := m.loader.LoadSkillFile(skillName, scriptPath)
if err != nil {
return nil, fmt.Errorf("failed to load script: %w", err)
}
if !file.IsScript {
return nil, fmt.Errorf("file is not an executable script: %s", scriptPath)
}
// Prepare execution config
logger.Info(ctx, "[Tool][ExecuteScript]:Prepare execution config")
sessionID, _ := types.SessionIDFromContext(ctx)
@ -287,19 +365,76 @@ func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath strin
}
}
config := &sandbox.ExecuteConfig{
Script: file.Path,
Args: args,
WorkDir: basePath,
Stdin: stdin,
Env: env,
SessionID: sessionID,
config, err := buildSkillExecuteConfig(
source, skillName, scriptPath, basePath, args, stdin, env, sessionID,
)
if err != nil {
return nil, err
}
// Execute in sandbox
return m.sandboxMgr.Execute(ctx, config)
}
// buildSkillExecuteConfig turns one skill script into an execution request.
//
// The two sources diverge here and nowhere else. A skill installed into the
// image is run in place: there is no host-side copy to upload, and the
// executor pins WorkDir to the session workspace and runs it as the ordinary
// sandbox user. A preloaded skill keeps its existing behaviour exactly -
// uploaded from the host, executed with the skill directory as WorkDir.
func buildSkillExecuteConfig(
source SkillSource,
skillName, scriptPath, basePath string,
args []string,
stdin string,
env map[string]string,
sessionID string,
) (*sandbox.ExecuteConfig, error) {
image, installed := source.(imageSkillSource)
if !installed {
// Load the script file to verify it exists and is a script
file, err := source.LoadSkillFile(skillName, scriptPath)
if err != nil {
return nil, fmt.Errorf("failed to load script: %w", err)
}
if !file.IsScript {
return nil, fmt.Errorf("file is not an executable script: %s", scriptPath)
}
return &sandbox.ExecuteConfig{
Script: file.Path,
Args: args,
WorkDir: basePath,
Stdin: stdin,
Env: env,
SessionID: sessionID,
}, nil
}
// The archive is deliberately not consulted: the image is what executes,
// and a skill whose archive failed to store is still installed and
// runnable. That leaves the extension as the only check available here,
// which is also the one the executor's interpreter choice depends on.
if !IsScript(scriptPath) {
return nil, fmt.Errorf("file is not an executable script: %s", scriptPath)
}
remoteScript, err := image.RemoteScriptPath(skillName, scriptPath)
if err != nil {
return nil, err
}
// The install-time smoke run exports the skill directory under this name,
// so a script that located its own resources through it during
// verification must be able to do the same when the agent calls it.
env[skillDirEnvVar] = basePath
return &sandbox.ExecuteConfig{
RemoteScriptPath: remoteScript,
Args: args,
Stdin: stdin,
Env: env,
SessionID: sessionID,
}, nil
}
// sessionFileStoreFromManager returns the sandbox manager's effective
// session filesystem capability, or nil when the backend cannot expose one.
// Isolated in a helper so callers stay free of provider-specific branches.
@ -321,12 +456,13 @@ func (m *Manager) GetSkillInfo(ctx context.Context, skillName string) (*SkillInf
return nil, fmt.Errorf("skill not allowed: %s", skillName)
}
skill, err := m.loader.LoadSkillInstructions(skillName)
source := m.resolveSource(skillName)
skill, err := source.LoadSkillInstructions(skillName)
if err != nil {
return nil, err
}
files, err := m.loader.ListSkillFiles(skillName)
files, err := source.ListSkillFiles(skillName)
if err != nil {
files = []string{} // Non-fatal error
}
@ -355,7 +491,11 @@ func (m *Manager) Reload(ctx context.Context) error {
return nil
}
metadata, err := m.loader.Reload()
preloaded, err := m.loader.Reload()
if err != nil {
return err
}
metadata, err := m.mergeWithTenantSkills(preloaded)
if err != nil {
return err
}

View File

@ -0,0 +1,32 @@
package skills
// SkillSource is where one set of skills comes from. Two implementations
// exist: the deployment's preloaded skill directories (*Loader) and the
// projection of the skills an administrator installed into a workspace sandbox
// config's snapshot image (*TenantSkillSource).
//
// The five methods are the Progressive Disclosure levels the agent asks for:
// metadata for the system prompt, the SKILL.md body, individual resource
// files, the file listing, and the directory a script runs from.
type SkillSource interface {
DiscoverSkills() ([]*SkillMetadata, error)
LoadSkillInstructions(name string) (*Skill, error)
LoadSkillFile(name, relativePath string) (*SkillFile, error)
ListSkillFiles(name string) ([]string, error)
GetSkillBasePath(name string) (string, error)
}
var _ SkillSource = (*Loader)(nil)
// imageSkillSource is a source whose skills already exist inside the sandbox
// image. It is what separates the two sources at execution time: a preloaded
// skill lives on the WeKnora host and has to be uploaded into the sandbox,
// while an installed skill is already there and is executed in place.
type imageSkillSource interface {
SkillSource
// RemoteScriptPath returns the absolute in-sandbox path of one script.
RemoteScriptPath(name, relativePath string) (string, error)
}
var _ imageSkillSource = (*TenantSkillSource)(nil)

View File

@ -0,0 +1,388 @@
package skills
import (
"archive/zip"
"bytes"
"fmt"
"io"
"os"
"path"
"sort"
"strings"
"sync"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// Bundle limits bound decompression. They mirror the install-time limits: the
// archive read here is the same one that was accepted then, and a corrupted or
// hostile object in storage must not be able to exhaust this process.
const (
maxBundleEntries = 2000
maxBundleEntryBytes = 32 << 20 // 32 MiB per entry
maxBundleBytes = 256 << 20 // 256 MiB across the archive
)
// cachedBundleCount bounds the unpacked archives one source keeps. A source
// lives for a single agent run, and within that run read_skill is typically
// called several times against the same skill, so a handful of entries removes
// the repeated download without holding archives past the turn.
const cachedBundleCount = 4
// TenantSkillSource exposes the skills an administrator installed into one
// sandbox config's snapshot image.
//
// The three disclosure levels come from different places on purpose: name,
// description and the SKILL.md body are columns on the row, so the request
// path never waits on object storage to tell the model what a skill is, while
// individual resource files come from the uploaded archive. Execution uses
// neither - the files are already in the image.
type TenantSkillSource struct {
byName map[string]*types.TenantSkillEntity
// order preserves the repository's ordering so the system prompt is stable
// between turns.
order []string
// loadBundle fetches an uploaded archive by its stored reference. It may
// be nil when the deployment cannot serve bundles, in which case only the
// levels backed by the row are available.
loadBundle func(ref string) ([]byte, error)
mu sync.Mutex
// cache holds unpacked archives, most recently used first, keyed by
// bundle_sha256: the archive is immutable under that key, so a hit can
// never serve a stale tree.
cache []cachedBundle
}
type cachedBundle struct {
key string
files map[string][]byte
}
// NewTenantSkillSource builds a source over the rows of one sandbox config.
// Callers pass every row; the source itself decides which are usable.
func NewTenantSkillSource(
rows []*types.TenantSkillEntity, loadBundle func(ref string) ([]byte, error),
) *TenantSkillSource {
src := &TenantSkillSource{
byName: make(map[string]*types.TenantSkillEntity, len(rows)),
loadBundle: loadBundle,
}
for _, row := range rows {
if !usableSkillRow(row) {
continue
}
if _, exists := src.byName[row.Name]; exists {
continue
}
src.byName[row.Name] = row
src.order = append(src.order, row.Name)
}
return src
}
// usableSkillRow is the one place "the agent can actually run this" is decided
// for a single row. A row that is still installing, failed, or was disabled by
// an administrator is invisible: telling the model about a skill it cannot
// invoke costs it turns and gains nothing.
//
// The name guard is not defensive: every path this source hands out is
// SkillDirFor(row.Name), which joins the name under the skills root. A name
// that is not a single path segment yields a path outside the skill, or outside
// the root entirely, and those paths reach the model in discovery metadata and
// in SkillFile.Path even though execution would refuse them. Filtering the row
// out here is what keeps them from ever being spoken. sandbox.IsValidSkillName
// is the same rule SkillDirFor enforces, so this cannot disagree with it.
func usableSkillRow(row *types.TenantSkillEntity) bool {
return row != nil &&
row.Enabled &&
row.Status == types.SkillStatusReady &&
sandbox.IsValidSkillName(row.Name)
}
// DiscoverSkills returns Level 1 metadata for every usable skill.
func (s *TenantSkillSource) DiscoverSkills() ([]*SkillMetadata, error) {
metadata := make([]*SkillMetadata, 0, len(s.order))
for _, name := range s.order {
row := s.byName[name]
basePath, err := sandbox.SkillDirFor(row.Name)
if err != nil {
return nil, err
}
metadata = append(metadata, &SkillMetadata{
Name: row.Name,
Description: row.Description,
BasePath: basePath,
})
}
return metadata, nil
}
// LoadSkillInstructions returns Level 2 from the row.
func (s *TenantSkillSource) LoadSkillInstructions(name string) (*Skill, error) {
row, err := s.row(name)
if err != nil {
return nil, err
}
basePath, err := sandbox.SkillDirFor(row.Name)
if err != nil {
return nil, err
}
return &Skill{
Name: row.Name,
Description: row.Description,
BasePath: basePath,
FilePath: path.Join(basePath, SkillFileName),
Instructions: row.Instructions,
Loaded: true,
}, nil
}
// LoadSkillFile returns one Level 3 resource out of the uploaded archive.
//
// The archive is read rather than the image: reading a file out of the image
// would need a sandbox, and read_skill must work whether or not this turn has
// already booted one.
func (s *TenantSkillSource) LoadSkillFile(name, relativePath string) (*SkillFile, error) {
row, err := s.row(name)
if err != nil {
return nil, err
}
clean, err := safeSkillRelPath(relativePath)
if err != nil {
return nil, err
}
files, err := s.bundleFiles(row)
if err != nil {
return nil, err
}
content, ok := files[clean]
if !ok {
return nil, fmt.Errorf("file not found in skill %s: %s", name, relativePath)
}
basePath, err := sandbox.SkillDirFor(row.Name)
if err != nil {
return nil, err
}
return &SkillFile{
Name: relativePath,
// The path the model sees is the in-image one, because that is where
// it can act on the file.
Path: path.Join(basePath, clean),
Content: string(content),
IsScript: IsScript(clean),
}, nil
}
// ListSkillFiles lists the archive contents of one skill, sorted so repeated
// calls within a turn do not look like different answers.
func (s *TenantSkillSource) ListSkillFiles(name string) ([]string, error) {
row, err := s.row(name)
if err != nil {
return nil, err
}
files, err := s.bundleFiles(row)
if err != nil {
return nil, err
}
names := make([]string, 0, len(files))
for rel := range files {
names = append(names, rel)
}
sort.Strings(names)
return names, nil
}
// GetSkillBasePath returns the skill's directory inside the image.
func (s *TenantSkillSource) GetSkillBasePath(name string) (string, error) {
row, err := s.row(name)
if err != nil {
return "", err
}
return sandbox.SkillDirFor(row.Name)
}
// RemoteScriptPath returns the absolute in-image path of one script. It is
// keyed on the skill name, which is also the directory the installer wrote.
//
// It deliberately does not consult the archive. The image is what executes,
// and a skill whose archive failed to store - the install logs a warning and
// carries on - is still installed and runnable.
func (s *TenantSkillSource) RemoteScriptPath(name, relativePath string) (string, error) {
row, err := s.row(name)
if err != nil {
return "", err
}
clean, err := safeSkillRelPath(relativePath)
if err != nil {
return "", err
}
basePath, err := sandbox.SkillDirFor(row.Name)
if err != nil {
return "", err
}
return path.Join(basePath, clean), nil
}
func (s *TenantSkillSource) row(name string) (*types.TenantSkillEntity, error) {
if row, ok := s.byName[name]; ok {
return row, nil
}
return nil, fmt.Errorf("skill not found: %s", name)
}
// safeSkillRelPath normalises a caller-supplied relative path and refuses
// anything that leaves the skill directory.
func safeSkillRelPath(relativePath string) (string, error) {
trimmed := strings.TrimSpace(relativePath)
if trimmed == "" {
return "", fmt.Errorf("skill file path is required")
}
if path.IsAbs(trimmed) {
return "", fmt.Errorf("invalid skill file path: %s", relativePath)
}
clean := path.Clean(trimmed)
if clean == "." || clean == ".." || strings.HasPrefix(clean, "../") {
return "", fmt.Errorf("invalid skill file path: %s", relativePath)
}
return clean, nil
}
// bundleFiles returns the unpacked archive of one skill, downloading it at
// most once per cache lifetime.
func (s *TenantSkillSource) bundleFiles(
row *types.TenantSkillEntity,
) (map[string][]byte, error) {
ref := strings.TrimSpace(row.BundleRef)
if ref == "" {
return nil, fmt.Errorf(
"skill %s has no stored bundle; its files cannot be read", row.Name)
}
if s.loadBundle == nil {
return nil, fmt.Errorf("skill bundles are not available in this deployment")
}
key := strings.TrimSpace(row.BundleSHA256)
if key == "" {
// Without a checksum the reference is the only stable key we have.
key = ref
}
if files := s.cached(key); files != nil {
return files, nil
}
archive, err := s.loadBundle(ref)
if err != nil {
return nil, fmt.Errorf("download bundle of skill %s: %w", row.Name, err)
}
files, err := unpackSkillBundle(archive)
if err != nil {
return nil, fmt.Errorf("read bundle of skill %s: %w", row.Name, err)
}
s.store(key, files)
return files, nil
}
func (s *TenantSkillSource) cached(key string) map[string][]byte {
s.mu.Lock()
defer s.mu.Unlock()
for i, entry := range s.cache {
if entry.key != key {
continue
}
s.cache = append(s.cache[:i], s.cache[i+1:]...)
s.cache = append([]cachedBundle{entry}, s.cache...)
return entry.files
}
return nil
}
func (s *TenantSkillSource) store(key string, files map[string][]byte) {
s.mu.Lock()
defer s.mu.Unlock()
s.cache = append([]cachedBundle{{key: key, files: files}}, s.cache...)
if len(s.cache) > cachedBundleCount {
s.cache = s.cache[:cachedBundleCount]
}
}
// unpackSkillBundle reads a skill archive into skill-root-relative paths. It
// re-roots the archive at the directory holding SKILL.md, because an archive
// wrapped in a single top-level directory is accepted at upload time and the
// relative paths the model is given must match either shape.
func unpackSkillBundle(archive []byte) (map[string][]byte, error) {
reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))
if err != nil {
return nil, fmt.Errorf("not a readable zip archive: %w", err)
}
if len(reader.File) > maxBundleEntries {
return nil, fmt.Errorf("archive holds more than %d files", maxBundleEntries)
}
raw := make(map[string][]byte, len(reader.File))
var total int64
for _, entry := range reader.File {
info := entry.FileInfo()
if info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
continue
}
name := path.Clean(entry.Name)
if name == "." || path.IsAbs(name) ||
name == ".." || strings.HasPrefix(name, "../") {
return nil, fmt.Errorf("entry %q escapes the archive root", entry.Name)
}
rc, err := entry.Open()
if err != nil {
return nil, fmt.Errorf("cannot read %q: %w", entry.Name, err)
}
content, err := io.ReadAll(io.LimitReader(rc, maxBundleEntryBytes+1))
_ = rc.Close()
if err != nil {
return nil, fmt.Errorf("cannot read %q: %w", entry.Name, err)
}
if len(content) > maxBundleEntryBytes {
return nil, fmt.Errorf("entry %q is too large", entry.Name)
}
total += int64(len(content))
if total > maxBundleBytes {
return nil, fmt.Errorf("archive is too large")
}
raw[name] = content
}
return reRootSkillBundle(raw)
}
// reRootSkillBundle strips a single wrapping directory when SKILL.md is not at
// the archive root.
func reRootSkillBundle(raw map[string][]byte) (map[string][]byte, error) {
if _, ok := raw[SkillFileName]; ok {
return raw, nil
}
prefix := ""
for name := range raw {
if path.Base(name) != SkillFileName {
continue
}
dir := path.Dir(name)
if dir == "." || strings.Contains(dir, "/") {
continue
}
if prefix != "" && prefix != dir {
return nil, fmt.Errorf("archive holds more than one skill")
}
prefix = dir
}
if prefix == "" {
return nil, fmt.Errorf("%s is missing from the archive", SkillFileName)
}
out := make(map[string][]byte, len(raw))
for name, content := range raw {
if !strings.HasPrefix(name, prefix+"/") {
continue
}
out[strings.TrimPrefix(name, prefix+"/")] = content
}
return out, nil
}

View File

@ -0,0 +1,308 @@
package skills
import (
"archive/zip"
"bytes"
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestTenantSkillSourceOnlyExposesUsableSkills(t *testing.T) {
rows := []*types.TenantSkillEntity{
{ID: "sk-1", Name: "ready-enabled", Status: types.SkillStatusReady, Enabled: true},
{ID: "sk-2", Name: "ready-disabled", Status: types.SkillStatusReady, Enabled: false},
{ID: "sk-3", Name: "still-installing", Status: types.SkillStatusInstalling, Enabled: true},
{ID: "sk-4", Name: "failed", Status: types.SkillStatusFailed, Enabled: true},
}
src := NewTenantSkillSource(rows, nil)
metadata, err := src.DiscoverSkills()
require.NoError(t, err)
require.Len(t, metadata, 1,
"a skill the agent cannot actually run must never reach the system prompt")
require.Equal(t, "ready-enabled", metadata[0].Name)
}
// The name is joined under the skills root to build every path this source
// hands out, so it has to be a single path segment. Execution rejects an
// escaping path anyway, but the base path travels to the model in metadata
// and in SkillFile.Path, which is the same reasoning guardSkillDir applies
// on the install side.
func TestTenantSkillSourceRejectsANameThatIsNotOnePathSegment(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{
{ID: "sk-2", Name: "../escaping", Status: types.SkillStatusReady, Enabled: true},
{ID: "sk-3", Name: "nested/name", Status: types.SkillStatusReady, Enabled: true},
{ID: "sk-4", Name: "..", Status: types.SkillStatusReady, Enabled: true},
}, nil)
metadata, err := src.DiscoverSkills()
require.NoError(t, err)
require.Empty(t, metadata)
for _, name := range []string{"../escaping", "nested/name", ".."} {
_, err := src.GetSkillBasePath(name)
require.Error(t, err, "%s must be invisible, not merely unexecutable", name)
}
}
func TestTenantSkillSourceBasePathIsTheImageDir(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{
{ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true},
}, nil)
base, err := src.GetSkillBasePath("pdf")
require.NoError(t, err)
require.Equal(t, "/opt/weknora/tenant/skills/pdf", base,
"the path is the skill name: that is the directory the installer writes")
}
// A skill the source does not expose must be unreachable through every entry
// point, not just discovery: routing decisions elsewhere ask these methods.
func TestTenantSkillSourceHidesUnusableSkillsFromEveryLookup(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{
{ID: "sk-2", Name: "ready-disabled", Status: types.SkillStatusReady, Enabled: false},
}, func(string) ([]byte, error) { return nil, errors.New("must not be called") })
_, err := src.GetSkillBasePath("ready-disabled")
require.Error(t, err)
_, err = src.LoadSkillInstructions("ready-disabled")
require.Error(t, err)
_, err = src.ListSkillFiles("ready-disabled")
require.Error(t, err)
_, err = src.LoadSkillFile("ready-disabled", "scripts/run.py")
require.Error(t, err)
_, err = src.RemoteScriptPath("ready-disabled", "scripts/run.py")
require.Error(t, err)
}
// Level 2 comes from the database projection: the request path must not depend
// on downloading an archive to answer "what does this skill say".
func TestTenantSkillSourceLoadsInstructionsFromTheRow(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Description: "PDF helpers",
Instructions: "Run scripts/extract.py.",
Status: types.SkillStatusReady, Enabled: true,
}}, func(string) ([]byte, error) { return nil, errors.New("must not be called") })
skill, err := src.LoadSkillInstructions("pdf")
require.NoError(t, err)
require.Equal(t, "pdf", skill.Name)
require.Equal(t, "PDF helpers", skill.Description)
require.Equal(t, "Run scripts/extract.py.", skill.Instructions)
require.True(t, skill.Loaded)
require.Equal(t, "/opt/weknora/tenant/skills/pdf", skill.BasePath)
require.Equal(t, "/opt/weknora/tenant/skills/pdf/SKILL.md", skill.FilePath)
}
func TestTenantSkillSourceReadsLevel3FilesFromTheBundle(t *testing.T) {
archive := zipArchive(t, map[string]string{
// Wrapped in a top-level directory, which is how people upload.
"pdf-tools/SKILL.md": "---\nname: pdf\ndescription: d\n---\nbody\n",
"pdf-tools/reference/FORMS.md": "form notes",
"pdf-tools/scripts/extract.py": "print('hi')\n",
})
src := NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
BundleRef: "local://sk-1.zip", BundleSHA256: "sha-1",
}}, func(ref string) ([]byte, error) {
require.Equal(t, "local://sk-1.zip", ref)
return archive, nil
})
files, err := src.ListSkillFiles("pdf")
require.NoError(t, err)
require.Equal(t, []string{"SKILL.md", "reference/FORMS.md", "scripts/extract.py"}, files)
file, err := src.LoadSkillFile("pdf", "reference/FORMS.md")
require.NoError(t, err)
require.Equal(t, "form notes", file.Content)
require.Equal(t, "/opt/weknora/tenant/skills/pdf/reference/FORMS.md", file.Path,
"the path the model is shown must be the one it can execute or read in the sandbox")
require.False(t, file.IsScript)
script, err := src.LoadSkillFile("pdf", "scripts/extract.py")
require.NoError(t, err)
require.True(t, script.IsScript)
}
func TestTenantSkillSourceDownloadsEachBundleOnce(t *testing.T) {
archive := zipArchive(t, map[string]string{
"SKILL.md": "---\nname: pdf\ndescription: d\n---\nbody\n",
"scripts/extract.py": "print('hi')\n",
})
downloads := 0
src := NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
BundleRef: "local://sk-1.zip", BundleSHA256: "sha-1",
}}, func(string) ([]byte, error) {
downloads++
return archive, nil
})
_, err := src.ListSkillFiles("pdf")
require.NoError(t, err)
_, err = src.LoadSkillFile("pdf", "scripts/extract.py")
require.NoError(t, err)
require.Equal(t, 1, downloads,
"one read_skill call per file would re-download the whole archive every time")
}
func TestTenantSkillSourceRefusesPathsOutsideTheSkill(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
BundleRef: "local://sk-1.zip",
}}, func(string) ([]byte, error) {
return nil, errors.New("must not be called")
})
for _, rel := range []string{"../other/secret", "/etc/passwd", ""} {
_, err := src.LoadSkillFile("pdf", rel)
require.Error(t, err, "rel=%q", rel)
_, err = src.RemoteScriptPath("pdf", rel)
require.Error(t, err, "rel=%q", rel)
}
}
// A skill whose archive could not be stored is still installed and runnable in
// the image, so execution must not depend on the bundle being downloadable.
func TestTenantSkillSourceReportsAMissingBundleWithoutBlockingExecution(t *testing.T) {
src := NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
}}, nil)
_, err := src.LoadSkillFile("pdf", "scripts/extract.py")
require.Error(t, err)
remote, err := src.RemoteScriptPath("pdf", "scripts/extract.py")
require.NoError(t, err)
require.Equal(t, "/opt/weknora/tenant/skills/pdf/scripts/extract.py", remote)
}
func TestManagerPrefersTheTenantSkillOverASameNamedPreloadedOne(t *testing.T) {
dir := preloadedSkillDir(t, "pdf", "preloaded description")
mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, nil)
mgr.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{
{
ID: "sk-1", Name: "pdf", Description: "tenant description",
Instructions: "tenant body", Status: types.SkillStatusReady, Enabled: true,
},
{
ID: "sk-2", Name: "csv", Description: "tenant only",
Status: types.SkillStatusReady, Enabled: true,
},
}, nil))
require.NoError(t, mgr.Initialize(context.Background()))
byName := map[string]*SkillMetadata{}
for _, meta := range mgr.GetAllMetadata() {
byName[meta.Name] = meta
}
require.Len(t, byName, 2)
require.Equal(t, "tenant description", byName["pdf"].Description,
"the tenant's own install is what the sandbox image actually carries")
require.Equal(t, "tenant only", byName["csv"].Description)
skill, err := mgr.LoadSkill(context.Background(), "pdf")
require.NoError(t, err)
require.Equal(t, "tenant body", skill.Instructions)
}
func TestManagerRunsATenantSkillFromTheImageWithoutUploading(t *testing.T) {
sandboxMgr := &recordingSandboxManager{}
mgr := NewManager(&ManagerConfig{SkillDirs: nil, Enabled: true}, sandboxMgr)
mgr.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
}}, nil))
require.NoError(t, mgr.Initialize(context.Background()))
_, err := mgr.ExecuteScript(
types.WithSessionID(context.Background(), "sess-1"),
"pdf", "scripts/extract.py", []string{"--flag"}, "",
)
require.NoError(t, err)
require.NotNil(t, sandboxMgr.config)
require.Equal(t, "/opt/weknora/tenant/skills/pdf/scripts/extract.py",
sandboxMgr.config.RemoteScriptPath)
require.Empty(t, sandboxMgr.config.Script,
"there is no host-side copy of an installed skill to upload")
require.Equal(t, []string{"--flag"}, sandboxMgr.config.Args)
require.Equal(t, "sess-1", sandboxMgr.config.SessionID)
require.Equal(t, sandbox.SkillsImageRoot+"/pdf",
sandboxMgr.config.Env["WEKNORA_SKILL_DIR"])
require.Equal(t, "/workspace/output", sandboxMgr.config.Env[artifactOutputEnvVar])
}
// Preloaded skills keep uploading from the host and keep running in their own
// directory; the tenant source must not change that path at all.
func TestManagerKeepsPreloadedSkillExecutionUnchanged(t *testing.T) {
dir := preloadedSkillDir(t, "pdf", "preloaded description")
sandboxMgr := &recordingSandboxManager{}
mgr := NewManager(&ManagerConfig{SkillDirs: []string{dir}, Enabled: true}, sandboxMgr)
mgr.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{{
ID: "sk-1", Name: "csv", Status: types.SkillStatusReady, Enabled: true,
}}, nil))
require.NoError(t, mgr.Initialize(context.Background()))
_, err := mgr.ExecuteScript(context.Background(), "pdf", "scripts/run.py", nil, "")
require.NoError(t, err)
require.NotNil(t, sandboxMgr.config)
require.Empty(t, sandboxMgr.config.RemoteScriptPath)
require.Equal(t, filepath.Join(dir, "pdf", "scripts", "run.py"), sandboxMgr.config.Script)
require.Equal(t, dir+"/pdf", sandboxMgr.config.WorkDir)
}
type recordingSandboxManager struct {
config *sandbox.ExecuteConfig
}
func (m *recordingSandboxManager) Execute(
_ context.Context, config *sandbox.ExecuteConfig,
) (*sandbox.ExecuteResult, error) {
m.config = config
return &sandbox.ExecuteResult{ExitCode: 0}, nil
}
func (m *recordingSandboxManager) Cleanup(context.Context) error { return nil }
func (m *recordingSandboxManager) GetSandbox() sandbox.Sandbox { return nil }
func (m *recordingSandboxManager) GetType() sandbox.SandboxType { return sandbox.SandboxTypeCube }
// preloadedSkillDir writes one deployment-preloaded skill to a temp directory
// and returns the search root it lives under.
func preloadedSkillDir(t *testing.T, name, description string) string {
t.Helper()
root := t.TempDir()
skillDir := filepath.Join(root, name)
require.NoError(t, os.MkdirAll(filepath.Join(skillDir, "scripts"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(skillDir, SkillFileName),
[]byte("---\nname: "+name+"\ndescription: "+description+"\n---\npreloaded body\n"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(skillDir, "scripts", "run.py"),
[]byte("print('preloaded')\n"), 0o644))
return root
}
func zipArchive(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
writer := zip.NewWriter(&buf)
for name, content := range files {
entry, err := writer.Create(name)
require.NoError(t, err)
_, err = entry.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, writer.Close())
return buf.Bytes()
}

View File

@ -163,6 +163,15 @@ func (r *sessionRepository) QueryPaged(
if q.UserID != "" {
db = db.Where("(s.user_id = ? OR s.user_id IS NULL OR s.user_id = '')", q.UserID)
}
// Skill image maintenance runs in a real session so its transcript can
// be read back, but it is not a conversation. Excluding it here rather
// than in applySource is deliberate: a source branch only covers its
// own bucket, and this row must be absent from all of them, including
// the unfiltered listing.
db = db.Where(
"(s.description IS NULL OR s.description NOT LIKE ?)",
types.SkillMaintenanceSessionMarker+"%",
)
if kw := strings.TrimSpace(q.Keyword); kw != "" {
db = db.Where(titleLikeExpr, "%"+escapeLikeKeyword(kw)+"%")
}

View File

@ -319,3 +319,29 @@ func TestSessionRepositoryQueryPagedAPISourceReturnsAllTenantAPIKeySessions(t *t
listItemIDsForTest(items),
)
}
// Maintenance sessions (skill install / remove) are real sessions with real
// transcripts, but they are infrastructure, not conversations. They must be
// invisible in every bucket — including the unfiltered listing, which is why
// the exclusion lives in applyBase and not in the "web" source branch.
func TestSessionRepositoryQueryPagedHidesMaintenanceSessions(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
web := createSessionForTest(t, db, 1, "alice")
maintenance := createSessionForTest(t, db, 1, "alice")
require.NoError(t, db.Model(&types.Session{}).Where("id = ?", maintenance.ID).
Update("description", types.SkillMaintenanceSessionMarker+"install").Error)
for _, source := range []string{"", "web"} {
items, total, err := repo.QueryPaged(ctx, &types.SessionListQuery{
TenantID: 1, UserID: "alice", Source: source, Page: 1, PageSize: 50,
})
require.NoError(t, err)
require.Equal(t, []string{web.ID}, listItemIDsForTest(items),
"source=%q must not list the maintenance session", source)
require.EqualValues(t, 1, total,
"source=%q count must not include the maintenance session", source)
}
}

View File

@ -19,6 +19,10 @@ type TenantSandboxConfigRepository interface {
Create(ctx context.Context, e *types.TenantSandboxConfigEntity) error
GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantSandboxConfigEntity, error)
// ListAll is the housekeeping scan. Unlike every other method it is not
// tenant-scoped: the stuck-run reaper and snapshot reconcile have to walk
// every workspace. Do not use it on a request path.
ListAll(ctx context.Context) ([]*types.TenantSandboxConfigEntity, error)
Update(ctx context.Context, e *types.TenantSandboxConfigEntity) error
SoftDelete(ctx context.Context, tenantID uint64, id string) error
SetCordon(ctx context.Context, tenantID uint64, id string, at time.Time) error
@ -72,6 +76,19 @@ func (r *tenantSandboxConfigRepository) ListByTenant(
return list, nil
}
func (r *tenantSandboxConfigRepository) ListAll(
ctx context.Context,
) ([]*types.TenantSandboxConfigEntity, error) {
var list []*types.TenantSandboxConfigEntity
err := r.db.WithContext(ctx).
Order("tenant_id ASC, created_at ASC").
Find(&list).Error
if err != nil {
return nil, err
}
return list, nil
}
// Update writes the mutable columns. Select is explicit so a zero-valued
// CordonedAt on the passed entity cannot silently release someone else's lease.
func (r *tenantSandboxConfigRepository) Update(

View File

@ -112,6 +112,8 @@ func (r *tenantSkillRepository) UpdateSkill(ctx context.Context, e *types.Tenant
"bundle_sha256": e.BundleSHA256,
"enabled": e.Enabled,
"installed_snapshot_id": e.InstalledSnapshotID,
"install_session_id": e.InstallSessionID,
"install_message_id": e.InstallMessageID,
"status": e.Status,
"error": e.Error,
"installing_since": e.InstallingSince,

View File

@ -61,6 +61,8 @@ func TestSkillRepoUpdatePersistsPointerAndStatus(t *testing.T) {
row.Status = types.SkillStatusReady
row.InstalledSnapshotID = "snap-1"
row.Enabled = false
row.InstallSessionID = "sess-1"
row.InstallMessageID = "msg-1"
require.NoError(t, repo.UpdateSkill(ctx, row))
got, err := repo.GetSkill(ctx, 7, "cfg-1", "sk-a")
@ -68,6 +70,10 @@ func TestSkillRepoUpdatePersistsPointerAndStatus(t *testing.T) {
require.Equal(t, types.SkillStatusReady, got.Status)
require.Equal(t, "snap-1", got.InstalledSnapshotID)
require.False(t, got.Enabled, "disabling a skill must round-trip; it is the visibility switch")
// The locators go through the same explicit column map as everything else,
// so a field added to the entity but not to that map reads back empty.
require.Equal(t, "sess-1", got.InstallSessionID)
require.Equal(t, "msg-1", got.InstallMessageID)
}
func TestSnapshotLedgerRecordsChain(t *testing.T) {

View File

@ -3,7 +3,9 @@ package service
import (
"context"
"database/sql"
"errors"
"fmt"
"io"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/approval"
@ -399,6 +401,9 @@ func (s *agentService) initializeSkillsManager(
}
skillsManager := skills.NewManager(skillsConfig, sandboxMgr)
if source := s.tenantSkillSource(ctx, config); source != nil {
skillsManager.WithTenantSource(source)
}
// Initialize (discover skills)
if err := skillsManager.Initialize(ctx); err != nil {
@ -448,6 +453,70 @@ func (s *agentService) initializeSkillsManager(
return skillsManager, nil
}
// tenantSkillSource builds the source for the skills installed into this run's
// sandbox image, or nil when the run has none. The set was already narrowed to
// what this run can invoke when the config was built; nothing here re-decides
// it.
func (s *agentService) tenantSkillSource(
ctx context.Context, config *types.AgentConfig,
) skills.SkillSource {
rows := config.TenantSkills
if len(rows) == 0 {
return nil
}
// The rows were fetched under the caller's workspace, so this is the
// caller's ID; it is read off the row rather than the context so the
// bundle download cannot resolve a different workspace's storage than the
// one the rows came from.
ownerTenantID := rows[0].TenantID
// The closure captures the engine-creation context because loadBundle
// takes no context of its own. That is the turn's context today -
// CreateAgentEngine and engine.Execute are called back to back with the
// same ctx - so it stays live for as long as read_skill can be called. If
// a caller ever creates the engine under a shorter-lived context, bundle
// downloads start failing for installed skills only, and loadBundle needs
// a ctx parameter.
return skills.NewTenantSkillSource(rows, func(ref string) ([]byte, error) {
return s.readSkillBundle(ctx, ownerTenantID, ref)
})
}
// readSkillBundle downloads one uploaded skill archive. It backs read_skill for
// installed skills: the image holds the executable copy, but reading a file out
// of it would need a live sandbox, and the archive is byte-identical to what
// was installed.
func (s *agentService) readSkillBundle(
ctx context.Context, tenantID uint64, ref string,
) ([]byte, error) {
if s.storageResolver == nil {
return nil, errors.New("storage resolver is not configured")
}
fs, _, err := s.storageResolver.ResolveFileService(
ctx, &types.Tenant{ID: tenantID}, "", "", "",
)
if err != nil {
return nil, err
}
if fs == nil {
return nil, errors.New("file service is not configured")
}
reader, err := fs.GetFile(ctx, ref)
if err != nil {
return nil, err
}
defer func() { _ = reader.Close() }()
// Bounded because the object is read into memory: the upload limit is the
// only thing that says how large a legitimate archive can be.
archive, err := io.ReadAll(io.LimitReader(reader, maxSkillBundleTotalBytes+1))
if err != nil {
return nil, err
}
if len(archive) > maxSkillBundleTotalBytes {
return nil, fmt.Errorf("skill bundle %s is larger than the upload limit", ref)
}
return archive, nil
}
// registerSandboxShellTool registers the one shell_exec variant this run is
// entitled to.
//

View File

@ -8,6 +8,7 @@ import (
"time"
"github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/sandbox"
@ -299,6 +300,56 @@ func TestSkillToolsFollowSkillsEnabled(t *testing.T) {
})
}
// Whether an installed skill is invocable is decided when the AgentConfig is
// built (effectiveTenantSkills). This is the other half of that contract: the
// manager the model is described from must carry exactly the rows it was
// handed, and nothing when it was handed none.
func TestSkillsManagerOffersTheInjectedInstalledSkills(t *testing.T) {
newSvc := func() *agentService {
return &agentService{
sandboxResolver: stubSandboxResolver{
mgr: &capableManager{typ: sandbox.SandboxTypeCube, shell: &stubShellExecutor{}},
},
}
}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
skillNamesOf := func(mgr *skills.Manager) []string {
var names []string
for _, meta := range mgr.GetAllMetadata() {
names = append(names, meta.Name)
}
return names
}
t.Run("injected rows are offered", func(t *testing.T) {
mgr, err := newSvc().initializeSkillsManager(ctx, "sess-1", &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: true,
SkillDirs: []string{t.TempDir()},
TenantSkills: []*types.TenantSkillEntity{{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-remote",
Name: "pdf-tools", Description: "PDF helpers",
Status: types.SkillStatusReady, Enabled: true,
}},
}, tools.NewToolRegistry())
require.NoError(t, err)
require.Equal(t, []string{"pdf-tools"}, skillNamesOf(mgr))
})
t.Run("an unusable image injects no rows and offers no skills", func(t *testing.T) {
mgr, err := newSvc().initializeSkillsManager(ctx, "sess-1", &types.AgentConfig{
SandboxConfigID: "cfg-remote",
SkillsEnabled: true,
SkillDirs: []string{t.TempDir()},
}, tools.NewToolRegistry())
require.NoError(t, err)
require.Empty(t, skillNamesOf(mgr),
"a skill the model is told about but cannot invoke burns turns for nothing")
})
}
func TestSkillInstallerIsHiddenFromThePicker(t *testing.T) {
require.NoError(t, types.LoadBuiltinAgentsConfig(filepath.Join("..", "..", "..", "config")))

View File

@ -15,6 +15,7 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
"github.com/Tencent/WeKnora/internal/application/repository"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
"github.com/Tencent/WeKnora/internal/sandbox"
)
@ -129,6 +130,11 @@ type sessionService struct {
sandboxPinner *SessionSandboxPinner
sandboxPolicy WorkspaceSandboxPolicy
memoryService interfaces.MemoryService // Service for cross-session long-term memory
// sandboxConfigRepo and tenantSkillRepo answer "which installed skills can
// this turn actually invoke". They are repositories rather than
// TenantSkillService because that service depends on this one.
sandboxConfigRepo repository.TenantSandboxConfigRepository
tenantSkillRepo repository.TenantSkillRepository
}
// NewSessionService creates a new session service instance with all required dependencies
@ -151,6 +157,8 @@ func NewSessionService(cfg *config.Config,
sandboxPinner *SessionSandboxPinner,
sandboxPolicy WorkspaceSandboxPolicy,
memoryService interfaces.MemoryService,
sandboxConfigRepo repository.TenantSandboxConfigRepository,
tenantSkillRepo repository.TenantSkillRepository,
) interfaces.SessionService {
return &sessionService{
cfg: cfg,
@ -172,6 +180,8 @@ func NewSessionService(cfg *config.Config,
sandboxPinner: sandboxPinner,
sandboxPolicy: sandboxPolicy,
memoryService: memoryService,
sandboxConfigRepo: sandboxConfigRepo,
tenantSkillRepo: tenantSkillRepo,
}
}
@ -410,11 +420,16 @@ func (s *sessionService) UpdateSession(ctx context.Context, session *types.Sessi
// Update session in repository
userID := sessionUserIDFromContext(ctx)
if _, err := s.sessionRepo.Get(ctx, session.TenantID, userID, session.ID); err != nil {
existing, err := s.sessionRepo.Get(ctx, session.TenantID, userID, session.ID)
if err != nil {
return err
}
if existing != nil {
session.Description = types.SanitizeClientSessionDescription(
session.Description, existing.Description)
}
_, err := s.sessionRepo.Update(ctx, session, userID)
_, err = s.sessionRepo.Update(ctx, session, userID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": session.ID,
@ -682,7 +697,10 @@ func (s *sessionService) destroyBoundSandbox(ctx context.Context, sessionID stri
// to the default manager keeps those reachable: DestroySession is a cheap
// binding lookup that no-ops when the session truly has no sandbox, whereas
// skipping would abandon a paused instance that keeps billing.
mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy)
//
// Pass nil policy so the workspace kill switch cannot strand an already
// created sandbox: disabling script execution must still allow teardown.
mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, nil)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for session %s cleanup: %v", sessionID, err)
return
@ -918,3 +936,59 @@ func (s *sessionService) GenerateTitleAsync(
}
}()
}
// holdSandboxTurn opens a chat-turn lease on the session's remote sandbox so
// a skill-image change mid-turn cannot rebuild the VM between tool calls.
// The first resolve of this turn may still pick up a stale mark from the
// previous turn. The returned closer must be called.
func (s *sessionService) holdSandboxTurn(
ctx context.Context, sessionID, configID string,
) func() {
if strings.TrimSpace(sessionID) == "" {
return func() {}
}
begin := func(mgr sandbox.Manager) sandbox.SessionTurnHolder {
if mgr == nil {
return nil
}
holder, ok := mgr.(sandbox.SessionTurnHolder)
if !ok {
return nil
}
if err := holder.BeginSessionTurn(ctx, sessionID); err != nil {
logger.Warnf(ctx, "[sandbox] begin turn for session %s failed: %v", sessionID, err)
return nil
}
return holder
}
if holder := begin(s.sandboxMgr); holder != nil {
return func() {
if err := holder.EndSessionTurn(ctx, sessionID); err != nil {
logger.Warnf(ctx, "[sandbox] end turn for session %s failed: %v", sessionID, err)
}
}
}
tenantID, _ := types.TenantIDFromContext(ctx)
if s.sandboxResolver == nil || tenantID == 0 {
return func() {}
}
mgr, err := resolveTenantSandboxForConfig(
ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy,
)
if err != nil {
logger.Warnf(ctx, "[sandbox] resolve config %s to begin turn of session %s failed: %v",
configID, sessionID, err)
return func() {}
}
holder := begin(mgr)
if holder == nil {
return func() {}
}
return func() {
if err := holder.EndSessionTurn(ctx, sessionID); err != nil {
logger.Warnf(ctx, "[sandbox] end turn for session %s failed: %v", sessionID, err)
}
}
}

View File

@ -142,6 +142,13 @@ func (s *sessionService) AgentQA(
llmContext = []chat.Message{}
}
// Hold the sandbox across this turn so an install that finishes while we
// are running cannot rebuild the VM between tool calls. Staging below is
// the first resolve: if the previous turn left a stale mark, that is
// where the new image is picked up.
releaseTurn := s.holdSandboxTurn(ctx, sessionID, agentConfig.SandboxConfigID)
defer releaseTurn()
// Reconcile all durable session attachments into the session's remote
// sandbox before the model can request shell or skill execution. The
// durable storage URL — not the ephemeral sandbox path — remains the
@ -298,6 +305,25 @@ func (s *sessionService) buildAgentConfig(
// Configure skills based on CustomAgentConfig
s.configureSkillsFromAgent(ctx, agentConfig, customAgent)
// Then add the skills installed into the sandbox config this run boots.
//
// The workspace is the one on the context rather than the agent's owner,
// because that is where resolveSandboxForExecution reads it; skillsForRun
// picks the config the same way the sandbox resolution does.
sandboxTenantID, _ := types.TenantIDFromContext(ctx)
skillConfigID, tenantSkills := skillsForRun(
ctx, s.sandboxPinner, s.sandboxConfigRepo, s.tenantSkillRepo,
sandboxTenantID, req.Session.ID, agentConfig.SandboxConfigID,
)
agentConfig.TenantSkills = tenantSkills
if len(tenantSkills) > 0 {
// The config named here is the one the skills came from, which is the
// pinned one whenever it differs from the agent's - the only case the
// line is worth reading.
logger.Infof(ctx, "Sandbox config %s offers %d installed skill(s) to this run",
skillConfigID, len(tenantSkills))
}
// Resolve knowledge bases using shared helper
kbIDs, knowledgeIDs, err := s.resolveKnowledgeBases(ctx, req)
if err != nil {
@ -583,5 +609,4 @@ func (s *sessionService) configureSkillsFromAgent(
agentConfig.SkillsEnabled = false
logger.Warnf(ctx, "Unknown SkillsSelectionMode=%s: skills disabled", customAgent.Config.SkillsSelectionMode)
}
}

View File

@ -0,0 +1,48 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestHoldSandboxTurnOpensAndClosesTheLease(t *testing.T) {
holder := &turnLeaseManager{}
svc := &sessionService{sandboxMgr: holder}
release := svc.holdSandboxTurn(context.Background(), "session-a", "")
require.Equal(t, 1, holder.begins)
require.Zero(t, holder.ends)
release()
require.Equal(t, 1, holder.ends)
}
func TestHoldSandboxTurnIsNoopWhenBeginFails(t *testing.T) {
holder := &turnLeaseManager{beginErr: context.Canceled}
svc := &sessionService{sandboxMgr: holder}
release := svc.holdSandboxTurn(context.Background(), "session-a", "")
require.Equal(t, 1, holder.begins)
release()
require.Zero(t, holder.ends)
}
type turnLeaseManager struct {
stagingSandboxManager
begins int
ends int
beginErr error
endErr error
}
func (m *turnLeaseManager) BeginSessionTurn(context.Context, string) error {
m.begins++
return m.beginErr
}
func (m *turnLeaseManager) EndSessionTurn(context.Context, string) error {
m.ends++
return m.endErr
}

View File

@ -116,6 +116,56 @@ func TestUpdateSessionIsScopedToCurrentUserAndAllowsNoOp(t *testing.T) {
require.NoError(t, err)
}
func TestUpdateSessionRejectsPlantedMaintenanceDescription(t *testing.T) {
svc, db := newTestSessionService(t)
aliceSession := &types.Session{
TenantID: 1,
UserID: "alice",
Title: "alice private session",
Description: "ordinary",
}
require.NoError(t, db.Create(aliceSession).Error)
err := svc.UpdateSession(testSessionScopeContext(1, "alice"), &types.Session{
ID: aliceSession.ID,
TenantID: 1,
Title: "still mine",
Description: types.SkillMaintenanceSessionMarker + "install",
})
require.NoError(t, err)
var got types.Session
require.NoError(t, db.First(&got, "id = ?", aliceSession.ID).Error)
require.Equal(t, "still mine", got.Title)
require.Empty(t, got.Description,
"a client must not be able to hide a session behind the maintenance marker")
}
func TestUpdateSessionPreservesMaintenanceDescription(t *testing.T) {
svc, db := newTestSessionService(t)
marker := types.SkillMaintenanceSessionMarker + "install"
row := &types.Session{
TenantID: 1,
UserID: "alice",
Title: "Skill install",
Description: marker,
}
require.NoError(t, db.Create(row).Error)
err := svc.UpdateSession(testSessionScopeContext(1, "alice"), &types.Session{
ID: row.ID,
TenantID: 1,
Title: "unhide me",
Description: "plain chat",
})
require.NoError(t, err)
var got types.Session
require.NoError(t, db.First(&got, "id = ?", row.ID).Error)
require.Equal(t, marker, got.Description,
"a PUT must not strip the marker off a real maintenance session")
}
func TestGetSessionIsScopedToAPIExternalUser(t *testing.T) {
svc, db := newTestSessionService(t)
aliceSession := &types.Session{

View File

@ -41,6 +41,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
)
@ -108,6 +109,56 @@ var ErrNamedSandboxBackendUnsupported = stderrors.New(
"named sandbox configs only support cube, e2b, docker and local backends",
)
// 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.
var ErrSkillSnapshotReleaseFailed = stderrors.New("failed to release skill snapshots")
// SkillSnapshotReleaseFailedError names the snapshots that are still on the
// provider so the handler can show them and a retry can skip already-deleted
// ones.
type SkillSnapshotReleaseFailedError struct {
Remaining []string
}
func (e *SkillSnapshotReleaseFailedError) Error() string {
if e == nil || len(e.Remaining) == 0 {
return ErrSkillSnapshotReleaseFailed.Error()
}
return fmt.Sprintf("%s: %s", ErrSkillSnapshotReleaseFailed.Error(), strings.Join(e.Remaining, ", "))
}
func (e *SkillSnapshotReleaseFailedError) Unwrap() error {
return ErrSkillSnapshotReleaseFailed
}
// sandboxSnapshotReleaser is the provider capability Delete needs. It is a
// named slice of RemoteSnapshotManager so tests do not have to fake Create or
// List, and so the type assertion is not anonymous.
type sandboxSnapshotReleaser interface {
DeleteSnapshot(ctx context.Context, snapshotID string) error
}
// sandboxConfigSkillStore is the skill/ledger slice Delete needs to destroy
// snapshots and drop rows that would dangle after SoftDelete.
type sandboxConfigSkillStore interface {
ListSnapshotsByConfig(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillSnapshotEntity, error)
MarkSnapshotState(ctx context.Context, tenantID uint64, id, state, snapshotID string) error
ListSkillsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
DeleteSnapshotRowsByConfig(ctx context.Context, tenantID uint64, configID string) error
}
// sandboxConfigBundleResolver locates the tenant file service so config
// deletion can drop skill archives after the ledger is released.
type sandboxConfigBundleResolver interface {
ResolveFileService(
ctx context.Context, tenant *types.Tenant, backendID, provider, localBaseDir string,
) (interfaces.FileService, string, error)
}
// SandboxInventory describes what a config holds and who a change disturbs.
type SandboxInventory struct {
SandboxCount int `json:"sandbox_count"`
@ -163,6 +214,12 @@ type TenantSandboxConfigService struct {
globalCfg *sandbox.Config
now func() time.Time
// skills and files are used only when deleting a config, to destroy the
// snapshot ledger and drop skill archives. Either may be nil in tests
// that never delete a config that owns skills.
skills sandboxConfigSkillStore
files sandboxConfigBundleResolver
// newClient is injectable so tests can supply a provider inventory.
newClient func(*sandbox.Config) (sandbox.ConfigSandboxClient, error)
@ -178,12 +235,16 @@ func NewTenantSandboxConfigService(
repo repository.TenantSandboxConfigRepository,
agents SandboxConfigAgentRepo,
globalCfg *sandbox.Config,
skills repository.TenantSkillRepository,
files sandboxConfigBundleResolver,
) *TenantSandboxConfigService {
return &TenantSandboxConfigService{
repo: repo,
agents: agents,
globalCfg: globalCfg,
now: time.Now,
skills: skills,
files: files,
newClient: func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return sandbox.NewRemoteClientForCheck(cfg)
},
@ -228,9 +289,21 @@ func SanitizeSandboxConfig(
if _, err := sandbox.ResolveEffectiveConfig(merged, sandbox.DefaultConfig()); err != nil {
return nil, err
}
if err := validateSkillRollout(merged.SkillRollout); err != nil {
return nil, err
}
return merged, nil
}
func validateSkillRollout(value string) error {
switch strings.TrimSpace(value) {
case "", types.SkillRolloutNextTurn, types.SkillRolloutNewSession:
return nil
default:
return apperrors.NewBadRequestError("invalid skill_rollout")
}
}
func validateNamedSandboxBackend(cfg *types.TenantSandboxConfig) error {
if cfg == nil || strings.TrimSpace(cfg.SandboxType) == "" {
return apperrors.NewBadRequestError("sandbox backend type is required")
@ -662,15 +735,18 @@ func (s *TenantSandboxConfigService) Update(
return updated, nil
}
// Delete refuses only while the config still owns sandboxes. Agent references
// are permanent state and are surfaced as warnings by callers, not blockers.
// Delete refuses while the config still owns sandboxes, and while skill
// snapshots on its ledger cannot be destroyed. Agent references are permanent
// state and are surfaced as warnings by callers, not blockers.
//
// force covers exactly one case: the provider could not be reached, so we cannot
// tell whether anything is live. Without it a config whose endpoint's DNS record
// disappeared could never be removed — unlike an edit, deletion has no "create a
// second config" way out. It does NOT override sandboxes we can actually see;
// those still have to be dealt with through their sessions, otherwise the forced
// deletion would be precisely the permanent leak this whole flow prevents.
// force covers two cases we cannot complete from here: the provider could not
// be reached to list sandboxes, and a skill snapshot could not be destroyed.
// Without it a config whose endpoint's DNS record disappeared, or whose
// snapshot API is down, could never be removed — unlike an edit, deletion has
// no "create a second config" way out. It does NOT override sandboxes we can
// actually see; those still have to be dealt with through their sessions,
// otherwise the forced deletion would be precisely the permanent leak this
// whole flow prevents.
func (s *TenantSandboxConfigService) Delete(
ctx context.Context, tenantID uint64, id string, force bool,
) error {
@ -699,9 +775,204 @@ func (s *TenantSandboxConfigService) Delete(
inv := s.inventoryFromSummaries(ctx, tenantID, id, summaries)
return &SandboxesStillLiveError{Inventory: inv}
}
if err := s.releaseSkillSnapshots(ctx, entity, tenantID, id, force); err != nil {
return err
}
return s.repo.SoftDelete(ctx, tenantID, id)
}
func snapshotReleaserFrom(client sandbox.ConfigSandboxClient) (sandboxSnapshotReleaser, bool) {
if client == nil {
return nil, false
}
releaser, ok := client.(sandboxSnapshotReleaser)
return releaser, ok
}
func pendingHaveProviderIDs(rows []*types.TenantSkillSnapshotEntity) bool {
for _, row := range rows {
if row != nil && strings.TrimSpace(row.SnapshotID) != "" {
return true
}
}
return false
}
func pendingSkillSnapshots(rows []*types.TenantSkillSnapshotEntity) []*types.TenantSkillSnapshotEntity {
var out []*types.TenantSkillSnapshotEntity
for _, row := range rows {
if row == nil || row.State == types.SkillSnapshotStateDeleted {
continue
}
out = append(out, row)
}
return out
}
func skillSnapshotName(row *types.TenantSkillSnapshotEntity) string {
if row == nil {
return ""
}
if name := strings.TrimSpace(row.SnapshotID); name != "" {
return name
}
return row.ID
}
func (s *TenantSandboxConfigService) releaseSkillSnapshots(
ctx context.Context,
entity *types.TenantSandboxConfigEntity,
tenantID uint64,
configID string,
force bool,
) error {
if s.skills == nil {
return nil
}
rows, err := s.skills.ListSnapshotsByConfig(ctx, tenantID, configID)
if err != nil {
if !force {
return fmt.Errorf("%w: list snapshots: %v", ErrSkillSnapshotReleaseFailed, err)
}
logger.Warnf(ctx,
"[sandbox] force-deleting config %s without listing skill snapshots: %v",
configID, err)
}
pending := pendingSkillSnapshots(rows)
remaining := s.destroyPendingSnapshots(ctx, entity, pending)
if len(remaining) > 0 && !force {
return &SkillSnapshotReleaseFailedError{Remaining: remaining}
}
if len(remaining) > 0 {
logger.Warnf(ctx,
"[sandbox] force-deleting config %s with unreleased snapshots %s",
configID, strings.Join(remaining, ", "))
}
s.cleanupSkillMetadata(ctx, tenantID, configID)
return nil
}
func (s *TenantSandboxConfigService) destroyPendingSnapshots(
ctx context.Context,
entity *types.TenantSandboxConfigEntity,
pending []*types.TenantSkillSnapshotEntity,
) []string {
if len(pending) == 0 {
return nil
}
releaser := sandboxSnapshotReleaser(nil)
if pendingHaveProviderIDs(pending) {
releaser = s.snapshotReleaserFor(ctx, entity)
}
var remaining []string
for _, row := range pending {
if err := deleteProviderSnapshot(ctx, releaser, row); err != nil {
remaining = append(remaining, skillSnapshotName(row))
continue
}
if err := s.skills.MarkSnapshotState(
ctx, row.TenantID, row.ID, types.SkillSnapshotStateDeleted, row.SnapshotID,
); err != nil {
logger.Warnf(ctx, "[sandbox] mark snapshot %s deleted failed: %v", row.ID, err)
remaining = append(remaining, skillSnapshotName(row))
}
}
return remaining
}
func (s *TenantSandboxConfigService) snapshotReleaserFor(
ctx context.Context, entity *types.TenantSandboxConfigEntity,
) sandboxSnapshotReleaser {
cfg := (*types.TenantSandboxConfig)(nil)
if entity != nil {
cfg = entity.Config
}
client, err := s.clientFor(cfg)
if err != nil {
logger.Warnf(ctx, "[sandbox] cannot build snapshot client for config %s: %v",
entityID(entity), err)
return nil
}
releaser, ok := snapshotReleaserFrom(client)
if !ok {
logger.Warnf(ctx, "[sandbox] config %s provider does not support snapshot delete",
entityID(entity))
return nil
}
return releaser
}
func entityID(entity *types.TenantSandboxConfigEntity) string {
if entity == nil {
return ""
}
return entity.ID
}
func deleteProviderSnapshot(
ctx context.Context, releaser sandboxSnapshotReleaser, row *types.TenantSkillSnapshotEntity,
) error {
if row == nil {
return nil
}
snapshotID := strings.TrimSpace(row.SnapshotID)
if snapshotID == "" {
return nil
}
if releaser == nil {
return fmt.Errorf("snapshot delete is unavailable")
}
err := releaser.DeleteSnapshot(ctx, snapshotID)
if err == nil || sandbox.IsRemoteNotFound(err) {
return nil
}
return err
}
func (s *TenantSandboxConfigService) cleanupSkillMetadata(
ctx context.Context, tenantID uint64, configID string,
) {
skills, err := s.skills.ListSkillsByConfig(ctx, tenantID, configID)
if err != nil {
logger.Warnf(ctx, "[sandbox] list skills for config %s cleanup failed: %v", configID, err)
}
for _, skill := range skills {
if skill == nil {
continue
}
s.deleteSkillBundleBestEffort(ctx, tenantID, skill.BundleRef)
if err := s.skills.DeleteSkill(ctx, tenantID, configID, skill.ID); err != nil {
logger.Warnf(ctx, "[sandbox] delete skill %s on config %s failed: %v",
skill.ID, configID, err)
}
}
if err := s.skills.DeleteSnapshotRowsByConfig(ctx, tenantID, configID); err != nil {
logger.Warnf(ctx, "[sandbox] delete snapshot ledger for config %s failed: %v",
configID, err)
}
}
func (s *TenantSandboxConfigService) deleteSkillBundleBestEffort(
ctx context.Context, tenantID uint64, bundleRef string,
) {
if s.files == nil || strings.TrimSpace(bundleRef) == "" {
return
}
fs, _, err := s.files.ResolveFileService(ctx, &types.Tenant{ID: tenantID}, "", "", "")
if err != nil || fs == nil {
logger.Warnf(ctx, "[sandbox] resolve file service to delete bundle %s failed: %v",
bundleRef, err)
return
}
if err := fs.DeleteFile(ctx, bundleRef); err != nil {
logger.Warnf(ctx, "[sandbox] delete bundle %s failed: %v", bundleRef, err)
}
}
func (s *TenantSandboxConfigService) clientFor(
cfg *types.TenantSandboxConfig,
) (sandbox.ConfigSandboxClient, error) {

View File

@ -3,6 +3,8 @@ package service
import (
"context"
stderrors "errors"
"io"
"mime/multipart"
"net/http"
"strings"
"sync"
@ -15,6 +17,7 @@ import (
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// testGlobalSandboxConfig supplies built-in runtime tuning values. Named
@ -234,6 +237,10 @@ func (f *fakeConfigRepo) ListByTenant(
return out, nil
}
func (f *fakeConfigRepo) ListAll(context.Context) ([]*types.TenantSandboxConfigEntity, error) {
return f.ListByTenant(context.Background(), 0)
}
func (f *fakeConfigRepo) Update(
_ context.Context, e *types.TenantSandboxConfigEntity,
) error {
@ -340,7 +347,7 @@ func newTestConfigService(
if client == nil {
client = &stubProviderClient{}
}
svc := NewTenantSandboxConfigService(repo, agents, testGlobalSandboxConfig())
svc := NewTenantSandboxConfigService(repo, agents, testGlobalSandboxConfig(), nil, nil)
svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return client, nil
}
@ -475,7 +482,7 @@ func TestQueryTemplatesResolvesMaskedStoredCredential(t *testing.T) {
ID: "cfg-a", TenantID: 7, SandboxType: "e2b",
Config: e2bCfg("stored-secret", "https://api.e2b.app", "e2b.app", "old", 300),
}}
svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, sandbox.DefaultConfig())
svc := NewTenantSandboxConfigService(repo, stubAgentRepo{}, sandbox.DefaultConfig(), nil, nil)
client := &stubProviderClient{templates: []sandbox.RemoteTemplate{{ID: "tpl-a", Name: "a", Status: "ready"}}}
svc.newClient = func(cfg *sandbox.Config) (sandbox.ConfigSandboxClient, error) {
require.Equal(t, "stored-secret", cfg.E2BAPIKey)
@ -560,6 +567,40 @@ func TestUpdateNonIdentityEditSkipsCordon(t *testing.T) {
require.Equal(t, 0, client.listCalls)
}
// Saving the connection / runtime form must not discard the snapshot pointer.
// The editor payload has no skill_image field; that pointer is owned by the
// install path. Wiping it is how a config can list two ready skills while
// every session still boots the base template.
func TestUpdateKeepsSkillImageWhenEditorOmitsIt(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-2",
Generation: 2,
BaseTemplateID: "base-template",
OwnerFingerprint: "fp-1",
}
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a",
TenantID: 7,
Name: "prod",
SandboxType: "e2b",
Config: stored,
}}
svc := newTestConfigService(t, repo, &stubProviderClient{}, stubAgentRepo{})
updated, err := svc.Update(context.Background(), 7, "cfg-a", UpdateSandboxConfigInput{
Name: "prod",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 900),
})
require.NoError(t, err)
require.NotNil(t, updated.Config.SkillImage)
require.Equal(t, "snap-2", updated.Config.SkillImage.SnapshotID)
require.Equal(t, 2, updated.Config.SkillImage.Generation)
require.Equal(t, "base-template", updated.Config.SkillImage.BaseTemplateID)
}
func TestUpdateRefusalCarriesInventory(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
@ -842,6 +883,22 @@ func TestSanitizeSandboxConfigPreservesSkillImage(t *testing.T) {
"the sandbox config API must not let a client plant or wipe the skill image")
}
func TestSanitizeSandboxConfigRejectsUnknownSkillRollout(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
SkillRollout: "whenever",
E2B: &types.E2BSandboxConfig{
APIKey: "stored-key", APIURL: "https://203.0.113.10", TemplateID: "t1",
},
}
_, err := SanitizeSandboxConfig(incoming, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "skill_rollout")
}
// Nothing is inherited from the deployment, so an incomplete config has to be
// refused when it is saved rather than at the first sandbox allocation.
func TestSanitizeSandboxConfigRejectsIncompleteConfig(t *testing.T) {
@ -980,3 +1037,315 @@ func TestWorkspaceScriptsDisabledPolicy(t *testing.T) {
require.NoError(t, err)
require.False(t, disabled)
}
func TestDeleteReleasesSkillSnapshotsBeforeSoftDelete(t *testing.T) {
fx := newSnapshotReleaseFixture(t, nil)
err := fx.svc.Delete(context.Background(), 7, "cfg-a", false)
require.NoError(t, err)
require.Equal(t, []string{"snap-1", "snap-2", "soft-delete"}, fx.events)
require.Contains(t, fx.skills.marks, "row-1:"+types.SkillSnapshotStateDeleted)
require.Contains(t, fx.skills.marks, "row-2:"+types.SkillSnapshotStateDeleted)
require.NotContains(t, fx.skills.marks, "row-0:"+types.SkillSnapshotStateDeleted)
require.Empty(t, fx.skills.skills, "tenant_skills rows must be dropped before SoftDelete")
require.True(t, fx.skills.ledgerCleared)
require.Equal(t, []string{"bundle://skill-a.zip"}, fx.files.deleted)
}
func TestDeleteRefusesWhenSnapshotReleaseFailsWithoutForce(t *testing.T) {
fx := newSnapshotReleaseFixture(t, map[string]error{
"snap-2": stderrors.New("provider unavailable"),
})
err := fx.svc.Delete(context.Background(), 7, "cfg-a", false)
require.ErrorIs(t, err, ErrSkillSnapshotReleaseFailed)
var releaseErr *SkillSnapshotReleaseFailedError
require.ErrorAs(t, err, &releaseErr)
require.Equal(t, []string{"snap-2"}, releaseErr.Remaining)
require.NotContains(t, fx.events, "soft-delete",
"leaving the row behind is recoverable; leaking a billable snapshot is not")
require.Equal(t, types.SkillSnapshotStateDeleted, fx.skills.snapshot("row-1").State)
require.Equal(t, types.SkillSnapshotStateSuperseded, fx.skills.snapshot("row-2").State)
require.Len(t, fx.skills.skills, 1, "skill rows stay so a retry can finish the release")
require.False(t, fx.skills.ledgerCleared)
}
func TestDeleteWithForceProceedsAndRecordsThePartialSuccess(t *testing.T) {
fx := newSnapshotReleaseFixture(t, map[string]error{
"snap-2": stderrors.New("provider unavailable"),
})
err := fx.svc.Delete(context.Background(), 7, "cfg-a", true)
require.NoError(t, err)
require.Equal(t, []string{"snap-1", "soft-delete"}, fx.events)
require.Contains(t, fx.skills.marks, "row-1:"+types.SkillSnapshotStateDeleted)
require.NotContains(t, fx.skills.marks, "row-2:"+types.SkillSnapshotStateDeleted)
require.True(t, fx.repo.deleted)
require.True(t, fx.skills.ledgerCleared)
require.Empty(t, fx.skills.skills)
}
func TestDeleteMarksBuildingSnapshotsWhenProviderHasNoSnapshotClient(t *testing.T) {
repo := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "local", SandboxType: "local",
Config: &types.TenantSandboxConfig{SandboxType: "local"},
}}
skills := &deleteSkillStore{
snapshots: []*types.TenantSkillSnapshotEntity{{
ID: "row-build", TenantID: 7, SandboxConfigID: "cfg-a",
State: types.SkillSnapshotStateBuilding,
}},
}
svc := newTestConfigService(t, repo, nil, stubAgentRepo{})
svc.skills = skills
err := svc.Delete(context.Background(), 7, "cfg-a", false)
require.NoError(t, err)
require.True(t, repo.deleted)
require.Contains(t, skills.marks, "row-build:"+types.SkillSnapshotStateDeleted)
}
// snapshotReleaseFixture drives Delete through a provider that also implements
// snapshot deletion, which is the production Cube/E2B split.
type snapshotReleaseFixture struct {
events []string
repo *eventRecordingConfigRepo
skills *deleteSkillStore
files *deleteBundleResolver
svc *TenantSandboxConfigService
}
func newSnapshotReleaseFixture(t *testing.T, failDelete map[string]error) *snapshotReleaseFixture {
t.Helper()
fx := &snapshotReleaseFixture{
skills: &deleteSkillStore{
snapshots: []*types.TenantSkillSnapshotEntity{
{
ID: "row-0", TenantID: 7, SandboxConfigID: "cfg-a",
SnapshotID: "snap-gone", State: types.SkillSnapshotStateDeleted,
},
{
ID: "row-1", TenantID: 7, SandboxConfigID: "cfg-a",
SnapshotID: "snap-1", State: types.SkillSnapshotStateActive,
},
{
ID: "row-2", TenantID: 7, SandboxConfigID: "cfg-a",
SnapshotID: "snap-2", State: types.SkillSnapshotStateSuperseded,
},
},
skills: []*types.TenantSkillEntity{{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-a",
BundleRef: "bundle://skill-a.zip",
}},
},
files: &deleteBundleResolver{},
}
inner := &fakeConfigRepo{entity: &types.TenantSandboxConfigEntity{
ID: "cfg-a", TenantID: 7, Name: "prod", SandboxType: "e2b",
Config: e2bCfg("key-a", "https://api.e2b.app", "e2b.app", "t1", 300),
}}
fx.repo = &eventRecordingConfigRepo{fakeConfigRepo: inner, events: &fx.events}
client := &snapshotReleaseClient{events: &fx.events, failDelete: failDelete}
fx.svc = newTestConfigService(t, inner, &client.stubProviderClient, stubAgentRepo{})
fx.svc.repo = fx.repo
fx.svc.skills = fx.skills
fx.svc.files = fx.files
fx.svc.newClient = func(*sandbox.Config) (sandbox.ConfigSandboxClient, error) {
return client, nil
}
return fx
}
type eventRecordingConfigRepo struct {
*fakeConfigRepo
events *[]string
}
func (r *eventRecordingConfigRepo) SoftDelete(ctx context.Context, tenantID uint64, id string) error {
if err := ctx.Err(); err != nil {
return err
}
*r.events = append(*r.events, "soft-delete")
return r.fakeConfigRepo.SoftDelete(ctx, tenantID, id)
}
type snapshotReleaseClient struct {
stubProviderClient
events *[]string
failDelete map[string]error
}
func (c *snapshotReleaseClient) List(
ctx context.Context, filter sandbox.RemoteListFilter,
) ([]sandbox.RemoteSandboxSummary, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
return c.stubProviderClient.List(ctx, filter)
}
func (c *snapshotReleaseClient) Delete(ctx context.Context, sandboxID string) error {
if err := ctx.Err(); err != nil {
return err
}
return c.stubProviderClient.Delete(ctx, sandboxID)
}
func (c *snapshotReleaseClient) DeleteSnapshot(ctx context.Context, snapshotID string) error {
if err := ctx.Err(); err != nil {
return err
}
if err := c.failDelete[snapshotID]; err != nil {
return err
}
*c.events = append(*c.events, snapshotID)
return nil
}
type deleteSkillStore struct {
snapshots []*types.TenantSkillSnapshotEntity
skills []*types.TenantSkillEntity
marks []string
ledgerCleared bool
}
func (s *deleteSkillStore) snapshot(id string) *types.TenantSkillSnapshotEntity {
for _, row := range s.snapshots {
if row.ID == id {
return row
}
}
return &types.TenantSkillSnapshotEntity{}
}
func (s *deleteSkillStore) ListSnapshotsByConfig(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillSnapshotEntity, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
var out []*types.TenantSkillSnapshotEntity
for _, row := range s.snapshots {
if row.TenantID == tenantID && row.SandboxConfigID == configID {
cp := *row
out = append(out, &cp)
}
}
return out, nil
}
func (s *deleteSkillStore) MarkSnapshotState(
ctx context.Context, tenantID uint64, id, state, snapshotID string,
) error {
if err := ctx.Err(); err != nil {
return err
}
s.marks = append(s.marks, id+":"+state)
for _, row := range s.snapshots {
// The real query is tenant-scoped, so a caller passing the wrong
// workspace must match nothing here too.
if row.ID != id || row.TenantID != tenantID {
continue
}
row.State = state
if snapshotID != "" {
row.SnapshotID = snapshotID
}
}
return nil
}
func (s *deleteSkillStore) ListSkillsByConfig(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillEntity, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
var out []*types.TenantSkillEntity
for _, row := range s.skills {
if row.TenantID == tenantID && row.SandboxConfigID == configID {
cp := *row
out = append(out, &cp)
}
}
return out, nil
}
func (s *deleteSkillStore) DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error {
if err := ctx.Err(); err != nil {
return err
}
kept := s.skills[:0]
for _, row := range s.skills {
if row.TenantID == tenantID && row.SandboxConfigID == configID && row.ID == skillID {
continue
}
kept = append(kept, row)
}
s.skills = kept
return nil
}
func (s *deleteSkillStore) DeleteSnapshotRowsByConfig(ctx context.Context, tenantID uint64, configID string) error {
if err := ctx.Err(); err != nil {
return err
}
s.ledgerCleared = true
kept := s.snapshots[:0]
for _, row := range s.snapshots {
if row.TenantID == tenantID && row.SandboxConfigID == configID {
continue
}
kept = append(kept, row)
}
s.snapshots = kept
return nil
}
type deleteBundleResolver struct {
deleted []string
}
func (r *deleteBundleResolver) ResolveFileService(
ctx context.Context, _ *types.Tenant, _, _, _ string,
) (interfaces.FileService, string, error) {
if err := ctx.Err(); err != nil {
return nil, "", err
}
return deleteFileService{r: r}, "", nil
}
type deleteFileService struct{ r *deleteBundleResolver }
func (deleteFileService) CheckConnectivity(context.Context) error { return nil }
func (deleteFileService) SaveFile(context.Context, *multipart.FileHeader, uint64, string) (string, error) {
return "", nil
}
func (deleteFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) {
return "", nil
}
func (deleteFileService) GetFile(context.Context, string) (io.ReadCloser, error) { return nil, nil }
func (deleteFileService) GetFileURL(context.Context, string) (string, error) { return "", nil }
func (s deleteFileService) DeleteFile(ctx context.Context, ref string) error {
if err := ctx.Err(); err != nil {
return err
}
s.r.deleted = append(s.r.deleted, ref)
return nil
}
func (deleteFileService) CopyFile(context.Context, string, uint64, string) (string, error) {
return "", nil
}
var (
_ sandbox.ConfigSandboxClient = (*snapshotReleaseClient)(nil)
_ sandboxSnapshotReleaser = (*snapshotReleaseClient)(nil)
_ sandboxConfigSkillStore = (*deleteSkillStore)(nil)
_ sandboxConfigBundleResolver = (*deleteBundleResolver)(nil)
)

View File

@ -0,0 +1,106 @@
package service
import (
"context"
"encoding/json"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
)
// ListUsableSkills returns the installed skills a chat turn can actually
// invoke on this config: ready, enabled, and carried by the live snapshot.
// Failures and a missing config yield an empty list so @ mention never 500s.
func (s *TenantSkillService) ListUsableSkills(
ctx context.Context, tenantID uint64, configID string,
) []*types.TenantSkillEntity {
return effectiveTenantSkills(ctx, s.configs, s.skills, tenantID, configID)
}
// ListSkills returns the skills installed onto one sandbox config.
//
// The config is read first so a config that does not belong to this workspace
// is reported as missing rather than as a config that simply has no skills.
func (s *TenantSkillService) ListSkills(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillEntity, error) {
cfgEntity, err := s.configs.GetByID(ctx, tenantID, configID)
if err != nil {
return nil, err
}
if cfgEntity == nil {
return nil, apperrors.NewNotFoundError("sandbox config not found")
}
return s.skills.ListSkillsByConfig(ctx, tenantID, configID)
}
// GetSkill returns one installed skill, or nil when this workspace's config
// does not carry it. The repository scopes the lookup by workspace and config,
// so a skill ID from another workspace is indistinguishable from a missing one.
func (s *TenantSkillService) GetSkill(
ctx context.Context, tenantID uint64, configID, skillID string,
) (*types.TenantSkillEntity, error) {
return s.skills.GetSkill(ctx, tenantID, configID, skillID)
}
// SetSkillEnabled hides or reveals an installed skill.
//
// This is metadata only: the files stay in the image either way, which is what
// makes it safe to toggle while the image is otherwise untouched. Removing the
// files is RemoveSkill's job and needs a new snapshot. It returns nil when the
// skill is not reachable for this workspace and config.
func (s *TenantSkillService) SetSkillEnabled(
ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
) (*types.TenantSkillEntity, error) {
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
return nil, err
}
if skill == nil {
return nil, nil
}
if skill.Enabled == enabled {
return skill, nil
}
skill.Enabled = enabled
if err := s.skills.UpdateSkill(ctx, skill); err != nil {
return nil, err
}
return skill, nil
}
// SubscribeProgress follows one install or removal.
//
// A nil channel means there is no live stream to follow — without Redis
// nothing is published at all — and the caller is expected to fall back to the
// durable status. The returned closer must always be called: it releases the
// Redis subscription, which would otherwise outlive the request.
func (s *TenantSkillService) SubscribeProgress(
ctx context.Context, tenantID uint64, configID, skillID string,
) (<-chan SkillProgress, func(), error) {
if s.redis == nil {
return nil, func() {}, nil
}
sub := s.redis.Subscribe(ctx, skillProgressKey(tenantID, configID, skillID))
out := make(chan SkillProgress, skillProgressBuffer)
go func() {
defer close(out)
for msg := range sub.Channel() {
var p SkillProgress
if err := json.Unmarshal([]byte(msg.Payload), &p); err != nil {
continue
}
select {
case out <- p:
case <-ctx.Done():
return
}
}
}()
return out, func() { _ = sub.Close() }, nil
}
// skillProgressBuffer absorbs the burst a fast stage transition produces so a
// subscriber that is momentarily busy writing to its client does not stall the
// pub/sub reader.
const skillProgressBuffer = 16

View File

@ -0,0 +1,101 @@
package service
import (
"context"
"testing"
"github.com/stretchr/testify/require"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
)
func TestListSkillsReturnsTheConfigsSkills(t *testing.T) {
fx := newInstallFixture(t)
skills, err := fx.svc.ListSkills(context.Background(), 7, "cfg-1")
require.NoError(t, err)
require.Len(t, skills, 1)
require.Equal(t, "sk-1", skills[0].ID)
}
// A config another workspace owns must be unreachable, not merely empty: an
// empty list would tell the caller the config exists.
func TestListSkillsRefusesAConfigOfAnotherWorkspace(t *testing.T) {
fx := newInstallFixture(t)
_, err := fx.svc.ListSkills(context.Background(), 8, "cfg-1")
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
require.Equal(t, 404, appErr.HTTPCode)
}
func TestGetSkillIsScopedToWorkspaceAndConfig(t *testing.T) {
fx := newInstallFixture(t)
ctx := context.Background()
skill, err := fx.svc.GetSkill(ctx, 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.NotNil(t, skill)
for _, tc := range []struct {
name string
tenantID uint64
configID string
}{
{"another workspace", 8, "cfg-1"},
{"another config", 7, "cfg-2"},
} {
t.Run(tc.name, func(t *testing.T) {
found, err := fx.svc.GetSkill(ctx, tc.tenantID, tc.configID, "sk-1")
require.NoError(t, err)
require.Nil(t, found)
})
}
}
// Hiding a skill is metadata only: the row's install state must survive it,
// because the files are still in the image.
func TestSetSkillEnabledPersistsWithoutTouchingInstallState(t *testing.T) {
fx := newInstallFixture(t)
ctx := context.Background()
updated, err := fx.svc.SetSkillEnabled(ctx, 7, "cfg-1", "sk-1", false)
require.NoError(t, err)
require.NotNil(t, updated)
require.False(t, updated.Enabled)
stored, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.False(t, stored.Enabled)
require.Equal(t, types.SkillStatusInstalling, stored.Status)
back, err := fx.svc.SetSkillEnabled(ctx, 7, "cfg-1", "sk-1", true)
require.NoError(t, err)
require.True(t, back.Enabled)
}
func TestSetSkillEnabledReturnsNilForAnotherWorkspace(t *testing.T) {
fx := newInstallFixture(t)
updated, err := fx.svc.SetSkillEnabled(context.Background(), 8, "cfg-1", "sk-1", false)
require.NoError(t, err)
require.Nil(t, updated)
stored, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.True(t, stored.Enabled, "a foreign workspace must not be able to hide this skill")
}
// Without Redis nothing publishes progress, so there is no stream to hand out.
// The closer must still be safe to call: every caller defers it.
func TestSubscribeProgressWithoutRedisYieldsNoStream(t *testing.T) {
fx := newInstallFixture(t)
events, release, err := fx.svc.SubscribeProgress(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Nil(t, events)
require.NotNil(t, release)
release()
}

View File

@ -0,0 +1,120 @@
package service
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// skillImageConfigReader reads the sandbox config an agent selected. Narrowed
// to the one method this derivation needs so a chat turn cannot reach the
// config write surface.
type skillImageConfigReader interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
}
// installedSkillLister lists the skills installed onto one sandbox config.
type installedSkillLister interface {
ListSkillsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
}
// skillsForRun returns the sandbox config this run's sandbox boots and the
// installed skills that config offers.
//
// The config is not simply the agent's. A session's remote sandbox is
// long-lived and stays on the config it was pinned to, so an agent re-pointed
// mid-conversation still runs on the pinned image; deriving skills from the
// agent's current choice would announce skills the running image does not
// carry, which is exactly the failure this derivation exists to prevent.
//
// A pin we cannot read leaves us unable to say which image boots, and the
// agent's config is precisely the wrong guess in the case that matters, so
// that path offers nothing.
func skillsForRun(
ctx context.Context,
pinner *SessionSandboxPinner,
configs skillImageConfigReader,
skills installedSkillLister,
tenantID uint64,
sessionID string,
agentConfigID string,
) (string, []*types.TenantSkillEntity) {
configID := agentConfigID
pinned, err := sandboxConfigForExistingSandbox(ctx, pinner, sessionID)
if err != nil {
logger.Warnf(ctx, "[skill] read the pinned sandbox config of session %s failed: %v",
sessionID, err)
return "", nil
}
if pinned != "" {
configID = pinned
}
return configID, effectiveTenantSkills(ctx, configs, skills, tenantID, configID)
}
// effectiveTenantSkills returns the installed skills this run can actually
// invoke, which is the only set worth telling a model about.
//
// Two conditions have to hold, and both are about the same thing - whether the
// files exist where the call would look for them:
//
// - The stored snapshot must be the image sessions boot. When the backend
// cannot snapshot, or the credentials no longer resolve the recorded
// snapshot, sessions boot the BASE template, which carries none of these
// skills. Announcing them then costs the model several turns on calls that
// can only fail, so ZERO skills are returned - not a degraded subset.
// - The row must be ready and enabled. Anything else is either not in the
// image yet, not in it any more, or deliberately hidden by an
// administrator.
//
// Every failure returns nothing: a chat turn must not fail because a skill
// lookup did, and a workspace with no installed skills is the common case.
func effectiveTenantSkills(
ctx context.Context,
configs skillImageConfigReader,
skills installedSkillLister,
tenantID uint64,
configID string,
) []*types.TenantSkillEntity {
if configs == nil || skills == nil || configID == "" || tenantID == 0 {
return nil
}
cfgEntity, err := configs.GetByID(ctx, tenantID, configID)
if err != nil {
logger.Warnf(ctx, "[skill] load sandbox config %s for skill injection failed: %v",
configID, err)
return nil
}
if cfgEntity == nil || cfgEntity.Config == nil {
return nil
}
if !sandbox.SkillImageActive(cfgEntity.Config) {
if image := cfgEntity.Config.SkillImage; image != nil && image.SnapshotID != "" {
logger.Warnf(ctx,
"[skill] sandbox config %s boots its base template rather than skill image %s; "+
"no installed skills are offered to the agent",
configID, image.SnapshotID)
}
return nil
}
rows, err := skills.ListSkillsByConfig(ctx, tenantID, configID)
if err != nil {
logger.Warnf(ctx, "[skill] list skills of sandbox config %s failed: %v", configID, err)
return nil
}
usable := make([]*types.TenantSkillEntity, 0, len(rows))
for _, row := range rows {
if row == nil || !row.Enabled || row.Status != types.SkillStatusReady {
continue
}
usable = append(usable, row)
}
if len(usable) == 0 {
return nil
}
return usable
}

View File

@ -0,0 +1,262 @@
package service
import (
"context"
"errors"
"testing"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
// effectiveFixture is one sandbox config whose image is usable, carrying one
// skill of every lifecycle state.
type effectiveFixture struct {
configs *installConfigRepo
skills *installSkillRepo
}
// usableSkillImageConfig is a config whose stored snapshot is the image its
// sessions boot, which is the precondition for offering any installed skill.
func usableSkillImageConfig(id string, tenantID uint64) *types.TenantSandboxConfigEntity {
fingerprint := sandbox.SkillImageFingerprint("e2b", "key-1", "https://e2b.example")
return &types.TenantSandboxConfigEntity{
ID: id,
TenantID: tenantID,
SandboxType: string(sandbox.SandboxTypeE2B),
Config: &types.TenantSandboxConfig{
SandboxType: string(sandbox.SandboxTypeE2B),
E2B: &types.E2BSandboxConfig{
APIURL: "https://e2b.example", APIKey: "key-1", TemplateID: "base-template",
},
SkillImage: &types.SkillImageConfig{
SnapshotID: "snap-3", Generation: 3,
BaseTemplateID: "base-template", OwnerFingerprint: fingerprint,
},
},
}
}
func newEffectiveFixture(t *testing.T) *effectiveFixture {
t.Helper()
fx := &effectiveFixture{
configs: &installConfigRepo{entity: usableSkillImageConfig("cfg-1", 7)},
skills: newInstallSkillRepo(),
}
rows := []*types.TenantSkillEntity{
{ID: "sk-1", Name: "ready-enabled", Status: types.SkillStatusReady, Enabled: true},
{ID: "sk-2", Name: "ready-disabled", Status: types.SkillStatusReady, Enabled: false},
{ID: "sk-3", Name: "installing", Status: types.SkillStatusInstalling, Enabled: true},
{ID: "sk-4", Name: "failed", Status: types.SkillStatusFailed, Enabled: true},
{ID: "sk-5", Name: "removing", Status: types.SkillStatusRemoving, Enabled: true},
{ID: "sk-6", Name: "second-ready", Status: types.SkillStatusReady, Enabled: true},
}
for _, row := range rows {
row.TenantID = 7
row.SandboxConfigID = "cfg-1"
require.NoError(t, fx.skills.CreateSkill(context.Background(), row))
}
return fx
}
func (fx *effectiveFixture) derive(ctx context.Context) []*types.TenantSkillEntity {
return effectiveTenantSkills(ctx, fx.configs, fx.skills, 7, "cfg-1")
}
func skillNames(rows []*types.TenantSkillEntity) []string {
names := make([]string, 0, len(rows))
for _, row := range rows {
names = append(names, row.Name)
}
return names
}
func TestEffectiveTenantSkillsKeepsOnlyReadyAndEnabledSkills(t *testing.T) {
fx := newEffectiveFixture(t)
got := fx.derive(context.Background())
require.ElementsMatch(t, []string{"ready-enabled", "second-ready"}, skillNames(got))
}
func TestListUsableSkillsMatchesTheEffectiveSet(t *testing.T) {
fx := newEffectiveFixture(t)
svc := &TenantSkillService{configs: fx.configs, skills: fx.skills}
got := svc.ListUsableSkills(context.Background(), 7, "cfg-1")
require.ElementsMatch(t, []string{"ready-enabled", "second-ready"}, skillNames(got))
}
// The image is what carries the skills. When the live credentials cannot
// resolve the stored snapshot, sessions boot the base template, which has none
// of them - so announcing any would burn turns on calls that cannot work.
func TestEffectiveTenantSkillsInjectsNothingWhenTheFingerprintDisagrees(t *testing.T) {
fx := newEffectiveFixture(t)
fx.configs.entity.Config.E2B.APIKey = "rotated-key"
require.Empty(t, fx.derive(context.Background()))
}
func TestEffectiveTenantSkillsInjectsNothingWhenTheBackendCannotSnapshot(t *testing.T) {
fx := newEffectiveFixture(t)
fx.configs.entity.SandboxType = "docker"
fx.configs.entity.Config.SandboxType = "docker"
require.Empty(t, fx.derive(context.Background()))
}
func TestEffectiveTenantSkillsInjectsNothingWithoutAnImage(t *testing.T) {
fx := newEffectiveFixture(t)
fx.configs.entity.Config.SkillImage = nil
require.Empty(t, fx.derive(context.Background()))
}
func TestEffectiveTenantSkillsInjectsNothingWithoutASelectedConfig(t *testing.T) {
fx := newEffectiveFixture(t)
require.Empty(t, effectiveTenantSkills(
context.Background(), fx.configs, fx.skills, 7, ""))
require.Empty(t, effectiveTenantSkills(
context.Background(), fx.configs, fx.skills, 7, "cfg-other"),
"a config that does not exist for this workspace has no skills")
require.Empty(t, effectiveTenantSkills(
context.Background(), fx.configs, fx.skills, 9, "cfg-1"),
"another workspace must not see these skills")
}
// failingConfigRepo is the config read erroring the way the gorm repository
// does on a dead connection or a cancelled query.
//
// It hands back the entity as well as the error on purpose: a scan that fails
// part way leaves the destination struct populated, so the error - not the
// emptiness of the result - has to be what stops the derivation.
type failingConfigRepo struct {
entity *types.TenantSandboxConfigEntity
err error
}
func (r failingConfigRepo) GetByID(
context.Context, uint64, string,
) (*types.TenantSandboxConfigEntity, error) {
return r.entity, r.err
}
// Without the config we cannot tell whether the image sessions boot carries
// these skills, so the derivation must stop there rather than list rows and
// offer them.
func TestEffectiveTenantSkillsInjectsNothingWhenTheConfigLookupFails(t *testing.T) {
fx := newEffectiveFixture(t)
failing := failingConfigRepo{
entity: usableSkillImageConfig("cfg-1", 7),
err: errors.New("connection refused"),
}
require.Empty(t, effectiveTenantSkills(
context.Background(), failing, fx.skills, 7, "cfg-1"))
require.Zero(t, fx.skills.listCalls,
"a config we could not read says nothing about which skills are usable")
}
// The other half of the same rule, one step later: the config read succeeded
// and listing the rows is what failed.
func TestEffectiveTenantSkillsInjectsNothingWhenTheSkillListingFails(t *testing.T) {
fx := newEffectiveFixture(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
require.Empty(t, fx.derive(ctx))
require.Equal(t, 1, fx.skills.listCalls)
}
// multiConfigRepo answers for several sandbox configs at once, which the
// install fake - built around the single config an install runs against -
// cannot do.
type multiConfigRepo struct {
entities map[string]*types.TenantSandboxConfigEntity
}
func (r *multiConfigRepo) GetByID(
_ context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
entity, ok := r.entities[id]
if !ok || entity.TenantID != tenantID {
return nil, nil
}
return entity, nil
}
// twoConfigFixture holds two usable configs with one ready skill each, so a
// test can tell which of them the derivation actually used.
func twoConfigFixture(t *testing.T) (*multiConfigRepo, *installSkillRepo) {
t.Helper()
configs := &multiConfigRepo{entities: map[string]*types.TenantSandboxConfigEntity{
"cfg-a": usableSkillImageConfig("cfg-a", 7),
"cfg-b": usableSkillImageConfig("cfg-b", 7),
}}
skills := newInstallSkillRepo()
for configID, name := range map[string]string{"cfg-a": "skill-of-a", "cfg-b": "skill-of-b"} {
require.NoError(t, skills.CreateSkill(context.Background(), &types.TenantSkillEntity{
ID: "sk-" + configID, Name: name, TenantID: 7, SandboxConfigID: configID,
Status: types.SkillStatusReady, Enabled: true,
}))
}
return configs, skills
}
// A session's sandbox is long-lived and boots the config it was pinned to. If
// the derivation followed the agent's current choice instead, re-pointing an
// agent mid-conversation would announce skills the running image does not
// carry - the exact hole this derivation exists to close.
func TestSkillsForRunPrefersThePinnedConfigOverTheAgents(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
ctx := context.Background()
_, err := pinner.Pin(ctx, "s-1", "cfg-a")
require.NoError(t, err)
configs, skills := twoConfigFixture(t)
configID, rows := skillsForRun(ctx, pinner, configs, skills, 7, "s-1", "cfg-b")
require.Equal(t, "cfg-a", configID)
require.Equal(t, []string{"skill-of-a"}, skillNames(rows))
}
// Without a pin the session has no sandbox yet, so its first one will boot the
// agent's config.
func TestSkillsForRunFallsBackToTheAgentConfigWhenUnpinned(t *testing.T) {
pinner := NewSessionSandboxPinner(newPinTestDB(t))
configs, skills := twoConfigFixture(t)
configID, rows := skillsForRun(
context.Background(), pinner, configs, skills, 7, "s-1", "cfg-b")
require.Equal(t, "cfg-b", configID)
require.Equal(t, []string{"skill-of-b"}, skillNames(rows))
}
// When the pin cannot be read we do not know which image boots, and guessing
// the agent's config is exactly the wrong guess for a re-pointed agent. Offer
// nothing.
func TestSkillsForRunOffersNothingWhenThePinCannotBeRead(t *testing.T) {
db := newPinTestDB(t)
pinner := NewSessionSandboxPinner(db)
require.NoError(t, db.Migrator().DropTable(&types.Session{}))
configs, skills := twoConfigFixture(t)
configID, rows := skillsForRun(
context.Background(), pinner, configs, skills, 7, "s-1", "cfg-b")
require.Empty(t, configID)
require.Empty(t, rows)
require.Zero(t, skills.listCalls)
}
func TestEffectiveTenantSkillsToleratesMissingDependencies(t *testing.T) {
fx := newEffectiveFixture(t)
require.Empty(t, effectiveTenantSkills(context.Background(), nil, fx.skills, 7, "cfg-1"))
require.Empty(t, effectiveTenantSkills(context.Background(), fx.configs, nil, 7, "cfg-1"))
}

View File

@ -11,6 +11,7 @@ import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"github.com/Tencent/WeKnora/internal/agent/tools"
apperrors "github.com/Tencent/WeKnora/internal/errors"
@ -84,7 +85,29 @@ func (s *TenantSkillService) InstallSkill(
BundleSHA256: bundle.SHA256, Enabled: true,
Status: types.SkillStatusInstalling, InstallingSince: &now,
}); err != nil {
return "", err
if !isSkillNameConflict(err) {
return "", err
}
// Two first-time uploads of the same name raced the unique index.
// Take the row that won rather than surfacing a 500.
winner, lookupErr := s.skills.GetSkillByName(ctx, tenantID, configID, bundle.Name)
if lookupErr != nil {
return "", lookupErr
}
if winner == nil {
return "", err
}
skillID = winner.ID
winner.Version = bundle.Version
winner.Description = bundle.Description
winner.Instructions = bundle.Instructions
winner.BundleSHA256 = bundle.SHA256
winner.Status = types.SkillStatusInstalling
winner.Error = ""
winner.InstallingSince = &now
if err := s.skills.UpdateSkill(ctx, winner); err != nil {
return "", err
}
}
}
@ -234,7 +257,7 @@ func (s *TenantSkillService) runInstall(
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{Percent: 35, Stage: "seeded"})
// 3. Let the installer agent install dependencies.
if err := s.driveInstallerAgent(ctx, tenantID, sess, mgr, skillDir, bundle); err != nil {
if err := s.driveInstallerAgent(ctx, tenantID, skillID, sess, mgr, skillDir, bundle); err != nil {
return err
}
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{Percent: 80, Stage: "agent_done"})
@ -470,8 +493,8 @@ func (s *TenantSkillService) seedSkillFiles(
// swallows engine failures (it emits an error event and returns nil) and we
// need a reliable signal before switching the image.
func (s *TenantSkillService) driveInstallerAgent(
ctx context.Context, tenantID uint64, sess *types.Session, mgr sandbox.Manager,
skillDir string, bundle *SkillBundle,
ctx context.Context, tenantID uint64, skillID string, sess *types.Session,
mgr sandbox.Manager, skillDir string, bundle *SkillBundle,
) error {
if s.installerAgents == nil {
return errors.New("custom agent service is not configured")
@ -493,20 +516,49 @@ func (s *TenantSkillService) driveInstallerAgent(
bus := event.NewEventBus()
assistantMessageID := uuid.NewString()
prompt := buildInstallPrompt(skillDir, bundle, s.probeUv(ctx, mgr, sess.ID))
// The transcript is set up before the engine so a console that attaches
// while the install is still running finds a message to stream into. Its
// failures are logged rather than returned: an unreadable transcript is a
// worse outcome than no transcript, but neither is a reason to refuse an
// otherwise good install.
transcript := newInstallTranscript(ctx, bus, s.streams, s.messages, sess.ID, assistantMessageID)
if err := transcript.Create(ctx, prompt); err != nil {
logger.Warnf(ctx, "[skill] seed install transcript for %s failed: %v", skillID, err)
}
transcript.Subscribe()
if err := s.updateSkillFields(ctx, tenantID, sess.SandboxConfigID, skillID,
func(e *types.TenantSkillEntity) {
e.InstallSessionID = sess.ID
e.InstallMessageID = assistantMessageID
}); err != nil {
logger.Warnf(ctx, "[skill] record transcript locators for %s failed: %v", skillID, err)
}
engine, err := s.agents.CreateAgentEngine(
ctx, agentConfig, chatModel, nil, bus, sess.ID, assistantMessageID,
)
if err != nil {
return fmt.Errorf("create installer engine: %w", err)
runErr := fmt.Errorf("create installer engine: %w", err)
transcript.Finish(ctx, runErr)
return runErr
}
prompt := buildInstallPrompt(skillDir, bundle, s.probeUv(ctx, mgr, sess.ID))
state, err := engine.Execute(ctx, sess.ID, assistantMessageID, prompt, nil)
if err != nil {
return fmt.Errorf("installer agent failed: %w", err)
runErr := err
if runErr == nil && (state == nil || !state.IsComplete) {
runErr = errors.New("installer agent stopped without completing")
}
if state == nil || !state.IsComplete {
return errors.New("installer agent stopped without completing")
// Detached from cancellation: when the install lock's renewal fails the
// context dies, and the transcript of the run that just died is precisely
// what someone will want to read.
transcript.Finish(context.WithoutCancel(ctx), runErr)
if runErr != nil {
if err != nil {
return fmt.Errorf("installer agent failed: %w", err)
}
return runErr
}
return nil
}
@ -569,16 +621,24 @@ func (s *TenantSkillService) verifyDeclaredDependencies(
return nil
}
// normalizeSkillPermissions hands the skill tree to the execution user.
// Installs run as root, so without this the non-root user that actually runs
// skills could not read them — which is also why it runs before verification:
// the smoke test has to exercise the permissions the snapshot will carry.
// normalizeSkillPermissions makes the skill tree readable and executable by
// the non-root execution user, and writable by nobody. Installs run as root,
// so without the mode change the user that actually runs skills could not read
// them at all — which is also why this runs before verification: the smoke
// test has to exercise the permissions the snapshot will carry.
//
// Ownership stays with root rather than moving to the execution user because
// this tree is baked into an image every session of the config inherits. A
// session that could write here would be editing the skills every other
// session runs. 555 leaves reads and execs to the "other" bits, which is all a
// skill run needs; the cost is that Python cannot write __pycache__ into the
// tree and silently skips bytecode caching.
func (s *TenantSkillService) normalizeSkillPermissions(
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string,
) error {
cmds := []string{
fmt.Sprintf("chmod -R 755 %s", sandbox.ShellQuote(skillDir)),
fmt.Sprintf("chown -R %s %s", sandbox.DefaultSandboxExecUser, sandbox.ShellQuote(skillDir)),
fmt.Sprintf("chmod -R 555 %s", sandbox.ShellQuote(skillDir)),
fmt.Sprintf("chown -R root:root %s", sandbox.ShellQuote(skillDir)),
}
for _, cmd := range cmds {
if _, err := s.execInstall(ctx, mgr, sessionID, cmd); err != nil {
@ -818,6 +878,10 @@ func (s *TenantSkillService) installStillOwnsTheRow(
// operation name is carried into the session because the transcript is kept
// deliberately, for troubleshooting: filing a removal's under "Skill install"
// would send whoever reads it looking at the wrong operation.
//
// The description marker is what keeps this row out of the console's session
// list, and the owner is the admin who started the operation, so a transcript
// is readable by the person who caused it rather than by the whole workspace.
func (s *TenantSkillService) startMaintenanceSession(
ctx context.Context, tenantID uint64, configID, operation string,
) (*types.Session, sandbox.Manager, error) {
@ -840,8 +904,9 @@ func (s *TenantSkillService) startMaintenanceSession(
}
sess, err := s.sessions.CreateSession(ctx, &types.Session{
TenantID: tenantID,
UserID: sessionUserIDFromContext(ctx),
Title: "Skill " + operation,
Description: "Tenant skill image maintenance",
Description: types.SkillMaintenanceSessionMarker + operation,
SandboxConfigID: configID,
})
if err != nil {
@ -1307,6 +1372,19 @@ func currentBaseTemplate(cfg *types.TenantSandboxConfig) string {
return ""
}
// isSkillNameConflict recognises the unique (config, name) violation two
// concurrent first-time uploads of the same skill produce.
func isSkillNameConflict(err error) bool {
if err == nil {
return false
}
if errors.Is(err, gorm.ErrDuplicatedKey) {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "duplicate") || strings.Contains(msg, "unique constraint")
}
func skillOwnerFingerprint(cfg *types.TenantSandboxConfig) string {
if cfg == nil {
return ""
@ -1324,15 +1402,83 @@ func skillOwnerFingerprint(cfg *types.TenantSandboxConfig) string {
return ""
}
// markConfigSandboxesStale is deliberately a no-op here. Sessions that already
// hold a live sandbox keep running on the previous image until it is replaced;
// marking and rebuilding those bindings is Task 13 (stale sandbox rebuild),
// which owns the session-side state this would have to touch. Future sessions
// already pick up the new snapshot through the config pointer.
// configSandboxInvalidator is the narrow capability marking bound sandboxes
// needs. It is reached by type assertion rather than declared on Manager
// because only the session-bound remote manager owns bindings to mark: a local
// or disabled backend has none, and for those doing nothing is correct.
type configSandboxInvalidator interface {
InvalidateConfigSandboxes(ctx context.Context, tenantID uint64, configID string) (int, error)
}
// The manager the resolver hands out must keep satisfying this, so a rename on
// the sandbox side breaks the build instead of silently skipping every mark.
var _ configSandboxInvalidator = (*sandbox.SessionBoundManager)(nil)
// markConfigSandboxesStale tells every session already holding a sandbox of
// this config that the image underneath it has been replaced.
//
// The pointer switch alone only reaches FUTURE sessions: one that is open right
// now is bound to a sandbox booted from the previous image, and without this it
// would keep serving that image until the session ends - so a skill installed
// minutes ago would be missing from exactly the sessions whose user just asked
// for it. Nothing is destroyed here; the binding is marked and the session's
// next resolve rebuilds it.
//
// It is best-effort on purpose. It runs after the pointer switch, so the
// install has already succeeded, and a binding that could not be marked is a
// session serving a stale image - an annoyance, not a corruption. Turning that
// into a failed install would be a lie about an image that is live and serving.
//
// The context is detached because the caller's is cancelled exactly when this
// matters most: withConfigLock cancels the run's context the moment lock
// renewal fails, and marking is ordinary Redis traffic that a dead context
// fails outright.
func (s *TenantSkillService) markConfigSandboxesStale(
ctx context.Context, tenantID uint64, configID string,
) {
_ = ctx
_ = tenantID
_ = configID
if s.sandboxes == nil {
return
}
markCtx, cancel := s.cleanupContext(context.WithoutCancel(ctx))
defer cancel()
if s.configs != nil {
entity, err := s.configs.GetByID(markCtx, tenantID, configID)
if err != nil {
logger.Warnf(markCtx,
"[skill] read config %s skill_rollout before marking sandboxes stale failed: %v",
configID, err)
} else if entity != nil && !entity.Config.RebuildsExistingOnSkillChange() {
logger.Infof(markCtx,
"[skill] config %s skill_rollout=%s; leaving live sandboxes on the previous image",
configID, types.SkillRolloutNewSession)
return
}
}
mgr, err := s.sandboxes.Resolve(markCtx, tenantID, configID)
if err != nil || mgr == nil {
logger.Warnf(markCtx,
"[skill] resolve sandbox config %s to mark its sandboxes stale failed: %v",
configID, err)
return
}
invalidator, ok := mgr.(configSandboxInvalidator)
if !ok {
return
}
marked, err := invalidator.InvalidateConfigSandboxes(markCtx, tenantID, configID)
if err != nil {
logger.Warnf(markCtx,
"[skill] mark live sandboxes of config %s stale failed: %v", configID, err)
return
}
if marked == 0 {
return
}
logger.Infof(markCtx,
"[skill] marked %d live sandbox binding(s) of config %s stale "+
"(this run's own maintenance session included); each remaining session "+
"rebuilds from the new image on its next use",
marked, configID)
}

View File

@ -43,7 +43,7 @@ func TestRunInstallHappyPathSwitchesPointerLast(t *testing.T) {
"create-session", "prepare-skill-dir", "seed-files", "agent-execute",
"chmod", "verify-structure", "verify-smoke", "write-manifest",
"cleanup-workspace", "create-snapshot",
"switch-pointer", "destroy-sandbox",
"switch-pointer", "mark-stale", "destroy-sandbox",
}, fx.events, "the pointer must move only after the snapshot exists")
cfg := fx.configRepo.saved.Config
@ -79,8 +79,8 @@ func TestRunInstallIssuesExactlyTheseCommands(t *testing.T) {
require.Equal(t, []string{
installPrepareCommand,
"uv --version",
"chmod -R 755 " + installSkillDir,
"chown -R user " + installSkillDir,
"chmod -R 555 " + installSkillDir,
"chown -R root:root " + installSkillDir,
"test -f " + installSkillDir + "/SKILL.md",
"test -f " + installSkillDir + "/scripts/extract.py",
installSmokeCommand,
@ -278,6 +278,22 @@ func TestFailSkillDoesNotStampANewerBundle(t *testing.T) {
require.Empty(t, skill.Error)
}
func TestInstallSkillRecoversFromNameConflict(t *testing.T) {
fx := newInstallFixture(t)
fx.skillRepo.getByNameMisses = 1
fx.skillRepo.createErr = errors.New("UNIQUE constraint failed: tenant_skills.sandbox_config_id")
archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
id, err := fx.svc.InstallSkill(context.Background(), 7, "cfg-1", archive)
require.NoError(t, err)
require.Equal(t, "sk-1", id,
"the upload that lost the unique index must reuse the row that won")
skill, getErr := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, getErr)
require.Equal(t, types.SkillStatusInstalling, skill.Status)
}
func TestInstallSkillRefusesWhenBundleCannotBeStored(t *testing.T) {
fx := newInstallFixture(t)
fx.saveErr = errors.New("object store down")
@ -651,6 +667,41 @@ func TestResolveInstallerModelFallsBackWhenTheAgentNamesNoModel(t *testing.T) {
require.Equal(t, "model-1", model.GetModelID())
}
// The console attaches to a running install through the assistant message, so
// the locators must be on the skill row before the engine starts — not after
// the run ends, by which point there is nothing live left to watch.
func TestRunInstallPublishesTranscriptLocatorsBeforeTheAgentRuns(t *testing.T) {
fx := newInstallFixture(t)
var atExecute *types.TenantSkillEntity
fx.beforeExecute = func() {
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
copied := *skill
atExecute = &copied
}
require.NoError(t, fx.svc.runInstall(ctxWithTenant(7), 7, "cfg-1", "sk-1", fx.bundle))
require.NotNil(t, atExecute, "the installer engine never ran")
require.NotEmpty(t, atExecute.InstallSessionID)
require.NotEmpty(t, atExecute.InstallMessageID)
}
// Maintenance sessions are excluded from the console by their description, and
// scoped to the admin who started the install by their owner. Both are written
// at creation time; neither has a backfill.
func TestStartMaintenanceSessionMarksAndScopesTheSession(t *testing.T) {
fx := newInstallFixture(t)
ctx := context.WithValue(ctxWithTenant(7), types.UserIDContextKey, "admin-1")
sess, _, err := fx.svc.startMaintenanceSession(ctx, 7, "cfg-1", "install")
require.NoError(t, err)
require.Equal(t, types.SkillMaintenanceSessionMarker+"install", sess.Description)
require.Equal(t, "admin-1", sess.UserID)
require.Equal(t, "Skill install", sess.Title)
}
const installSkillDir = "/opt/weknora/tenant/skills/pdf-tools"
// The install commands are asserted verbatim: an install runs as root with the
@ -683,6 +734,14 @@ func indexOfEvent(events []string, needle string) int {
return -1
}
// staleMark is one request to mark a config's bound sandboxes stale. The
// tenant is part of it because marking the right config of the wrong workspace
// would rebuild sandboxes that never carried this image.
type staleMark struct {
tenantID uint64
configID string
}
type installFixture struct {
t *testing.T
svc *TenantSkillService
@ -709,6 +768,15 @@ type installFixture struct {
execResult *sandbox.ExecuteResult
smokeRanAsRoot bool
agentErr error
// beforeExecute runs at the moment the engine would start, so a test can
// observe the state an attaching console would see mid-install.
beforeExecute func()
// staleMarks records every InvalidateConfigSandboxes call, so a test can
// state which config was marked rather than only that something was.
staleMarks []staleMark
// invalidateErr fails the marking the way an unreachable binding store
// would, without failing anything else the run does.
invalidateErr error
// rmExitCode fails the removal's directory wipe, the one image step a
// removal has.
rmExitCode int
@ -805,6 +873,8 @@ func newInstallFixture(t *testing.T) *installFixture {
&installSessionService{fx: fx},
fx.modelSvc,
nil,
&transcriptStreams{},
&transcriptMessages{},
)
fx.svc.now = func() time.Time { return time.Date(2026, 8, 19, 9, 30, 0, 0, time.UTC) }
return fx
@ -908,6 +978,16 @@ func (r *installConfigRepo) ListByTenant(context.Context, uint64) ([]*types.Tena
return nil, nil
}
// ListAll returns the one config this fixture holds, so a housekeeping scan
// sees the same config the install and removal tests act on.
func (r *installConfigRepo) ListAll(context.Context) ([]*types.TenantSandboxConfigEntity, error) {
if r.entity == nil {
return nil, nil
}
cp := *r.entity
return []*types.TenantSandboxConfigEntity{&cp}, nil
}
// Update honours the context because the real gorm repository does: the
// pointer switch is the one write a lost lock must not be able to complete.
func (r *installConfigRepo) Update(ctx context.Context, e *types.TenantSandboxConfigEntity) error {
@ -948,8 +1028,14 @@ type installSkillRepo struct {
// deleteSkillErr models the row delete failing past the point of no
// return.
deleteSkillErr error
createErr error
getByNameMisses int
readyWriteAttempts int
deleteSkillAttempts int
// listCalls counts attempts, not successes: a caller that gave up before
// listing and one whose listing failed are different bugs, and the skill
// derivation tests turn on telling them apart.
listCalls int
}
func newInstallSkillRepo() *installSkillRepo {
@ -966,6 +1052,9 @@ func skillKey(tenantID uint64, configID, skillID string) string {
func (r *installSkillRepo) CreateSkill(_ context.Context, e *types.TenantSkillEntity) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.createErr != nil {
return r.createErr
}
cp := *e
r.skills[skillKey(e.TenantID, e.SandboxConfigID, e.ID)] = &cp
return nil
@ -994,6 +1083,10 @@ func (r *installSkillRepo) GetSkillByName(
) (*types.TenantSkillEntity, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.getByNameMisses > 0 {
r.getByNameMisses--
return nil, nil
}
for _, e := range r.skills {
if e.TenantID == tenantID && e.SandboxConfigID == configID && e.Name == name {
cp := *e
@ -1006,6 +1099,11 @@ func (r *installSkillRepo) GetSkillByName(
func (r *installSkillRepo) ListSkillsByConfig(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillEntity, error) {
// Counted before the context check so a cancelled listing still registers
// as an attempt.
r.mu.Lock()
r.listCalls++
r.mu.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
@ -1254,7 +1352,7 @@ func (m *installSandboxManager) ExecShellCommandWithOptions(
}, nil
case command == "rm -rf /workspace/* /workspace/.[!.]* || true":
m.fx.record("cleanup-workspace")
case strings.HasPrefix(command, "chmod -R 755 "):
case strings.HasPrefix(command, "chmod -R 555 "):
m.fx.record("chmod")
}
if m.fx.execResult != nil && command == m.fx.execResultCommand {
@ -1286,6 +1384,23 @@ func (m *installSandboxManager) ListSnapshots(context.Context, string) ([]sandbo
return nil, nil
}
// InvalidateConfigSandboxes refuses a cancelled context exactly as the
// Redis-backed binding store would, so a caller that forgot to detach the
// install's context fails here rather than silently marking nothing.
func (m *installSandboxManager) InvalidateConfigSandboxes(
ctx context.Context, tenantID uint64, configID string,
) (int, error) {
if err := ctx.Err(); err != nil {
return 0, err
}
if m.fx.invalidateErr != nil {
return 0, m.fx.invalidateErr
}
m.fx.staleMarks = append(m.fx.staleMarks, staleMark{tenantID: tenantID, configID: configID})
m.fx.record("mark-stale")
return 1, nil
}
// DestroySession refuses a cancelled context because the provider call does:
// releasing the sandbox is the compensation for a lost lock, so it must not run
// on the context the lock cancelled.
@ -1412,6 +1527,9 @@ func (e *installAgentEngine) Execute(
[]chat.Message,
...[]string,
) (*types.AgentState, error) {
if e.fx.beforeExecute != nil {
e.fx.beforeExecute()
}
e.fx.record("agent-execute")
if e.fx.agentDelay > 0 {
time.Sleep(e.fx.agentDelay)

View File

@ -0,0 +1,409 @@
package service
import (
"context"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/robfig/cron/v3"
)
const (
skillReaperCronSpec = "0 */5 * * * *"
skillInstallInterruptedMessage = "安装进程中断: the process died before the install finished"
)
// skillReaperStore is the skill-row slice ReapStuckRuns needs.
type skillReaperStore interface {
ListStaleInstalling(ctx context.Context, olderThan time.Time) ([]*types.TenantSkillEntity, error)
GetSkill(ctx context.Context, tenantID uint64, configID, skillID string) (*types.TenantSkillEntity, error)
UpdateSkill(ctx context.Context, e *types.TenantSkillEntity) error
DeleteSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
}
// skillReaperConfigReader is the config read ReapStuckRuns needs to tell a
// serving skill (pointer already switched) from a genuinely abandoned install.
type skillReaperConfigReader interface {
GetByID(ctx context.Context, tenantID uint64, id string) (*types.TenantSandboxConfigEntity, error)
}
// skillSnapshotLedger is the per-config chain: what ReconcileSnapshots compares
// provider listings against, and what ReapStuckRuns walks to decide whether a
// stuck run's skill is still in the live image.
type skillSnapshotLedger interface {
ListSnapshotsByConfig(
ctx context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillSnapshotEntity, error)
}
// skillSnapshotLister is the provider listing ReconcileSnapshots is allowed to
// call. It deliberately omits DeleteSnapshot: extras are warned, never removed,
// because the same provider account may be shared across environments.
type skillSnapshotLister interface {
ListSnapshots(ctx context.Context, sandboxID string) ([]sandbox.RemoteSnapshotRef, error)
}
// sandboxConfigEnumerator walks every sandbox config for the orphan-snapshot
// sweep. ListAll is housekeeping-only.
type sandboxConfigEnumerator interface {
ListAll(ctx context.Context) ([]*types.TenantSandboxConfigEntity, error)
}
var (
_ skillReaperStore = (repository.TenantSkillRepository)(nil)
_ skillSnapshotLedger = (repository.TenantSkillRepository)(nil)
_ skillReaperConfigReader = (repository.TenantSandboxConfigRepository)(nil)
_ sandboxConfigEnumerator = (repository.TenantSandboxConfigRepository)(nil)
_ skillSnapshotLister = (sandbox.RemoteSnapshotManager)(nil)
)
// ReapStuckRuns recovers skill rows whose install or remove process died.
//
// Both branches turn on one question — does the image every new session boots
// still carry this skill's files — and skillFilesInLiveImage answers it from
// the snapshot ledger rather than from the row.
//
// An installing row older than skillInstallStuckTTL is healed to ready when
// the files are there: a re-install that died before the pointer moved, or a
// terminal ready write that never landed. Leaving it at installing would hide
// a skill the image still carries. Otherwise it becomes failed so the UI stops
// spinning.
//
// A removing row is restored to ready while the files are still there, so the
// operator can retry. Once they are gone the leftover row is deleted, so the
// agent cannot be told to invoke a skill no image carries.
func (s *TenantSkillService) ReapStuckRuns(ctx context.Context) (int, error) {
if s == nil || s.skills == nil {
return 0, nil
}
now := s.now
if now == nil {
now = time.Now
}
cutoff := now().Add(-skillInstallStuckTTL)
stale, err := s.skills.ListStaleInstalling(ctx, cutoff)
if err != nil {
return 0, err
}
reaped := 0
for _, row := range stale {
if row == nil || row.InstallingSince == nil || !row.InstallingSince.Before(cutoff) {
continue
}
snapshotID, serving, known := s.skillFilesInLiveImage(ctx, row)
switch row.Status {
case types.SkillStatusInstalling:
// An unreadable config or ledger must not be treated as a failed
// install: the image may still be serving this skill.
if serving || !known {
if err := s.updateSkillFields(ctx, row.TenantID, row.SandboxConfigID, row.ID,
func(e *types.TenantSkillEntity) {
e.Status = types.SkillStatusReady
e.Error = ""
e.InstallingSince = nil
// The install that died past the pointer switch never
// got to record which snapshot carries it.
if snapshotID != "" {
e.InstalledSnapshotID = snapshotID
}
}); err != nil {
logger.Warnf(ctx, "[skill] heal abandoned install %s back to ready failed: %v",
row.ID, err)
continue
}
reaped++
continue
}
if err := s.updateSkillFields(ctx, row.TenantID, row.SandboxConfigID, row.ID,
func(e *types.TenantSkillEntity) {
e.Status = types.SkillStatusFailed
e.Error = skillInstallInterruptedMessage
e.InstallingSince = nil
}); err != nil {
logger.Warnf(ctx, "[skill] reap abandoned install %s failed: %v", row.ID, err)
continue
}
reaped++
case types.SkillStatusRemoving:
// Deleting the row and its bundle is the one irreversible thing
// the reaper does, so a run it cannot judge is left for the next
// sweep rather than guessed at.
if !known {
continue
}
if serving {
if err := s.updateSkillFields(ctx, row.TenantID, row.SandboxConfigID, row.ID,
func(e *types.TenantSkillEntity) {
e.Status = types.SkillStatusReady
e.Error = ""
e.InstallingSince = nil
if snapshotID != "" {
e.InstalledSnapshotID = snapshotID
}
}); err != nil {
logger.Warnf(ctx, "[skill] restore abandoned removal %s failed: %v", row.ID, err)
continue
}
reaped++
continue
}
if err := s.skills.DeleteSkill(ctx, row.TenantID, row.SandboxConfigID, row.ID); err != nil {
logger.Warnf(ctx, "[skill] drop abandoned removal %s failed: %v", row.ID, err)
continue
}
if row.BundleRef != "" {
s.deleteBundleBestEffort(ctx, row.TenantID, row.BundleRef)
}
reaped++
}
}
if reaped > 0 {
logger.Infof(ctx, "[skill] reaped %d stuck install/remove run(s)", reaped)
}
return reaped, nil
}
// skillFilesInLiveImage reports whether the image every new session boots
// still carries this skill, and which snapshot of the chain put it there.
// known is false when the config or the ledger cannot be read, so a caller
// about to do something irreversible can refuse to guess.
//
// The question is not whether this row's InstalledSnapshotID equals the live
// one. A config holds a single pointer that every install and removal
// advances, and each new snapshot is grown from the current one, so a skill
// installed two generations ago is still in the image under a snapshot ID its
// row never hears about — nothing rewrites one skill's row when another skill
// is installed. Comparing the two IDs calls such a skill gone: it fails
// healthy installs and, worse, deletes the row and bundle of a stuck removal
// whose files are still in the image.
//
// The ledger records each snapshot's parent, so the honest question is whether
// this skill's install is on the chain the pointer currently names.
func (s *TenantSkillService) skillFilesInLiveImage(
ctx context.Context, row *types.TenantSkillEntity,
) (string, bool, bool) {
if row == nil {
return "", false, false
}
live, ok := s.liveSnapshotID(ctx, row)
if !ok {
return "", false, false
}
if live = strings.TrimSpace(live); live == "" {
// The config boots its base template, which carries no skill by
// construction — the last removal of the config cleared the pointer.
return "", false, true
}
ledger, err := s.skills.ListSnapshotsByConfig(ctx, row.TenantID, row.SandboxConfigID)
if err != nil {
logger.Warnf(ctx, "[skill] reaper could not read the snapshot ledger of config %s: %v",
row.SandboxConfigID, err)
return "", false, false
}
bySnapshot := make(map[string]*types.TenantSkillSnapshotEntity, len(ledger))
everInstalled := false
for _, entry := range ledger {
if entry == nil {
continue
}
// A building row has no snapshot yet, and one abandoned between the
// snapshot and the pointer switch is a child of live rather than an
// ancestor, so anchoring the walk on live already excludes both.
if id := strings.TrimSpace(entry.SnapshotID); id != "" {
bySnapshot[id] = entry
}
if entry.SkillID == row.ID && entry.Trigger == types.SkillSnapshotTriggerInstall {
everInstalled = true
}
}
// The visited set only stops a corrupted parent pointer from looping; the
// chain itself is finite.
visited := make(map[string]struct{}, len(bySnapshot))
for cursor := live; cursor != ""; {
if _, seen := visited[cursor]; seen {
break
}
visited[cursor] = struct{}{}
entry, ok := bySnapshot[cursor]
if !ok {
// The chain runs out before it answers. A skill that never
// produced a snapshot is absent either way; for one that did,
// refuse to guess rather than delete files that may still exist.
return "", false, !everInstalled
}
if entry.SkillID == row.ID {
// The nearest generation naming this skill decides it: an install
// put the files in, a removal took them out, and a rebuild says
// nothing about one skill so the walk continues past it.
switch entry.Trigger {
case types.SkillSnapshotTriggerInstall:
return entry.SnapshotID, true, true
case types.SkillSnapshotTriggerRemove:
return "", false, true
}
}
cursor = strings.TrimSpace(entry.ParentSnapshotID)
}
return "", false, true
}
// liveSnapshotID returns the config's current SkillImage snapshot and whether
// that answer is trustworthy. ok is false when the config cannot be read, so
// the caller can refuse to guess.
func (s *TenantSkillService) liveSnapshotID(
ctx context.Context, row *types.TenantSkillEntity,
) (string, bool) {
if row == nil || s.configs == nil {
return "", false
}
cfg, err := s.configs.GetByID(ctx, row.TenantID, row.SandboxConfigID)
if err != nil {
logger.Warnf(ctx, "[skill] reaper could not read sandbox config %s: %v",
row.SandboxConfigID, err)
return "", false
}
return currentSnapshotID(cfg), true
}
// ReconcileSnapshots compares provider ListSnapshots against the ledger for one
// config. Snapshots that exist on the provider but not in the ledger are
// logged as warnings and never deleted: the same provider account may be
// shared across environments, and an extra here is often another environment's
// live image.
func (s *TenantSkillService) ReconcileSnapshots(
ctx context.Context, tenantID uint64, configID string,
) (int, error) {
if s == nil || s.skills == nil {
return 0, nil
}
rows, err := s.skills.ListSnapshotsByConfig(ctx, tenantID, configID)
if err != nil {
return 0, err
}
known := make(map[string]struct{}, len(rows))
for _, row := range rows {
if row == nil {
continue
}
id := strings.TrimSpace(row.SnapshotID)
if id == "" {
continue
}
known[id] = struct{}{}
}
lister := snapshotListerFrom(ctx, s.sandboxes, tenantID, configID)
if lister == nil {
return 0, nil
}
listed, err := lister.ListSnapshots(ctx, "")
if err != nil {
return 0, err
}
extras := 0
for _, snap := range listed {
id := strings.TrimSpace(snap.ID)
if id == "" {
continue
}
if _, ok := known[id]; ok {
continue
}
extras++
logger.Warnf(ctx,
"[skill] snapshot %s is not in the ledger of sandbox config %s "+
"(not deleted; the provider account may be shared across environments)",
id, configID)
}
return extras, nil
}
func snapshotListerFrom(
ctx context.Context, resolver sandbox.TenantSandboxResolver, tenantID uint64, configID string,
) skillSnapshotLister {
if resolver == nil {
return nil
}
mgr, err := resolver.Resolve(ctx, tenantID, configID)
if err != nil {
logger.Warnf(ctx, "[skill] resolve sandbox for snapshot reconcile of %s failed: %v", configID, err)
return nil
}
if mgr == nil {
return nil
}
lister, ok := mgr.(skillSnapshotLister)
if !ok {
return nil
}
return lister
}
func (s *TenantSkillService) reconcileAllSnapshots(ctx context.Context) {
enum, ok := s.configs.(sandboxConfigEnumerator)
if !ok {
return
}
configs, err := enum.ListAll(ctx)
if err != nil {
logger.Warnf(ctx, "[skill] list sandbox configs for snapshot reconcile failed: %v", err)
return
}
for _, cfg := range configs {
if cfg == nil || types.IsSandboxWorkspacePolicyRow(cfg) {
continue
}
if _, err := s.ReconcileSnapshots(ctx, cfg.TenantID, cfg.ID); err != nil {
logger.Warnf(ctx, "[skill] reconcile snapshots for config %s failed: %v", cfg.ID, err)
}
}
}
func (s *TenantSkillService) runSkillReaper(ctx context.Context) {
if _, err := s.ReapStuckRuns(ctx); err != nil {
logger.Warnf(ctx, "[skill] reap stuck runs failed: %v", err)
}
s.reconcileAllSnapshots(ctx)
}
// Start registers the five-minute stuck-run sweep and begins the background
// runner. Idempotent — repeated calls are a no-op so wiring code can call
// Start without coordinating ordering.
func (s *TenantSkillService) Start(ctx context.Context) error {
s.cronMu.Lock()
defer s.cronMu.Unlock()
if s.started {
return nil
}
if s.cron == nil {
s.cron = cron.New(cron.WithSeconds(), cron.WithChain(
cron.Recover(cron.DefaultLogger),
))
}
if _, err := s.cron.AddFunc(skillReaperCronSpec, func() {
s.runSkillReaper(context.Background())
}); err != nil {
return err
}
s.cron.Start()
s.started = true
logger.Infof(ctx, "[skill] reaper started with 5-minute sweep")
return nil
}
// Stop halts the cron and waits for in-flight sweeps to finish.
func (s *TenantSkillService) Stop() {
s.cronMu.Lock()
defer s.cronMu.Unlock()
if !s.started {
return
}
c := s.cron.Stop()
<-c.Done()
s.started = false
}

View File

@ -0,0 +1,490 @@
package service
import (
"context"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
func TestReapStuckRunsFailsAbandonedInstalls(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusInstalling, InstallingSince: &staleSince,
})
// The live image is another skill's generation: this install died before
// it ever produced a snapshot of its own.
fx.installed("sk-2", "snap-other", "")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
got := fx.skills.mustGet("sk-1")
require.Equal(t, types.SkillStatusFailed, got.Status,
"a row left installing after the process died must stop spinning in the UI")
require.Contains(t, got.Error, "安装进程中断")
require.Contains(t, strings.ToLower(got.Error), "process died")
require.Nil(t, got.InstallingSince)
}
func TestReapStuckRunsRestoresAbandonedRemovals(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusRemoving,
InstalledSnapshotID: "snap-live", InstallingSince: &staleSince,
})
fx.installed("sk-1", "snap-live", "")
fx.live("snap-live")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
got := fx.skills.mustGet("sk-1")
require.Equal(t, types.SkillStatusReady, got.Status,
"the image still has the skill, so showing it as removed would be a lie")
require.Nil(t, got.InstallingSince)
}
// A config accumulates generations, and only the skill being installed gets
// its row rewritten. Judging an older skill by whether its own snapshot is
// still the live one therefore condemns every skill but the most recent —
// here by deleting the row and bundle of files the image still carries.
func TestReapStuckRunsRestoresRemovalOfSkillInheritedByALaterSnapshot(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusRemoving,
InstalledSnapshotID: "snap-1", BundleRef: "bundle-1",
InstallingSince: &staleSince,
})
// A second skill was installed afterwards. Its snapshot grew from the one
// carrying pdf, so pdf is still in the image the pointer now names.
fx.installed("sk-1", "snap-1", "")
fx.installed("sk-2", "snap-2", "snap-1")
fx.live("snap-2")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
got := fx.skills.mustGet("sk-1")
require.NotNil(t, got, "the files are still in the image; deleting the row would lose a live skill")
require.Equal(t, types.SkillStatusReady, got.Status)
require.Nil(t, got.InstallingSince)
}
func TestReapStuckRunsDeletesAbandonedRemovalAfterPointerMoved(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusRemoving,
InstalledSnapshotID: "snap-old", BundleRef: "bundle-1",
InstallingSince: &staleSince,
})
// The removal got as far as snapshotting the image without the skill and
// switching the pointer; only its bookkeeping never landed.
fx.installed("sk-1", "snap-old", "")
fx.removed("sk-1", "snap-new", "snap-old")
fx.live("snap-new")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Nil(t, fx.skills.rows["sk-1"],
"the pointer already left this skill behind; restoring ready would offer files the image no longer has")
}
func TestReapStuckRunsDeletesAbandonedRemovalThatNeverReachedAnImage(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusRemoving, InstallingSince: &staleSince,
})
fx.installed("sk-2", "snap-other", "")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
require.Nil(t, fx.skills.rows["sk-1"],
"a skill that never reached an image must not be marked ready")
}
// Deleting the row and its bundle is the only irreversible thing the reaper
// does, so a chain it cannot follow must be left for the next sweep.
func TestReapStuckRunsLeavesRemovalAloneWhenTheChainCannotBeFollowed(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusRemoving,
InstalledSnapshotID: "snap-1", BundleRef: "bundle-1",
InstallingSince: &staleSince,
})
fx.installed("sk-1", "snap-1", "")
// The pointer names a generation the ledger does not describe, so whether
// snap-1 is one of its ancestors is unknowable.
fx.live("snap-missing")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Zero(t, n)
require.Equal(t, types.SkillStatusRemoving, fx.skills.mustGet("sk-1").Status,
"an unreadable chain must not be resolved by deleting the row")
}
func TestReapStuckRunsIgnoresFreshRuns(t *testing.T) {
fx := newReaperFixture(t)
freshSince := fx.now.Add(-time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusInstalling, InstallingSince: &freshSince,
})
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Zero(t, n, "a run started a minute ago must not be killed")
got := fx.skills.mustGet("sk-1")
require.Equal(t, types.SkillStatusInstalling, got.Status)
}
func TestReapStuckRunsHealsInstallingRowWhoseSnapshotIsStillLive(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusInstalling,
InstalledSnapshotID: "snap-live", InstallingSince: &staleSince,
})
fx.installed("sk-1", "snap-live", "")
fx.live("snap-live")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n,
"a re-install that died before the pointer moved must become ready again")
got := fx.skills.mustGet("sk-1")
require.Equal(t, types.SkillStatusReady, got.Status)
require.Empty(t, got.Error)
require.Nil(t, got.InstallingSince)
require.Equal(t, "snap-live", got.InstalledSnapshotID)
}
// The install's last step is a row write that runs after the pointer has
// already switched. When the process dies in between, the skill is in the
// image every session boots while its row still says nothing about it.
func TestReapStuckRunsHealsInstallThatDiedAfterThePointerSwitched(t *testing.T) {
fx := newReaperFixture(t)
staleSince := fx.now.Add(-skillInstallStuckTTL - time.Minute)
fx.skills.put(&types.TenantSkillEntity{
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
Name: "pdf", Status: types.SkillStatusInstalling, InstallingSince: &staleSince,
})
fx.installed("sk-2", "snap-old", "")
fx.installed("sk-1", "snap-new", "snap-old")
fx.live("snap-new")
n, err := fx.svc.ReapStuckRuns(context.Background())
require.NoError(t, err)
require.Equal(t, 1, n)
got := fx.skills.mustGet("sk-1")
require.Equal(t, types.SkillStatusReady, got.Status,
"failing this row would hide a skill from the agent that the image really carries")
require.Empty(t, got.Error)
require.Equal(t, "snap-new", got.InstalledSnapshotID,
"the snapshot the install never got to record is recoverable from the ledger")
}
func TestReconcileSnapshotsWarnsExtrasWithoutDeleting(t *testing.T) {
fx := newReaperFixture(t)
require.NoError(t, fx.skills.CreateSnapshotRow(context.Background(), &types.TenantSkillSnapshotEntity{
ID: "row-1", TenantID: 7, SandboxConfigID: "cfg-1",
SnapshotID: "snap-ledger", State: types.SkillSnapshotStateActive,
}))
fx.provider.listed = []sandbox.RemoteSnapshotRef{
{ID: "snap-ledger"},
{ID: "snap-orphan"},
}
n, err := fx.svc.ReconcileSnapshots(context.Background(), 7, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n, "the provider snapshot missing from the ledger is the extra")
require.Equal(t, []string{""}, fx.provider.listCalls,
"an empty sandboxID lists the whole account so extras from other environments are visible")
require.Empty(t, fx.provider.deleted,
"extras are only warned; the same provider account may be shared across environments")
}
func TestTenantSkillServiceStartIsIdempotent(t *testing.T) {
svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
require.NoError(t, svc.Start(context.Background()))
require.NoError(t, svc.Start(context.Background()),
"repeated Start must be a no-op so container wiring does not coordinate ordering")
svc.Stop()
svc.Stop()
}
type reaperFixture struct {
svc *TenantSkillService
skills *reaperSkillStore
configs *reaperConfigStore
provider *reaperSnapshotProvider
now time.Time
}
func newReaperFixture(t *testing.T) *reaperFixture {
t.Helper()
now := time.Date(2026, 8, 20, 12, 0, 0, 0, time.UTC)
skills := &reaperSkillStore{rows: map[string]*types.TenantSkillEntity{}}
configs := &reaperConfigStore{
entity: &types.TenantSandboxConfigEntity{
ID: "cfg-1", TenantID: 7,
Config: &types.TenantSandboxConfig{
SkillImage: &types.SkillImageConfig{SnapshotID: "snap-other"},
},
},
}
provider := &reaperSnapshotProvider{}
svc := NewTenantSkillService(
skills, configs, nil, &reaperSandboxResolver{provider: provider},
nil, nil, nil, nil, nil, nil, nil, nil,
)
svc.now = func() time.Time { return now }
return &reaperFixture{svc: svc, skills: skills, configs: configs, provider: provider, now: now}
}
// installed and removed write the ledger row an install or a removal leaves
// behind: the generation that changed the image, and the one it grew from.
func (f *reaperFixture) installed(skillID, snapshotID, parentSnapshotID string) {
f.snapshotRow(skillID, snapshotID, parentSnapshotID, types.SkillSnapshotTriggerInstall)
}
func (f *reaperFixture) removed(skillID, snapshotID, parentSnapshotID string) {
f.snapshotRow(skillID, snapshotID, parentSnapshotID, types.SkillSnapshotTriggerRemove)
}
func (f *reaperFixture) snapshotRow(skillID, snapshotID, parentSnapshotID, trigger string) {
f.skills.snapshots = append(f.skills.snapshots, &types.TenantSkillSnapshotEntity{
ID: "row-" + snapshotID, TenantID: 7, SandboxConfigID: "cfg-1", SkillID: skillID,
SnapshotID: snapshotID, ParentSnapshotID: parentSnapshotID,
Trigger: trigger, State: types.SkillSnapshotStateActive,
})
}
// live points the config at a snapshot, the way an install's pointer switch
// does.
func (f *reaperFixture) live(snapshotID string) {
f.configs.entity.Config.SkillImage = &types.SkillImageConfig{SnapshotID: snapshotID}
}
var (
_ skillReaperStore = (*reaperSkillStore)(nil)
_ skillSnapshotLedger = (*reaperSkillStore)(nil)
_ skillReaperConfigReader = (*reaperConfigStore)(nil)
_ sandboxConfigEnumerator = (*reaperConfigStore)(nil)
_ sandbox.TenantSandboxResolver = (*reaperSandboxResolver)(nil)
_ skillSnapshotLister = (*reaperSnapshotProvider)(nil)
)
type reaperSkillStore struct {
rows map[string]*types.TenantSkillEntity
snapshots []*types.TenantSkillSnapshotEntity
}
func (r *reaperSkillStore) put(e *types.TenantSkillEntity) {
cp := *e
r.rows[e.ID] = &cp
}
func (r *reaperSkillStore) mustGet(id string) *types.TenantSkillEntity {
return r.rows[id]
}
func (r *reaperSkillStore) ListStaleInstalling(
_ context.Context, olderThan time.Time,
) ([]*types.TenantSkillEntity, error) {
var out []*types.TenantSkillEntity
for _, e := range r.rows {
if e.InstallingSince == nil || !e.InstallingSince.Before(olderThan) {
continue
}
if e.Status != types.SkillStatusInstalling && e.Status != types.SkillStatusRemoving {
continue
}
cp := *e
out = append(out, &cp)
}
return out, nil
}
func (r *reaperSkillStore) GetSkill(
_ context.Context, tenantID uint64, configID, skillID string,
) (*types.TenantSkillEntity, error) {
e := r.rows[skillID]
if e == nil || e.TenantID != tenantID || e.SandboxConfigID != configID {
return nil, nil
}
cp := *e
return &cp, nil
}
func (r *reaperSkillStore) UpdateSkill(_ context.Context, e *types.TenantSkillEntity) error {
cp := *e
r.rows[e.ID] = &cp
return nil
}
func (r *reaperSkillStore) ListSnapshotsByConfig(
_ context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillSnapshotEntity, error) {
var out []*types.TenantSkillSnapshotEntity
for _, e := range r.snapshots {
if e.TenantID == tenantID && e.SandboxConfigID == configID {
cp := *e
out = append(out, &cp)
}
}
return out, nil
}
func (r *reaperSkillStore) CreateSkill(context.Context, *types.TenantSkillEntity) error {
panic("CreateSkill is outside the reaper surface")
}
func (r *reaperSkillStore) GetSkillByName(context.Context, uint64, string, string) (*types.TenantSkillEntity, error) {
panic("GetSkillByName is outside the reaper surface")
}
func (r *reaperSkillStore) ListSkillsByConfig(context.Context, uint64, string) ([]*types.TenantSkillEntity, error) {
panic("ListSkillsByConfig is outside the reaper surface")
}
func (r *reaperSkillStore) DeleteSkill(_ context.Context, tenantID uint64, configID, skillID string) error {
e := r.rows[skillID]
if e == nil || e.TenantID != tenantID || e.SandboxConfigID != configID {
return nil
}
delete(r.rows, skillID)
return nil
}
func (r *reaperSkillStore) CreateSnapshotRow(_ context.Context, e *types.TenantSkillSnapshotEntity) error {
cp := *e
r.snapshots = append(r.snapshots, &cp)
return nil
}
func (r *reaperSkillStore) MarkSnapshotState(
context.Context, uint64, string, string, string,
) error {
panic("MarkSnapshotState is outside the reaper surface")
}
func (r *reaperSkillStore) DeleteSnapshotRowsByConfig(context.Context, uint64, string) error {
panic("DeleteSnapshotRowsByConfig is outside the reaper surface")
}
type reaperConfigStore struct {
entity *types.TenantSandboxConfigEntity
}
func (r *reaperConfigStore) GetByID(
_ context.Context, tenantID uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
if r.entity == nil || r.entity.TenantID != tenantID || r.entity.ID != id {
return nil, nil
}
cp := *r.entity
return &cp, nil
}
func (r *reaperConfigStore) ListAll(_ context.Context) ([]*types.TenantSandboxConfigEntity, error) {
if r.entity == nil {
return nil, nil
}
cp := *r.entity
return []*types.TenantSandboxConfigEntity{&cp}, nil
}
func (r *reaperConfigStore) Create(context.Context, *types.TenantSandboxConfigEntity) error {
panic("Create is outside the reaper surface")
}
func (r *reaperConfigStore) ListByTenant(context.Context, uint64) ([]*types.TenantSandboxConfigEntity, error) {
panic("ListByTenant is outside the reaper surface")
}
func (r *reaperConfigStore) Update(context.Context, *types.TenantSandboxConfigEntity) error {
panic("Update is outside the reaper surface")
}
func (r *reaperConfigStore) SoftDelete(context.Context, uint64, string) error {
panic("SoftDelete is outside the reaper surface")
}
func (r *reaperConfigStore) SetCordon(context.Context, uint64, string, time.Time) error {
panic("SetCordon is outside the reaper surface")
}
func (r *reaperConfigStore) ClearCordon(context.Context, uint64, string) error {
panic("ClearCordon is outside the reaper surface")
}
type reaperSandboxResolver struct {
provider *reaperSnapshotProvider
}
func (r *reaperSandboxResolver) Resolve(context.Context, uint64, string) (sandbox.Manager, error) {
return r.provider, nil
}
// reaperSnapshotProvider is a Manager that can list and delete snapshots so a
// test can prove ReconcileSnapshots never type-asserts its way into a delete.
type reaperSnapshotProvider struct {
listed []sandbox.RemoteSnapshotRef
listCalls []string
deleted []string
}
func (p *reaperSnapshotProvider) ListSnapshots(
_ context.Context, sandboxID string,
) ([]sandbox.RemoteSnapshotRef, error) {
p.listCalls = append(p.listCalls, sandboxID)
return p.listed, nil
}
func (p *reaperSnapshotProvider) DeleteSnapshot(_ context.Context, snapshotID string) error {
p.deleted = append(p.deleted, snapshotID)
return nil
}
func (p *reaperSnapshotProvider) CreateSnapshot(context.Context, string, string) (sandbox.RemoteSnapshotRef, error) {
panic("CreateSnapshot is outside the reaper surface")
}
func (p *reaperSnapshotProvider) Execute(context.Context, *sandbox.ExecuteConfig) (*sandbox.ExecuteResult, error) {
return &sandbox.ExecuteResult{ExitCode: 0}, nil
}
func (p *reaperSnapshotProvider) Cleanup(context.Context) error { return nil }
func (p *reaperSnapshotProvider) GetSandbox() sandbox.Sandbox { return nil }
func (p *reaperSnapshotProvider) GetType() sandbox.SandboxType { return sandbox.SandboxTypeE2B }

View File

@ -132,9 +132,10 @@ func (s *TenantSkillService) runRemove(
return fmt.Errorf("sandbox config %s not found", configID)
}
// A skill that never made it into any image needs no sandbox at all.
// A skill that never made it into any image needs no sandbox at all, and
// no live sandbox can be out of date over a skill it never carried.
if currentSnapshotID(cfgEntity) == "" {
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
return s.finishRemoval(cleanupBase, tenantID, configID, skillID, false)
}
// Everything below either creates provider resources or moves the image
@ -163,7 +164,7 @@ func (s *TenantSkillService) runRemove(
// No new ledger row exists to keep active: nothing points at a
// snapshot any more.
s.markPreviousSnapshotsSuperseded(ctx, tenantID, configID, "")
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
return s.finishRemoval(cleanupBase, tenantID, configID, skillID, true)
}
// Remaining skills still live in the current snapshot, so it must be an
@ -253,7 +254,7 @@ func (s *TenantSkillService) runRemove(
}
imageChanged = true
s.markPreviousSnapshotsSuperseded(ctx, tenantID, configID, removeRowID)
return s.finishRemoval(cleanupBase, tenantID, configID, skillID)
return s.finishRemoval(cleanupBase, tenantID, configID, skillID, true)
}
// removeSkillDirectory wipes one skill's tree from the image. The per-skill
@ -383,7 +384,7 @@ func (s *TenantSkillService) clearImagePointer(
// removal: the files are gone and re-running the whole flow to fix a row would
// be absurd.
func (s *TenantSkillService) finishRemoval(
cleanupBase context.Context, tenantID uint64, configID, skillID string,
cleanupBase context.Context, tenantID uint64, configID, skillID string, imageChanged bool,
) error {
ctx, cancel := s.cleanupContext(cleanupBase)
defer cancel()
@ -412,7 +413,13 @@ func (s *TenantSkillService) finishRemoval(
if skill != nil && skill.BundleRef != "" {
s.deleteBundleBestEffort(ctx, tenantID, skill.BundleRef)
}
s.markConfigSandboxesStale(ctx, tenantID, configID)
// Only an image that actually changed can leave a bound sandbox out of
// date. Marking after a removal that moved no pointer would destroy and
// rebuild every live sandbox of the config - throwing away each session's
// /workspace scratch - for a change no sandbox can observe.
if imageChanged {
s.markConfigSandboxesStale(ctx, tenantID, configID)
}
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{
Percent: 100, Stage: "done", Status: "removed",
})

View File

@ -97,8 +97,9 @@ func TestRunRemoveFallsBackToBaseTemplateWhenNoSkillsRemain(t *testing.T) {
require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID,
"an image with no skills left is just the base template; do not spend a snapshot on it")
require.Equal(t, []string{"switch-pointer"}, fx.events,
"clearing the pointer is the whole job: no sandbox is started, so none is billed")
require.Equal(t, []string{"switch-pointer", "mark-stale"}, fx.events,
"no sandbox is started, so none is billed - but the sessions holding one must "+
"still rebuild from the base template")
require.Empty(t, fx.commands)
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
@ -189,7 +190,11 @@ func TestRunRemoveClearsTheLastSkillWhenCredentialsRotated(t *testing.T) {
require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID,
"the last skill can fall back to the base template without booting the unreadable snapshot")
require.Equal(t, []string{"switch-pointer"}, fx.events)
// The bindings are marked now that markConfigSandboxesStale does the work
// its placeholder described. It matters most here: those sandboxes run on a
// snapshot the live credentials can no longer resolve, so leaving them bound
// keeps them on an image nothing can rebuild.
require.Equal(t, []string{"switch-pointer", "mark-stale"}, fx.events)
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Nil(t, skill)

View File

@ -7,6 +7,7 @@ import (
"time"
"github.com/redis/go-redis/v9"
"github.com/robfig/cron/v3"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/common/redislock"
@ -39,6 +40,12 @@ type TenantSkillService struct {
models interfaces.ModelService
redis *redis.Client
// streams and messages are the two halves of an install transcript: the
// replayable event log the console tails, and the durable rows it falls
// back to once the log's TTL has passed.
streams interfaces.StreamManager
messages interfaces.MessageRepository
now func() time.Time
// cleanupTimeout bounds one piece of compensating work. Injectable so a
@ -48,6 +55,10 @@ type TenantSkillService struct {
// localLocks serialises installs when Redis is absent. It only guards this
// process; multi-replica deployments require Redis for cross-process safety.
localLocks *keyedMutex
cron *cron.Cron
cronMu sync.Mutex
started bool
}
// NewTenantSkillService wires the repositories and runtimes the install and
@ -64,6 +75,8 @@ func NewTenantSkillService(
sessions interfaces.SessionService,
models interfaces.ModelService,
redisClient *redis.Client,
streams interfaces.StreamManager,
messages interfaces.MessageRepository,
) *TenantSkillService {
return &TenantSkillService{
skills: skillsRepo,
@ -76,9 +89,14 @@ func NewTenantSkillService(
sessions: sessions,
models: models,
redis: redisClient,
streams: streams,
messages: messages,
now: time.Now,
cleanupTimeout: installCleanupTimeout,
localLocks: newKeyedMutex(),
cron: cron.New(cron.WithSeconds(), cron.WithChain(
cron.Recover(cron.DefaultLogger),
)),
}
}

View File

@ -22,7 +22,7 @@ func TestSkillImageLockKeyIncludesTheTenant(t *testing.T) {
}
func TestTenantSkillServiceWithConfigLockLocalRespectsCanceledContext(t *testing.T) {
svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
svc := NewTenantSkillService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
entered := make(chan struct{})
releaseHolder := make(chan struct{})
holderDone := make(chan error, 1)

View File

@ -0,0 +1,130 @@
package service
import (
"context"
"errors"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
var errInvalidateBoom = errors.New("binding store unavailable")
func TestRunInstallMarksBoundSandboxesStaleAfterThePointerSwitch(t *testing.T) {
fx := newInstallFixture(t)
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
require.Equal(t, []staleMark{{tenantID: 7, configID: "cfg-1"}}, fx.staleMarks,
"an open session would otherwise keep serving the previous image forever")
require.Less(t,
indexOfEvent(fx.events, "switch-pointer"), indexOfEvent(fx.events, "mark-stale"),
"marking before the pointer moved would rebuild sandboxes on the OLD image")
}
func TestRunRemoveMarksBoundSandboxesStaleAfterThePointerSwitch(t *testing.T) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 3)
fx.seedInstalledSkill("sk-2", "snap-old", 3)
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
require.Equal(t, []staleMark{{tenantID: 7, configID: "cfg-1"}}, fx.staleMarks)
require.Less(t,
indexOfEvent(fx.events, "switch-pointer"), indexOfEvent(fx.events, "mark-stale"))
}
// The base-template fallback moves the pointer without taking a snapshot, so
// the image every session boots really did change and the bound sandboxes have
// to rebuild.
func TestRunRemoveMarksBoundSandboxesStaleWhenTheImageFallsBackToTheBaseTemplate(
t *testing.T,
) {
fx := newInstallFixture(t)
fx.seedInstalledSkill("sk-1", "snap-old", 3)
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
require.Empty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID)
require.Equal(t, []staleMark{{tenantID: 7, configID: "cfg-1"}}, fx.staleMarks,
"the pointer moved to the base template, so every bound sandbox boots the wrong image")
}
// Removing a skill that never reached an image changes no image: there is no
// snapshot to grow from and no pointer write happens. Marking here would
// destroy and rebuild every live sandbox of the config - throwing away each
// session's /workspace scratch - for a change no sandbox can observe.
func TestRunRemoveDoesNotMarkSandboxesStaleWhenTheImageNeverHadTheSkill(t *testing.T) {
fx := newInstallFixture(t)
// The row has to be the one this run owns, the way RemoveSkill leaves it
// before queueing the run. Without that, removeStillOwnsTheRow reads a row
// still marked installing and declines to touch a newer upload's work.
require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",
func(e *types.TenantSkillEntity) { e.Status = types.SkillStatusRemoving }))
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Nil(t, skill, "the removal still completes: the row and its bundle go")
require.Empty(t, fx.staleMarks,
"no pointer write happened, so no live sandbox is out of date")
}
// The pointer has already moved by the time marking runs. A binding that could
// not be marked is a session serving a stale image until it ends - an
// annoyance, not a corruption - so it must never turn a finished install into a
// failed one.
func TestMarkingStaleSandboxesFailureLeavesTheInstallSuccessful(t *testing.T) {
fx := newInstallFixture(t)
fx.invalidateErr = errInvalidateBoom
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
require.NoError(t, err)
require.Equal(t, types.SkillStatusReady, skill.Status)
require.Empty(t, skill.Error)
require.Equal(t, "snap-1", fx.configRepo.saved.Config.SkillImage.SnapshotID,
"the image the install produced stays the one every new session boots")
}
// Marking runs past the point of no return, so it must not inherit the
// cancellation of whatever it compensates for: withConfigLock cancels the
// install context the moment lock renewal fails, and the binding store's writes
// are ordinary Redis calls that a dead context fails.
func TestMarkConfigSandboxesStaleRunsOnADetachedContext(t *testing.T) {
fx := newInstallFixture(t)
ctx, cancel := context.WithCancel(context.Background())
cancel()
fx.svc.markConfigSandboxesStale(ctx, 7, "cfg-1")
require.Equal(t, []staleMark{{tenantID: 7, configID: "cfg-1"}}, fx.staleMarks,
"the sandbox fake refuses a cancelled context, exactly as Redis would")
}
func TestMarkConfigSandboxesStaleSkipsWhenRolloutIsNewSession(t *testing.T) {
fx := newInstallFixture(t)
fx.configRepo.entity.Config.SkillRollout = types.SkillRolloutNewSession
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
require.Empty(t, fx.staleMarks,
"new_session rollout must not rebuild sandboxes already bound to a session")
require.Equal(t, "snap-1", fx.configRepo.saved.Config.SkillImage.SnapshotID,
"new sessions still boot the image this install produced")
}
func TestRunRemoveSkipsStaleMarkWhenRolloutIsNewSession(t *testing.T) {
fx := newInstallFixture(t)
fx.configRepo.entity.Config.SkillRollout = types.SkillRolloutNewSession
fx.seedInstalledSkill("sk-1", "snap-old", 3)
fx.seedInstalledSkill("sk-2", "snap-old", 3)
require.NoError(t, fx.svc.runRemove(context.Background(), 7, "cfg-1", "sk-1"))
require.Empty(t, fx.staleMarks)
require.NotEmpty(t, fx.configRepo.saved.Config.SkillImage.SnapshotID)
}

View File

@ -0,0 +1,449 @@
package service
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/google/uuid"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// installTranscript records one installer conversation.
//
// It is the installer's counterpart to handler/session.AgentStreamHandler, not
// a copy of it: that type lives above the service layer (it needs the artifact
// collector), so importing it here would close an import cycle. The overlap is
// bounded on purpose — install mode registers only shell_exec, so the six
// events below are all an install can produce, and references, memories,
// reflection, tool approvals and MCP OAuth are unreachable.
//
// The event shapes deliberately mirror AgentStreamHandler's so the console can
// render an install with the same components it renders a chat turn with.
type installTranscript struct {
// ctx is the run's context, kept for logging and for writes that outlive
// the emitting goroutine. Every write here is best-effort.
ctx context.Context
bus *event.EventBus
streams interfaces.StreamManager
messages interfaces.MessageRepository
sessionID string
assistantMessageID string
mu sync.Mutex
message *types.Message
answers []*installAnswerSegment
starts map[string]time.Time
finished bool
}
// installAnswerSegment accumulates the prose streamed under one final-answer
// event ID.
//
// The engine has no separate channel for a round's commentary: "the venv is
// missing, so I'll create it" arrives as a final-answer chunk exactly like the
// closing summary does. An install runs dozens of rounds, so keeping every
// chunk would persist dozens of preambles glued end to end. A round that goes
// on to call a tool was, by definition, not the last one, so its prose is
// retracted when that call arrives and only the round that ends the run
// survives as the answer.
type installAnswerSegment struct {
id string
content string
superseded bool
}
func newInstallTranscript(
ctx context.Context,
bus *event.EventBus,
streams interfaces.StreamManager,
messages interfaces.MessageRepository,
sessionID, assistantMessageID string,
) *installTranscript {
return &installTranscript{
ctx: ctx,
bus: bus,
streams: streams,
messages: messages,
sessionID: sessionID,
assistantMessageID: assistantMessageID,
starts: map[string]time.Time{},
}
}
// Create writes the two rows the conversation needs before the engine starts.
//
// The assistant row cannot wait until the run ends: /sessions/continue-stream
// validates the message before it opens the stream, so a console that attaches
// while the install is running would be refused.
func (tr *installTranscript) Create(ctx context.Context, prompt string) error {
if tr == nil || tr.messages == nil {
return nil
}
now := time.Now()
if _, err := tr.messages.CreateMessage(ctx, &types.Message{
ID: uuid.NewString(),
SessionID: tr.sessionID,
Role: "user",
Content: prompt,
IsCompleted: true,
CreatedAt: now,
UpdatedAt: now,
}); err != nil {
return fmt.Errorf("create installer prompt message: %w", err)
}
assistant := &types.Message{
ID: tr.assistantMessageID,
SessionID: tr.sessionID,
Role: "assistant",
CreatedAt: now.Add(time.Millisecond),
UpdatedAt: now.Add(time.Millisecond),
}
if _, err := tr.messages.CreateMessage(ctx, assistant); err != nil {
return fmt.Errorf("create installer answer message: %w", err)
}
tr.mu.Lock()
tr.message = assistant
tr.mu.Unlock()
// The prompt goes into the event log too, ahead of everything the agent
// does, so one replay of the log is the whole conversation. Without it a
// console following a running install would show the agent's side of a
// conversation whose opening line it cannot see.
tr.append(interfaces.StreamEvent{
ID: uuid.NewString(),
Type: types.ResponseTypeInstallPrompt,
Content: prompt,
Done: true,
Timestamp: now,
Data: map[string]interface{}{},
})
return nil
}
// Subscribe wires the six events an install can produce.
func (tr *installTranscript) Subscribe() {
if tr == nil || tr.bus == nil {
return
}
tr.bus.On(event.EventAgentThought, tr.onThought)
tr.bus.On(event.EventAgentToolCall, tr.onToolCall)
tr.bus.On(event.EventAgentToolResult, tr.onToolResult)
tr.bus.On(event.EventAgentFinalAnswer, tr.onAnswer)
tr.bus.On(event.EventError, tr.onError)
tr.bus.On(event.EventAgentComplete, tr.onComplete)
}
// Finish closes the record. runErr is the engine's verdict: the engine emits
// no complete event when it fails, and a failed install is the one people
// actually come to read, so the failure is written here rather than hoped for.
func (tr *installTranscript) Finish(ctx context.Context, runErr error) {
if tr == nil {
return
}
if runErr != nil {
tr.append(interfaces.StreamEvent{
ID: uuid.NewString(),
Type: types.ResponseTypeError,
Content: runErr.Error(),
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{
"stage": "install",
"error": runErr.Error(),
},
})
tr.mu.Lock()
// The verdict is never a preamble, so it gets its own segment that no
// later call can retract.
failure := tr.segmentLocked("install-failure")
if prose := tr.composeAnswerLocked(); prose != "" {
failure.content = "\n\n"
}
failure.content += runErr.Error()
tr.mu.Unlock()
}
tr.mu.Lock()
alreadyComplete := tr.finished
tr.finished = true
tr.mu.Unlock()
if !alreadyComplete {
tr.append(interfaces.StreamEvent{
ID: uuid.NewString(),
Type: types.ResponseTypeComplete,
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{},
})
}
tr.save(ctx)
}
func (tr *installTranscript) onThought(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentThoughtData)
if !ok {
return nil
}
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeThinking,
Content: data.Content,
Done: data.Done,
Timestamp: time.Now(),
Data: tr.spanMeta(evt.ID, data.Done),
})
return nil
}
func (tr *installTranscript) onToolCall(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentToolCallData)
if !ok {
return nil
}
tr.mu.Lock()
tr.starts[data.ToolCallID] = time.Now()
// This round called a tool, so it is not the round that ends the run: any
// prose it streamed was a preamble and must not reach Message.Content.
for _, seg := range tr.answers {
if !seg.superseded && seg.content != "" {
seg.superseded = true
}
}
tr.mu.Unlock()
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeToolCall,
Content: fmt.Sprintf("Calling tool: %s", data.ToolName),
Timestamp: time.Now(),
Data: map[string]interface{}{
"tool_name": data.ToolName,
"arguments": data.Arguments,
"tool_call_id": data.ToolCallID,
},
})
return nil
}
func (tr *installTranscript) onToolResult(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentToolResultData)
if !ok {
return nil
}
tr.mu.Lock()
durationMs := data.Duration
if start, ok := tr.starts[data.ToolCallID]; ok {
durationMs = time.Since(start).Milliseconds()
delete(tr.starts, data.ToolCallID)
}
tr.mu.Unlock()
// A failed command is surfaced as an error, matching the chat path, so the
// console highlights it instead of filing it as one more quiet step.
responseType := types.ResponseTypeToolResult
content := agenttools.StreamContentForToolResult(data.ToolName, data.Success, data.Error, data.Data)
if !data.Success {
responseType = types.ResponseTypeError
if content == "" && data.Error != "" {
content = data.Error
}
}
meta := map[string]interface{}{
"tool_name": data.ToolName,
"success": data.Success,
"error": data.Error,
"duration_ms": durationMs,
"tool_call_id": data.ToolCallID,
}
for k, v := range agenttools.SanitizeToolResultForClient(data.ToolName, &types.ToolResult{
Success: data.Success,
Output: data.Output,
Error: data.Error,
Data: data.Data,
}) {
meta[k] = v
}
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: responseType,
Content: content,
Timestamp: time.Now(),
Data: meta,
})
return nil
}
func (tr *installTranscript) onAnswer(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
tr.mu.Lock()
if data.Content != "" {
tr.segmentLocked(evt.ID).content += data.Content
}
tr.mu.Unlock()
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeAnswer,
Content: data.Content,
Done: data.Done,
Timestamp: time.Now(),
Data: tr.spanMeta(evt.ID, data.Done),
})
return nil
}
func (tr *installTranscript) onError(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.ErrorData)
if !ok {
return nil
}
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeError,
Content: data.Error,
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{
"stage": data.Stage,
"error": data.Error,
},
})
return nil
}
func (tr *installTranscript) onComplete(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentCompleteData)
if !ok {
return nil
}
tr.mu.Lock()
tr.finished = true
if data.MessageID == tr.assistantMessageID {
msg := tr.ensureMessageLocked()
msg.IsCompleted = true
msg.AgentDurationMs = data.TotalDurationMs
if steps, ok := data.AgentSteps.([]types.AgentStep); ok {
msg.AgentSteps = agenttools.SanitizeAgentStepsForStorage(steps)
}
}
// The engine may finish without ever streaming an answer chunk (it stops
// naturally with plain text). Take the summary from the completion payload
// so the transcript is not left with an empty final message.
if tr.composeAnswerLocked() == "" && data.FinalAnswer != "" {
tr.segmentLocked(evt.ID).content = data.FinalAnswer
}
tr.mu.Unlock()
tr.append(interfaces.StreamEvent{
ID: evt.ID,
Type: types.ResponseTypeComplete,
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{
"total_steps": data.TotalSteps,
"total_duration_ms": data.TotalDurationMs,
},
})
return nil
}
// spanMeta mirrors the chat path's per-chunk metadata so the console can group
// chunks by event ID and show a duration once the span closes.
func (tr *installTranscript) spanMeta(eventID string, done bool) map[string]interface{} {
tr.mu.Lock()
defer tr.mu.Unlock()
if _, ok := tr.starts[eventID]; !ok {
tr.starts[eventID] = time.Now()
}
if !done {
return map[string]interface{}{"event_id": eventID}
}
start := tr.starts[eventID]
delete(tr.starts, eventID)
return map[string]interface{}{
"event_id": eventID,
"duration_ms": time.Since(start).Milliseconds(),
"completed_at": time.Now().Unix(),
}
}
// segmentLocked returns the segment accumulating an answer event ID, creating
// it on first sight. Callers must hold tr.mu.
func (tr *installTranscript) segmentLocked(id string) *installAnswerSegment {
for _, seg := range tr.answers {
if seg.id == id {
return seg
}
}
seg := &installAnswerSegment{id: id}
tr.answers = append(tr.answers, seg)
return seg
}
// composeAnswerLocked rebuilds the answer from the segments no tool call
// retracted, in arrival order. Callers must hold tr.mu.
func (tr *installTranscript) composeAnswerLocked() string {
var b strings.Builder
for _, seg := range tr.answers {
if !seg.superseded {
b.WriteString(seg.content)
}
}
return b.String()
}
func (tr *installTranscript) append(evt interfaces.StreamEvent) {
if tr.streams == nil {
return
}
if err := tr.streams.AppendEvent(tr.ctx, tr.sessionID, tr.assistantMessageID, evt); err != nil {
logger.Warnf(tr.ctx, "[skill] append %s to install transcript %s failed: %v",
evt.Type, tr.sessionID, err)
}
}
// ensureMessageLocked returns the assistant row being accumulated, creating the
// in-memory shell if Create never ran (a transcript whose seeding failed still
// records what it can). Callers must hold tr.mu.
func (tr *installTranscript) ensureMessageLocked() *types.Message {
if tr.message == nil {
tr.message = &types.Message{
ID: tr.assistantMessageID,
SessionID: tr.sessionID,
Role: "assistant",
CreatedAt: time.Now(),
}
}
return tr.message
}
func (tr *installTranscript) save(ctx context.Context) {
if tr.messages == nil {
return
}
tr.mu.Lock()
msg := tr.ensureMessageLocked()
msg.Content = tr.composeAnswerLocked()
msg.IsCompleted = true
msg.UpdatedAt = time.Now()
tr.mu.Unlock()
if err := tr.messages.UpdateMessage(ctx, msg); err != nil {
logger.Warnf(ctx, "[skill] persist install transcript %s failed: %v", tr.sessionID, err)
}
}

View File

@ -0,0 +1,267 @@
package service
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// transcriptStreams records what the installer projects onto the replayable
// stream, in order, so a test can state the shape the console will read.
type transcriptStreams struct {
events []interfaces.StreamEvent
err error
}
func (s *transcriptStreams) AppendEvent(
_ context.Context, _, _ string, evt interfaces.StreamEvent,
) error {
s.events = append(s.events, evt)
return s.err
}
func (s *transcriptStreams) GetEvents(
_ context.Context, _, _ string, from int,
) ([]interfaces.StreamEvent, int, error) {
return s.events[from:], len(s.events), nil
}
func (s *transcriptStreams) types() []types.ResponseType {
out := make([]types.ResponseType, 0, len(s.events))
for _, evt := range s.events {
out = append(out, evt.Type)
}
return out
}
// transcriptMessages is the durable half. Only the two calls the transcript
// makes are implemented; the rest panic so an accidental new dependency on the
// repository surfaces as a test failure rather than a silent nil write.
type transcriptMessages struct {
interfaces.MessageRepository
created []*types.Message
updated []*types.Message
err error
}
func (m *transcriptMessages) CreateMessage(
_ context.Context, msg *types.Message,
) (*types.Message, error) {
m.created = append(m.created, msg)
return msg, m.err
}
func (m *transcriptMessages) UpdateMessage(_ context.Context, msg *types.Message) error {
m.updated = append(m.updated, msg)
return m.err
}
func newTranscriptForTest(t *testing.T) (
*installTranscript, *event.EventBus, *transcriptStreams, *transcriptMessages,
) {
t.Helper()
bus := event.NewEventBus()
streams := &transcriptStreams{}
messages := &transcriptMessages{}
tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1")
tr.Subscribe()
return tr, bus, streams, messages
}
func TestInstallTranscriptProjectsTheAgentsWork(t *testing.T) {
_, bus, streams, _ := newTranscriptForTest(t)
ctx := context.Background()
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "t-1", Type: event.EventAgentThought,
Data: event.AgentThoughtData{Content: "check for uv", Done: false},
}))
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "c-1", Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{
ToolName: "shell_exec", ToolCallID: "call-1",
Arguments: map[string]any{"command": "uv --version"},
},
}))
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "r-1", Type: event.EventAgentToolResult,
Data: event.AgentToolResultData{
ToolName: "shell_exec", ToolCallID: "call-1", Success: true, Output: "uv 0.4.0",
},
}))
require.Equal(t, []types.ResponseType{
types.ResponseTypeThinking,
types.ResponseTypeToolCall,
types.ResponseTypeToolResult,
}, streams.types())
call := streams.events[1]
require.Equal(t, "shell_exec", call.Data["tool_name"])
require.Equal(t, "call-1", call.Data["tool_call_id"])
}
// A failed command is the single most useful thing in an install transcript,
// so it must reach the stream as an error the console already knows how to
// render, not be dropped for having Success=false.
func TestInstallTranscriptReportsAFailedCommandAsAnError(t *testing.T) {
_, bus, streams, _ := newTranscriptForTest(t)
require.NoError(t, bus.Emit(context.Background(), event.Event{
ID: "r-1", Type: event.EventAgentToolResult,
Data: event.AgentToolResultData{
ToolName: "shell_exec", ToolCallID: "call-1",
Success: false, Error: "exit status 1",
},
}))
require.Equal(t, []types.ResponseType{types.ResponseTypeError}, streams.types())
require.Equal(t, "exit status 1", streams.events[0].Content)
require.Equal(t, false, streams.events[0].Data["success"])
}
func TestInstallTranscriptPersistsTheAnswerAndStepsOnComplete(t *testing.T) {
tr, bus, streams, messages := newTranscriptForTest(t)
ctx := context.Background()
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "a-1", Type: event.EventAgentFinalAnswer,
Data: event.AgentFinalAnswerData{Content: "installed ", Done: false},
}))
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "a-1", Type: event.EventAgentFinalAnswer,
Data: event.AgentFinalAnswerData{Content: "pdf-tools", Done: true},
}))
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "done", Type: event.EventAgentComplete,
Data: event.AgentCompleteData{
MessageID: "msg-1", TotalDurationMs: 4200, TotalSteps: 3,
},
}))
tr.Finish(ctx, nil)
require.Equal(t, types.ResponseTypeComplete, streams.types()[len(streams.types())-1])
require.Len(t, messages.updated, 1)
saved := messages.updated[0]
require.Equal(t, "installed pdf-tools", saved.Content)
require.True(t, saved.IsCompleted)
require.EqualValues(t, 4200, saved.AgentDurationMs)
}
// The engine routes a round's plain assistant prose through
// EventAgentFinalAnswer, so every "now I'll check X" preamble arrives as an
// answer chunk. Only the prose of the round that ends the run is the answer.
// Without retracting the preambles the persisted record is every round's
// commentary glued end to end, which is unreadable — and is what the console
// renders as the install's result.
func TestInstallTranscriptRetractsPreamblesSupersededByAToolCall(t *testing.T) {
tr, bus, _, messages := newTranscriptForTest(t)
ctx := context.Background()
emitAnswer := func(id, content string, done bool) {
require.NoError(t, bus.Emit(ctx, event.Event{
ID: id, Type: event.EventAgentFinalAnswer,
Data: event.AgentFinalAnswerData{Content: content, Done: done},
}))
}
emitAnswer("a-1", "The script needs duckduckgo-search, so I'll create the venv:", true)
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "c-1", Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{
ToolName: "shell_exec", ToolCallID: "call-1",
Arguments: map[string]any{"command": "uv venv .venv"},
},
}))
emitAnswer("a-2", "Installed successfully. Now verifying:", true)
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "c-2", Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{
ToolName: "shell_exec", ToolCallID: "call-2",
Arguments: map[string]any{"command": "python scripts/search.py --help"},
},
}))
emitAnswer("a-3", "Installed duckduckgo-search into the skill venv.", true)
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "done", Type: event.EventAgentComplete,
Data: event.AgentCompleteData{MessageID: "msg-1", TotalDurationMs: 900},
}))
tr.Finish(ctx, nil)
require.Len(t, messages.updated, 1)
require.Equal(t,
"Installed duckduckgo-search into the skill venv.",
messages.updated[0].Content,
"only the final round's prose is the answer; earlier preambles were retracted by their tool calls",
)
}
// An install that dies before the engine emits complete is exactly the run
// someone will come looking for, so Finish must close the record itself.
func TestInstallTranscriptRecordsAFailedRun(t *testing.T) {
tr, _, streams, messages := newTranscriptForTest(t)
tr.Finish(context.Background(), errors.New("installer agent failed: boom"))
require.Equal(t, []types.ResponseType{
types.ResponseTypeError,
types.ResponseTypeComplete,
}, streams.types())
require.Len(t, messages.updated, 1)
require.Contains(t, messages.updated[0].Content, "boom")
require.True(t, messages.updated[0].IsCompleted)
}
// The transcript is a troubleshooting aid. A broken Redis or a failing write
// must not be able to fail an otherwise good install.
func TestInstallTranscriptSwallowsItsOwnFailures(t *testing.T) {
bus := event.NewEventBus()
streams := &transcriptStreams{err: errors.New("redis down")}
messages := &transcriptMessages{err: errors.New("db down")}
tr := newInstallTranscript(context.Background(), bus, streams, messages, "sess-1", "msg-1")
tr.Subscribe()
require.NoError(t, bus.Emit(context.Background(), event.Event{
ID: "t-1", Type: event.EventAgentThought,
Data: event.AgentThoughtData{Content: "hi", Done: true},
}))
require.NotPanics(t, func() { tr.Finish(context.Background(), nil) })
}
func TestInstallTranscriptCreateSeedsTheAssistantRow(t *testing.T) {
streams := &transcriptStreams{}
messages := &transcriptMessages{}
tr := newInstallTranscript(
context.Background(), event.NewEventBus(), streams, messages, "sess-1", "msg-1",
)
require.NoError(t, tr.Create(context.Background(), "install pdf-tools"))
require.Len(t, messages.created, 2)
require.Equal(t, "user", messages.created[0].Role)
require.Equal(t, "install pdf-tools", messages.created[0].Content)
require.Equal(t, "assistant", messages.created[1].Role)
require.Equal(t, "msg-1", messages.created[1].ID)
require.Equal(t, "sess-1", messages.created[1].SessionID)
}
// A console that attaches to a running install reads the event log and nothing
// else, so the prompt has to be in the log or the run shows up as an agent
// answering a question nobody can see.
func TestInstallTranscriptCreateOpensTheLogWithThePrompt(t *testing.T) {
streams := &transcriptStreams{}
tr := newInstallTranscript(
context.Background(), event.NewEventBus(), streams, &transcriptMessages{}, "sess-1", "msg-1",
)
require.NoError(t, tr.Create(context.Background(), "install pdf-tools"))
require.Equal(t, []types.ResponseType{types.ResponseTypeInstallPrompt}, streams.types())
require.Equal(t, "install pdf-tools", streams.events[0].Content)
}

View File

@ -221,8 +221,10 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(func(
repo repository.TenantSandboxConfigRepository,
agents interfaces.CustomAgentRepository,
skills repository.TenantSkillRepository,
files interfaces.StorageBackendResolver,
) *service.TenantSandboxConfigService {
return service.NewTenantSandboxConfigService(repo, agents, buildGlobalSandboxConfig())
return service.NewTenantSandboxConfigService(repo, agents, buildGlobalSandboxConfig(), skills, files)
}))
must(container.Provide(func(s *service.TenantSandboxConfigService) service.WorkspaceSandboxPolicy {
return s
@ -376,6 +378,13 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipeline.NewPluginMemoryAffinity))
logger.Debugf(ctx, "[Container] Chat pipeline plugins registered")
// TenantSkillService is provided next to SessionService (handlers need
// it), but Invoke constructs the whole chain. SessionService needs
// *chatpipeline.EventManager, which only exists after the pipeline
// block above — starting the reaper any earlier panics.
must(container.Invoke(startTenantSkillReaper))
logger.Debugf(ctx, "[Container] Tenant skill reaper registered")
// HTTP handlers layer
logger.Debugf(ctx, "[Container] Registering HTTP handlers...")
must(container.Provide(handler.NewTenantHandler))
@ -392,6 +401,11 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewMessageSuggestionHandler))
must(container.Provide(handler.NewModelHandler))
must(container.Provide(handler.NewSandboxConfigHandler))
must(container.Provide(func(
s *service.TenantSkillService, streams interfaces.StreamManager,
) *handler.SandboxSkillHandler {
return handler.NewSandboxSkillHandler(s, streams)
}))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
must(container.Provide(handler.NewAuthHandler))
@ -409,7 +423,9 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewCustomAgentHandler))
must(container.Provide(handler.NewUserResourceFavoriteHandler))
must(container.Provide(service.NewSkillService))
must(container.Provide(handler.NewSkillHandler))
must(container.Provide(func(s *service.TenantSkillService) *handler.SkillHandler {
return handler.NewSkillHandler(s)
}))
must(container.Provide(handler.NewOrganizationHandler))
must(container.Provide(handler.NewMemoryHandler))
@ -1715,6 +1731,22 @@ func startHousekeepingService(svc *service.HousekeepingService, cleaner interfac
})
}
// startTenantSkillReaper starts the stuck-install / orphan-snapshot cron and
// registers cleanup. Best-effort: a startup error is logged but does NOT abort
// the container — the rest of the system stays usable.
func startTenantSkillReaper(svc *service.TenantSkillService, cleaner interfaces.ResourceCleaner) {
if svc == nil {
return
}
if err := svc.Start(context.Background()); err != nil {
logger.Warnf(context.Background(), "[Container] tenant skill reaper start failed: %v", err)
}
cleaner.RegisterWithName("TenantSkillReaper", func() error {
svc.Stop()
return nil
})
}
// startTemporaryDocumentCleanup removes expired session attachments and their
// extracted images. The durable expiry timestamp is the source of truth; the
// ticker only controls how quickly storage is reclaimed.

View File

@ -125,6 +125,17 @@ func respondSandboxInventoryUnverifiable(c *gin.Context) {
})
}
func respondSkillSnapshotReleaseFailed(c *gin.Context, remaining []string) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": gin.H{
"code": "skill_snapshot_release_failed",
"message": "无法销毁该配置下的技能快照,已中止删除以免快照继续计费",
"data": gin.H{"snapshot_ids": remaining},
},
})
}
func respondSandboxConfigCordoned(c *gin.Context) {
c.JSON(http.StatusLocked, gin.H{
"success": false,
@ -145,6 +156,15 @@ func respondSandboxConfigRefusal(c *gin.Context, err error) bool {
respondSandboxInventoryUnverifiable(c)
return true
}
var releaseErr *service.SkillSnapshotReleaseFailedError
if stderrors.As(err, &releaseErr) {
respondSkillSnapshotReleaseFailed(c, releaseErr.Remaining)
return true
}
if stderrors.Is(err, service.ErrSkillSnapshotReleaseFailed) {
respondSkillSnapshotReleaseFailed(c, nil)
return true
}
if stderrors.Is(err, repository.ErrSandboxConfigCordoned) {
respondSandboxConfigCordoned(c)
return true

View File

@ -106,6 +106,36 @@ func TestSandboxInventoryUnverifiableMapsToDistinct409(t *testing.T) {
require.Contains(t, payload.Error.Message, "无法连接")
}
func TestSkillSnapshotReleaseFailedMapsTo409WithRemaining(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.DELETE("/sandbox-configs/:id", func(c *gin.Context) {
if !respondSandboxConfigRefusal(c, &service.SkillSnapshotReleaseFailedError{
Remaining: []string{"snap-2"},
}) {
t.Fatal("expected snapshot release failure to map as a refusal")
}
})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, "/sandbox-configs/cfg-a", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusConflict, w.Code)
var payload struct {
Error struct {
Code string `json:"code"`
Data struct {
SnapshotIDs []string `json:"snapshot_ids"`
} `json:"data"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.Equal(t, "skill_snapshot_release_failed", payload.Error.Code)
require.Equal(t, []string{"snap-2"}, payload.Error.Data.SnapshotIDs)
}
func TestSandboxConfigDeletePassesForceQuery(t *testing.T) {
gin.SetMode(gin.TestMode)

View File

@ -0,0 +1,661 @@
package handler
import (
"context"
stderrors "errors"
"fmt"
"io"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/application/service"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
)
const (
// skillEventPollInterval is how often a live stream re-reads the durable
// status. It is not a nicety: a run can end without publishing anything
// (a duplicate removal returns early), and this poll is what ends the
// stream in that case.
skillEventPollInterval = 5 * time.Second
// skillEventMaxDuration bounds one stream. An install whose process died
// leaves the row at "installing" until the stuck-run reaper rewrites it,
// and a connection that waits for that forever is a leak, so the stream
// stops following and says so.
skillEventMaxDuration = 60 * time.Minute
// skillUploadEnvelopeSlack is the multipart framing allowed on top of the
// file itself, so the body cap refuses a genuinely oversized upload
// without rejecting a legal one for its boundary lines.
skillUploadEnvelopeSlack = 1 << 20
)
// sandboxSkillService is the skill surface the admin endpoints need. Reads and
// writes are workspace-scoped by the service; the progress calls are not, which
// is why every handler here resolves the skill for the caller's workspace first.
type sandboxSkillService interface {
ListSkills(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error)
GetSkill(ctx context.Context, tenantID uint64, configID, skillID string) (*types.TenantSkillEntity, error)
SetSkillEnabled(
ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
) (*types.TenantSkillEntity, error)
InstallSkill(ctx context.Context, tenantID uint64, configID string, archive []byte) (string, error)
RemoveSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
LastProgress(
ctx context.Context, tenantID uint64, configID, skillID string,
) (service.SkillProgress, bool)
SubscribeProgress(
ctx context.Context, tenantID uint64, configID, skillID string,
) (<-chan service.SkillProgress, func(), error)
}
// SandboxSkillHandler serves the agent-skill endpoints of one sandbox config.
type SandboxSkillHandler struct {
service sandboxSkillService
// streams replays the installer agent's own event log. It is the same
// manager the install writes through, and it may be nil in a deployment
// without Redis, which only costs the transcript endpoint.
streams interfaces.StreamManager
// pollInterval and maxDuration are fields rather than constants so a test
// can exercise a whole stream lifecycle without waiting minutes for it.
pollInterval time.Duration
maxDuration time.Duration
}
// NewSandboxSkillHandler constructs the admin HTTP surface for tenant skills.
func NewSandboxSkillHandler(
svc sandboxSkillService, streams interfaces.StreamManager,
) *SandboxSkillHandler {
return &SandboxSkillHandler{
service: svc,
streams: streams,
pollInterval: skillEventPollInterval,
maxDuration: skillEventMaxDuration,
}
}
// skillResponse is the outward projection of an installed skill. The SKILL.md
// body is deliberately omitted: it is level-2 disclosure for the agent, and a
// list of them would dwarf the response.
type skillResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version,omitempty"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
BundleSHA256 string `json:"bundle_sha256,omitempty"`
InstalledSnapshotID string `json:"installed_snapshot_id,omitempty"`
InstallSessionID string `json:"install_session_id,omitempty"`
InstallMessageID string `json:"install_message_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func toSkillResponse(e *types.TenantSkillEntity) skillResponse {
if e == nil {
return skillResponse{}
}
return skillResponse{
ID: e.ID,
Name: e.Name,
Version: e.Version,
Description: e.Description,
Enabled: e.Enabled,
Status: e.Status,
Error: e.Error,
BundleSHA256: e.BundleSHA256,
InstalledSnapshotID: e.InstalledSnapshotID,
InstallSessionID: e.InstallSessionID,
InstallMessageID: e.InstallMessageID,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
}
}
// respondSkillServiceError promotes every rejection of an uploaded archive to
// 400. It is matched as a sentinel rather than by message so a reworded
// validation error cannot silently start returning 500 for bad input.
func respondSkillServiceError(c *gin.Context, err error) {
if stderrors.Is(err, service.ErrSkillBundleInvalid) {
_ = c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
_ = c.Error(err)
}
// List godoc
// @Summary List installed skills
// @Description List the agent skills installed onto one sandbox config's image.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Success 200 {object} map[string]interface{} "Installed skills"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills [get]
func (h *SandboxSkillHandler) List(c *gin.Context) {
skills, err := h.service.ListSkills(c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
data := make([]skillResponse, 0, len(skills))
for _, skill := range skills {
data = append(data, toSkillResponse(skill))
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": data})
}
// Get godoc
// @Summary Get an installed skill
// @Description Retrieve one installed skill of a sandbox config.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param skillId path string true "Skill ID"
// @Success 200 {object} map[string]interface{} "Installed skill"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Skill not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills/{skillId} [get]
func (h *SandboxSkillHandler) Get(c *gin.Context) {
skill, err := h.resolveSkill(c)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": toSkillResponse(skill)})
}
// Upload godoc
// @Summary Install a skill
// @Description Upload a skill bundle. The install boots a sandbox from the
// @Description config's current image and runs for minutes, so the upload is
// @Description only accepted; follow it via the install-events stream.
// @Tags SandboxConfig
// @Accept multipart/form-data
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param file formData file true "Skill bundle (zip)"
// @Success 202 {object} map[string]interface{} "Install accepted"
// @Failure 400 {object} apperrors.AppError "Missing, oversized or invalid bundle"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills [post]
func (h *SandboxSkillHandler) Upload(c *gin.Context) {
maxBytes := secutils.GetMaxFileSize()
// The cap is applied to the body before it is parsed: multipart parsing
// buffers the whole request, spilling to temp files, so checking only the
// declared part size would let an unbounded body through first.
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes+skillUploadEnvelopeSlack)
file, header, err := c.Request.FormFile("file")
if err != nil {
var tooLarge *http.MaxBytesError
if stderrors.As(err, &tooLarge) {
_ = c.Error(skillTooLargeError())
return
}
_ = c.Error(apperrors.NewBadRequestError("file is required"))
return
}
defer func() { _ = file.Close() }()
if header.Size > maxBytes {
_ = c.Error(skillTooLargeError())
return
}
archive, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
if err != nil {
_ = c.Error(apperrors.NewBadRequestError("failed to read the uploaded skill bundle"))
return
}
// A multipart part may under-declare its size, so the bytes actually read
// are checked too.
if int64(len(archive)) > maxBytes {
_ = c.Error(skillTooLargeError())
return
}
skillID, err := h.service.InstallSkill(
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), archive,
)
if err != nil {
respondSkillServiceError(c, err)
return
}
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
}
func skillTooLargeError() error {
return apperrors.NewBadRequestError(
fmt.Sprintf("skill bundle cannot exceed %d MB", secutils.GetMaxFileSizeMB()))
}
type skillPatchRequest struct {
// Enabled is a pointer because its absence is a bad request rather than a
// request to disable the skill.
Enabled *bool `json:"enabled"`
}
// Patch godoc
// @Summary Update an installed skill
// @Description Show or hide an installed skill. The files stay in the image either way; removal is a separate flow.
// @Tags SandboxConfig
// @Accept json
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param skillId path string true "Skill ID"
// @Param request body skillPatchRequest true "Fields to update"
// @Success 200 {object} map[string]interface{} "Updated skill"
// @Failure 400 {object} apperrors.AppError "Invalid request"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Skill not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills/{skillId} [patch]
func (h *SandboxSkillHandler) Patch(c *gin.Context) {
var req skillPatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
if req.Enabled == nil {
_ = c.Error(apperrors.NewBadRequestError("enabled is required"))
return
}
updated, err := h.service.SetSkillEnabled(c.Request.Context(), sandboxConfigTenantID(c),
c.Param("id"), c.Param("skillId"), *req.Enabled)
if err != nil {
_ = c.Error(err)
return
}
if updated == nil {
_ = c.Error(apperrors.NewNotFoundError("skill not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": toSkillResponse(updated)})
}
// Delete godoc
// @Summary Remove an installed skill
// @Description Remove a skill from the config's image. The removal rebuilds
// @Description the image and runs for minutes, so it is only accepted; follow
// @Description it via the install-events stream.
// @Tags SandboxConfig
// @Produce json
// @Param id path string true "Sandbox config ID"
// @Param skillId path string true "Skill ID"
// @Success 202 {object} map[string]interface{} "Removal accepted"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Skill not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills/{skillId} [delete]
func (h *SandboxSkillHandler) Delete(c *gin.Context) {
skillID := c.Param("skillId")
err := h.service.RemoveSkill(
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), skillID,
)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
}
// skillInstallEvent is one frame of the install/removal stream. Done is carried
// explicitly so a client terminates on the flag rather than on a stage name it
// has to keep in sync with the server.
type skillInstallEvent struct {
Percent int `json:"percent"`
Stage string `json:"stage"`
Log string `json:"log,omitempty"`
Status string `json:"status,omitempty"`
Done bool `json:"done"`
}
// Terminal stages, as published by the service when a run reaches 100%.
const (
skillStageDone = "done"
skillStageFailed = "failed"
// skillStageDetached is the handler's own: the stream stopped following a
// run that is still in progress. It is not a verdict on the install.
skillStageDetached = "detached"
)
// skillStatusRemoved is the status a finished removal publishes. The row is
// gone by then, so it is also what a synthesized terminal event reports.
const skillStatusRemoved = "removed"
func skillEventFromProgress(p service.SkillProgress) skillInstallEvent {
return skillInstallEvent{
Percent: p.Percent,
Stage: p.Stage,
Log: p.Log,
Status: p.Status,
Done: p.Stage == skillStageDone || p.Stage == skillStageFailed,
}
}
// terminalSkillEvent derives an end-of-stream frame from the durable state, for
// every run that ends without publishing one: a duplicate removal returns
// early, and a run whose process died publishes nothing ever again. A nil skill
// is a finished removal — the row is deleted by the last step of one.
func terminalSkillEvent(skill *types.TenantSkillEntity) (skillInstallEvent, bool) {
if skill == nil {
return skillInstallEvent{
Percent: 100, Stage: skillStageDone, Status: skillStatusRemoved, Done: true,
}, true
}
switch skill.Status {
case types.SkillStatusInstalling, types.SkillStatusRemoving:
return skillInstallEvent{}, false
case types.SkillStatusFailed:
return skillInstallEvent{
Percent: 100, Stage: skillStageFailed, Status: skill.Status,
Log: skill.Error, Done: true,
}, true
default:
return skillInstallEvent{
Percent: 100, Stage: skillStageDone, Status: skill.Status,
Log: skill.Error, Done: true,
}, true
}
}
// InstallEvents godoc
// @Summary Follow an install or removal
// @Description Server-sent progress for one install or removal. The stream
// @Description always terminates: with the run's own terminal event, with one
// @Description derived from the durable status, or with a "detached" frame
// @Description when it stops following a run that is still going.
// @Tags SandboxConfig
// @Produce text/event-stream
// @Param id path string true "Sandbox config ID"
// @Param skillId path string true "Skill ID"
// @Success 200 {string} string "SSE stream of progress events"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Skill not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills/{skillId}/install-events [get]
func (h *SandboxSkillHandler) InstallEvents(c *gin.Context) {
ctx := c.Request.Context()
tenantID := sandboxConfigTenantID(c)
configID, skillID := c.Param("id"), c.Param("skillId")
// The progress key is workspace-scoped, so this lookup is not what isolates
// the stream; it is what turns "this skill is not yours" into a 404 while a
// refusal can still be rendered as JSON, before any SSE header is written.
skill, err := h.resolveSkill(c)
if err != nil {
_ = c.Error(err)
return
}
// Subscribing before the first read means an event published between the
// two is delivered rather than missed.
events, release, err := h.service.SubscribeProgress(ctx, tenantID, configID, skillID)
if err != nil {
_ = c.Error(err)
return
}
defer release()
setSandboxSkillSSEHeaders(c)
// lastPercent is what a detached frame reports, so giving up on following
// a run does not appear to reset its progress.
lastPercent := 0
if last, ok := h.service.LastProgress(ctx, tenantID, configID, skillID); ok {
event := skillEventFromProgress(last)
lastPercent = event.Percent
if !h.emit(c, event) || event.Done {
return
}
}
if terminal, ok := terminalSkillEvent(skill); ok {
h.emit(c, terminal)
return
}
if events == nil {
// Nothing publishes progress without Redis. One frame stating the
// durable status is all this connection can ever say.
h.emit(c, skillInstallEvent{
Stage: skill.Status,
Status: skill.Status,
Log: "live progress is unavailable; poll the skill for its status",
Done: true,
})
return
}
poll := time.NewTicker(h.pollInterval)
defer poll.Stop()
deadline := time.NewTimer(h.maxDuration)
defer deadline.Stop()
for {
select {
case <-ctx.Done():
// The client is gone. The install keeps running; only this view
// of it ends.
return
case p, ok := <-events:
if !ok {
// The subscription ended under us. The poll below is now the
// only source of truth, so keep the connection until it
// reaches a terminal state or the cap expires.
events = nil
continue
}
event := skillEventFromProgress(p)
lastPercent = event.Percent
if !h.emit(c, event) || event.Done {
return
}
case <-poll.C:
current, err := h.service.GetSkill(ctx, tenantID, configID, skillID)
if err != nil {
logger.Warnf(ctx, "[skill] re-read %s while streaming failed: %v", skillID, err)
if !h.emitComment(c) {
return
}
continue
}
if terminal, ok := terminalSkillEvent(current); ok {
h.emit(c, terminal)
return
}
// Nothing to report: a comment keeps the connection warm and
// surfaces a client that has already gone away.
if !h.emitComment(c) {
return
}
case <-deadline.C:
h.emit(c, skillInstallEvent{
Percent: lastPercent,
Stage: skillStageDetached,
Status: skill.Status,
Log: "stopped following this run; reconnect or poll the skill for its status",
Done: true,
})
return
}
}
}
// InstallTranscript godoc
// @Summary Follow an install's agent transcript
// @Description Server-sent replay of everything the installer agent did — the
// @Description prompt it was given, its thinking, the commands it ran and
// @Description their output — followed live while the install is still
// @Description running. Frames are the same shape the chat stream uses, so a
// @Description console renders an install with the components it renders a
// @Description chat turn with. 404 once the event log has expired; the
// @Description durable message history is the fallback.
// @Tags SandboxConfig
// @Produce text/event-stream
// @Param id path string true "Sandbox config ID"
// @Param skillId path string true "Skill ID"
// @Success 200 {string} string "SSE stream of transcript events"
// @Failure 401 {object} map[string]interface{} "Unauthorized"
// @Failure 404 {object} apperrors.AppError "Skill or transcript not found"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sandbox-configs/{id}/skills/{skillId}/transcript [get]
//
// The transcript deliberately does not reuse /sessions/continue-stream. That
// endpoint authorizes by "does this chat session belong to you", while an
// install is a workspace-level maintenance run whose session is hidden from the
// session list on purpose — the two rules pull in opposite directions. Here the
// skill lookup above is the authorization, exactly as it is for every other
// route in this file.
func (h *SandboxSkillHandler) InstallTranscript(c *gin.Context) {
ctx := c.Request.Context()
skill, err := h.resolveSkill(c)
if err != nil {
_ = c.Error(err)
return
}
sessionID, messageID := skill.InstallSessionID, skill.InstallMessageID
if sessionID == "" || messageID == "" {
_ = c.Error(apperrors.NewNotFoundError("this skill has no install transcript"))
return
}
if h.streams == nil {
_ = c.Error(apperrors.NewNotFoundError("install transcripts are unavailable"))
return
}
events, offset, err := h.streams.GetEvents(ctx, sessionID, messageID, 0)
if err != nil {
logger.Errorf(ctx, "[skill] read install transcript of %s failed: %v", skill.ID, err)
_ = c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
// An empty log means the run predates the transcript or its TTL has passed.
// Refuse before any SSE header is written so the caller can still fall back
// to the durable message history.
if len(events) == 0 {
_ = c.Error(apperrors.NewNotFoundError("this install's event log is no longer available"))
return
}
setSandboxSkillSSEHeaders(c)
done := h.emitTranscript(c, sessionID, messageID, events)
if done {
return
}
// Tailing at the chat stream's cadence: the installer emits thinking token
// by token, and a slower tick would arrive as visible bursts.
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
deadline := time.NewTimer(h.maxDuration)
defer deadline.Stop()
for {
select {
case <-ctx.Done():
// The viewer navigated away. The install keeps running.
return
case <-deadline.C:
return
case <-tick.C:
newEvents, newOffset, err := h.streams.GetEvents(ctx, sessionID, messageID, offset)
if err != nil {
logger.Warnf(ctx, "[skill] tail install transcript of %s failed: %v", skill.ID, err)
return
}
offset = newOffset
if h.emitTranscript(c, sessionID, messageID, newEvents) {
return
}
}
}
}
// emitTranscript writes frames and reports whether the stream is over, either
// because the run completed or because the viewer is gone.
func (h *SandboxSkillHandler) emitTranscript(
c *gin.Context, sessionID, messageID string, events []interfaces.StreamEvent,
) bool {
for _, evt := range events {
c.SSEvent("message", types.StreamResponse{
// Every frame carries the assistant message ID so the console
// groups the whole run into one turn.
ID: messageID,
ResponseType: evt.Type,
Content: evt.Content,
Done: evt.Done,
SessionID: sessionID,
AssistantMessageID: messageID,
Data: evt.Data,
})
c.Writer.Flush()
if c.Request.Context().Err() != nil {
return true
}
if evt.Type == types.ResponseTypeComplete {
return true
}
}
return c.Request.Context().Err() != nil
}
// resolveSkill loads the skill for the caller's workspace and config, and
// returns the 404 every route renders when it is not reachable.
func (h *SandboxSkillHandler) resolveSkill(c *gin.Context) (*types.TenantSkillEntity, error) {
skill, err := h.service.GetSkill(c.Request.Context(), sandboxConfigTenantID(c),
c.Param("id"), c.Param("skillId"))
if err != nil {
return nil, err
}
if skill == nil {
return nil, apperrors.NewNotFoundError("skill not found")
}
return skill, nil
}
// emit writes one frame and reports whether the stream can continue.
func (h *SandboxSkillHandler) emit(c *gin.Context, event skillInstallEvent) bool {
c.SSEvent("message", event)
c.Writer.Flush()
return c.Request.Context().Err() == nil
}
func (h *SandboxSkillHandler) emitComment(c *gin.Context) bool {
if _, err := c.Writer.WriteString(": keep-alive\n\n"); err != nil {
return false
}
c.Writer.Flush()
return c.Request.Context().Err() == nil
}
// setSandboxSkillSSEHeaders mirrors the session package's SSE preamble;
// X-Accel-Buffering is what stops nginx from holding progress frames back.
func setSandboxSkillSSEHeaders(c *gin.Context) {
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("X-Accel-Buffering", "no")
}

View File

@ -0,0 +1,850 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
const testSkillTenantID = uint64(42)
// fakeSandboxSkillService mirrors the real service surface: every method takes
// the workspace ID the route resolved, and the progress subscription honours
// the request context and hands back a closer the handler must call.
type fakeSandboxSkillService struct {
mu sync.Mutex
skills map[string]*types.TenantSkillEntity
listErr error
getErr error
patchErr error
installID string
installErr error
removeErr error
last service.SkillProgress
hasLast bool
events chan service.SkillProgress
subscribe error
// Recorded calls. Every one keeps the workspace ID so a route that
// forgot to scope its lookups fails the test.
listTenant uint64
listConfig string
getCalls int
installTenant uint64
installConfig string
installBytes []byte
removeTenant uint64
removeConfig string
removeSkill string
patchEnabled bool
closed bool
// onGet runs on every read, so a test can model a row that disappears
// while the client is streaming.
onGet func(calls int)
}
func (f *fakeSandboxSkillService) ListSkills(
_ context.Context, tenantID uint64, configID string,
) ([]*types.TenantSkillEntity, error) {
f.listTenant, f.listConfig = tenantID, configID
if f.listErr != nil {
return nil, f.listErr
}
out := make([]*types.TenantSkillEntity, 0, len(f.skills))
for _, skill := range f.skills {
out = append(out, skill)
}
return out, nil
}
func (f *fakeSandboxSkillService) GetSkill(
_ context.Context, tenantID uint64, configID, skillID string,
) (*types.TenantSkillEntity, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.getCalls++
if f.onGet != nil {
f.onGet(f.getCalls)
}
if f.getErr != nil {
return nil, f.getErr
}
if tenantID != testSkillTenantID {
return nil, nil
}
skill := f.skills[skillID]
if skill == nil || skill.SandboxConfigID != configID {
return nil, nil
}
return skill, nil
}
func (f *fakeSandboxSkillService) SetSkillEnabled(
_ context.Context, tenantID uint64, configID, skillID string, enabled bool,
) (*types.TenantSkillEntity, error) {
if f.patchErr != nil {
return nil, f.patchErr
}
f.patchEnabled = enabled
skill := f.skills[skillID]
if skill == nil || tenantID != testSkillTenantID || skill.SandboxConfigID != configID {
return nil, nil
}
skill.Enabled = enabled
return skill, nil
}
func (f *fakeSandboxSkillService) InstallSkill(
_ context.Context, tenantID uint64, configID string, archive []byte,
) (string, error) {
f.installTenant, f.installConfig, f.installBytes = tenantID, configID, archive
return f.installID, f.installErr
}
func (f *fakeSandboxSkillService) RemoveSkill(
_ context.Context, tenantID uint64, configID, skillID string,
) error {
f.removeTenant, f.removeConfig, f.removeSkill = tenantID, configID, skillID
return f.removeErr
}
func (f *fakeSandboxSkillService) LastProgress(
_ context.Context, _ uint64, _, _ string,
) (service.SkillProgress, bool) {
return f.last, f.hasLast
}
func (f *fakeSandboxSkillService) SubscribeProgress(
ctx context.Context, _ uint64, _, _ string,
) (<-chan service.SkillProgress, func(), error) {
if f.subscribe != nil {
return nil, func() {}, f.subscribe
}
closer := func() {
f.mu.Lock()
defer f.mu.Unlock()
f.closed = true
}
if f.events == nil {
return nil, closer, nil
}
// The real subscription stops delivering once the request context is
// gone; a fake that kept delivering would hide a handler that ignores it.
out := make(chan service.SkillProgress, cap(f.events))
go func() {
defer close(out)
for {
select {
case p, ok := <-f.events:
if !ok {
return
}
select {
case out <- p:
case <-ctx.Done():
return
}
case <-ctx.Done():
return
}
}
}()
return out, closer, nil
}
func (f *fakeSandboxSkillService) subscriptionClosed() bool {
f.mu.Lock()
defer f.mu.Unlock()
return f.closed
}
func newSkillTestRouter(h *SandboxSkillHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), testSkillTenantID)
c.Next()
})
r.GET("/sandbox-configs/:id/skills", h.List)
r.POST("/sandbox-configs/:id/skills", h.Upload)
r.GET("/sandbox-configs/:id/skills/:skillId", h.Get)
r.PATCH("/sandbox-configs/:id/skills/:skillId", h.Patch)
r.DELETE("/sandbox-configs/:id/skills/:skillId", h.Delete)
r.GET("/sandbox-configs/:id/skills/:skillId/install-events", h.InstallEvents)
r.GET("/sandbox-configs/:id/skills/:skillId/transcript", h.InstallTranscript)
return r
}
func skillUploadRequest(t *testing.T, configID string, archive []byte) *http.Request {
t.Helper()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", "skill.zip")
require.NoError(t, err)
_, err = part.Write(archive)
require.NoError(t, err)
require.NoError(t, writer.Close())
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/"+configID+"/skills", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
return req
}
// An upload larger than the platform's file cap must be refused by the HTTP
// layer, before the whole body is buffered for the parser.
func TestSandboxSkillUploadOverLimitReturns400(t *testing.T) {
t.Setenv("MAX_FILE_SIZE_MB", "1")
svc := &fakeSandboxSkillService{installID: "skill-1"}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, skillUploadRequest(t, "cfg-a", bytes.Repeat([]byte("z"), 2<<20)))
require.Equal(t, http.StatusBadRequest, w.Code)
require.Contains(t, w.Body.String(), "1 MB")
require.Nil(t, svc.installBytes, "an oversize body must never reach the service")
}
// Every rejection of an uploaded archive is one class of error, matched as a
// sentinel so a reworded message cannot start returning 500 for bad input.
func TestSandboxSkillUploadInvalidBundleReturns400(t *testing.T) {
svc := &fakeSandboxSkillService{
installErr: fmt.Errorf("%w: SKILL.md is missing", service.ErrSkillBundleInvalid),
}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, skillUploadRequest(t, "cfg-a", []byte("not a zip")))
require.Equal(t, http.StatusBadRequest, w.Code)
require.Contains(t, w.Body.String(), "SKILL.md is missing")
}
// The install runs for minutes, so the upload is only ever accepted; the ID is
// what the client needs to follow it.
func TestSandboxSkillUploadAcceptedReturnsSkillID(t *testing.T) {
svc := &fakeSandboxSkillService{installID: "skill-7"}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, skillUploadRequest(t, "cfg-a", []byte("zip-bytes")))
require.Equal(t, http.StatusAccepted, w.Code)
var payload struct {
Success bool `json:"success"`
Data struct {
SkillID string `json:"skill_id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.True(t, payload.Success)
require.Equal(t, "skill-7", payload.Data.SkillID)
require.Equal(t, testSkillTenantID, svc.installTenant)
require.Equal(t, "cfg-a", svc.installConfig)
require.Equal(t, []byte("zip-bytes"), svc.installBytes)
}
func TestSandboxSkillUploadWithoutFileReturns400(t *testing.T) {
svc := &fakeSandboxSkillService{}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",
strings.NewReader(""))
req.Header.Set("Content-Type", "multipart/form-data; boundary=none")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
require.Nil(t, svc.installBytes)
}
// Every route must scope to the caller's workspace, and a skill under another
// workspace's config must be unreachable rather than merely empty.
func TestSandboxSkillRoutesScopeToCallerWorkspace(t *testing.T) {
svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {
ID: "skill-1", TenantID: testSkillTenantID, SandboxConfigID: "cfg-a",
Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
},
}}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
for _, tc := range []struct {
name string
method string
target string
body string
wantGot int
}{
{
name: "get own skill", method: http.MethodGet,
target: "/sandbox-configs/cfg-a/skills/skill-1", wantGot: http.StatusOK,
},
{
name: "get skill of another config", method: http.MethodGet,
target: "/sandbox-configs/cfg-b/skills/skill-1", wantGot: http.StatusNotFound,
},
{
name: "patch skill of another config", method: http.MethodPatch,
target: "/sandbox-configs/cfg-b/skills/skill-1", body: `{"enabled":false}`,
wantGot: http.StatusNotFound,
},
{
name: "stream skill of another config", method: http.MethodGet,
target: "/sandbox-configs/cfg-b/skills/skill-1/install-events",
wantGot: http.StatusNotFound,
},
} {
t.Run(tc.name, func(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(tc.method, tc.target, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, tc.wantGot, w.Code)
})
}
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sandbox-configs/cfg-a/skills", nil))
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, testSkillTenantID, svc.listTenant)
require.Equal(t, "cfg-a", svc.listConfig)
}
func TestSandboxSkillListReturnsProjection(t *testing.T) {
svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {
ID: "skill-1", TenantID: testSkillTenantID, SandboxConfigID: "cfg-a",
Name: "pdf", Version: "1.2.0", Description: "read pdfs",
Status: types.SkillStatusReady, Enabled: true, BundleSHA256: "abc",
InstalledSnapshotID: "snap-1",
},
}}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/sandbox-configs/cfg-a/skills", nil))
require.Equal(t, http.StatusOK, w.Code)
var payload struct {
Data []struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
Status string `json:"status"`
Enabled bool `json:"enabled"`
Snapshot string `json:"installed_snapshot_id"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.Len(t, payload.Data, 1)
require.Equal(t, "skill-1", payload.Data[0].ID)
require.Equal(t, "1.2.0", payload.Data[0].Version)
require.Equal(t, types.SkillStatusReady, payload.Data[0].Status)
require.True(t, payload.Data[0].Enabled)
require.Equal(t, "snap-1", payload.Data[0].Snapshot)
}
func TestSandboxSkillPatchTogglesEnabled(t *testing.T) {
svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {
ID: "skill-1", TenantID: testSkillTenantID, SandboxConfigID: "cfg-a",
Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
},
}}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
strings.NewReader(`{"enabled":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.False(t, svc.patchEnabled)
require.Contains(t, w.Body.String(), `"enabled":false`)
}
// An empty body must not be read as "disable it": the field is the whole
// request, so its absence is a bad request rather than a silent false.
func TestSandboxSkillPatchWithoutEnabledFieldReturns400(t *testing.T) {
svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Enabled: true},
}}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPatch, "/sandbox-configs/cfg-a/skills/skill-1",
strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
require.True(t, svc.skills["skill-1"].Enabled)
}
// Removal rebuilds the image, so it is accepted and followed, never awaited.
func TestSandboxSkillDeleteIsAccepted(t *testing.T) {
svc := &fakeSandboxSkillService{}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/sandbox-configs/cfg-a/skills/skill-1", nil))
require.Equal(t, http.StatusAccepted, w.Code)
require.Equal(t, testSkillTenantID, svc.removeTenant)
require.Equal(t, "cfg-a", svc.removeConfig)
require.Equal(t, "skill-1", svc.removeSkill)
}
func decodeSSEEvents(t *testing.T, body string) []map[string]any {
t.Helper()
var events []map[string]any
for _, line := range strings.Split(body, "\n") {
if !strings.HasPrefix(line, "data:") {
continue
}
var payload map[string]any
require.NoError(t, json.Unmarshal(
[]byte(strings.TrimSpace(strings.TrimPrefix(line, "data:"))), &payload))
events = append(events, payload)
}
return events
}
// A client that connects after the install finished must be told so and get its
// connection closed, not left waiting for an event that already happened.
func TestSandboxSkillInstallEventsFinishedInstallTerminatesImmediately(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {
ID: "skill-1", SandboxConfigID: "cfg-a",
Status: types.SkillStatusReady, Enabled: true,
},
},
events: make(chan service.SkillProgress),
}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
require.Equal(t, http.StatusOK, w.Code)
require.Contains(t, w.Header().Get("Content-Type"), "text/event-stream")
events := decodeSSEEvents(t, w.Body.String())
require.NotEmpty(t, events)
final := events[len(events)-1]
require.Equal(t, true, final["done"])
require.Equal(t, types.SkillStatusReady, final["status"])
require.True(t, svc.subscriptionClosed(), "the subscription must be released")
}
// A late subscriber still gets the last stored value, so the UI can paint
// without waiting for the next tick.
func TestSandboxSkillInstallEventsReplaysLastProgress(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling},
},
last: service.SkillProgress{Percent: 35, Stage: "seeded"},
hasLast: true,
events: make(chan service.SkillProgress, 1),
}
svc.events <- service.SkillProgress{
Percent: 100, Stage: "done", Status: types.SkillStatusReady,
}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
events := decodeSSEEvents(t, w.Body.String())
require.Len(t, events, 2)
require.Equal(t, "seeded", events[0]["stage"])
require.Equal(t, false, events[0]["done"])
require.Equal(t, "done", events[1]["stage"])
require.Equal(t, true, events[1]["done"])
}
// A failed run is terminal too: the client must not keep a connection open
// waiting for a success that will never come.
func TestSandboxSkillInstallEventsFailureTerminatesStream(t *testing.T) {
events := make(chan service.SkillProgress, 1)
events <- service.SkillProgress{
Percent: 100, Stage: "failed", Status: types.SkillStatusFailed, Log: "smoke run failed",
}
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling},
},
events: events,
}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
decoded := decodeSSEEvents(t, w.Body.String())
require.NotEmpty(t, decoded)
final := decoded[len(decoded)-1]
require.Equal(t, true, final["done"])
require.Equal(t, "smoke run failed", final["log"])
}
// A duplicate removal submission finishes without publishing anything: the
// second run finds nothing to remove and returns. The durable state is the only
// thing left that says so, so the stream must watch it and end itself.
func TestSandboxSkillInstallEventsSynthesizesTerminalWhenRowDisappears(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusRemoving},
},
last: service.SkillProgress{
Percent: 5, Stage: "accepted", Status: types.SkillStatusRemoving,
},
hasLast: true,
events: make(chan service.SkillProgress),
}
// The row is gone by the first re-check, exactly as it is once the first
// removal has finished.
svc.onGet = func(calls int) {
if calls > 1 {
svc.skills = map[string]*types.TenantSkillEntity{}
}
}
h := NewSandboxSkillHandler(svc, nil)
h.pollInterval = 10 * time.Millisecond
router := newSkillTestRouter(h)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
events := decodeSSEEvents(t, w.Body.String())
require.NotEmpty(t, events)
final := events[len(events)-1]
require.Equal(t, true, final["done"])
require.Equal(t, "removed", final["status"])
}
// Without Redis there is no live progress at all. One event describing the
// durable state is honest; holding the connection open is not.
func TestSandboxSkillInstallEventsWithoutRedisSendsStateAndCloses(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling},
},
}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
events := decodeSSEEvents(t, w.Body.String())
require.Len(t, events, 1)
require.Equal(t, true, events[0]["done"])
require.Equal(t, types.SkillStatusInstalling, events[0]["status"])
require.True(t, svc.subscriptionClosed())
}
// A disconnected client must free the subscription rather than leaving a
// goroutine and a Redis connection behind for the rest of the install.
func TestSandboxSkillInstallEventsStopsWhenClientDisconnects(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling},
},
events: make(chan service.SkillProgress),
}
h := NewSandboxSkillHandler(svc, nil)
h.pollInterval = time.Hour
router := newSkillTestRouter(h)
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil).WithContext(ctx)
done := make(chan struct{})
go func() {
defer close(done)
router.ServeHTTP(httptest.NewRecorder(), req)
}()
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("the handler kept streaming after the client went away")
}
require.True(t, svc.subscriptionClosed())
}
// A run whose process died leaves the row at "installing" forever until the
// reaper lands. The stream must still end by itself.
func TestSandboxSkillInstallEventsStopsFollowingAfterCap(t *testing.T) {
svc := &fakeSandboxSkillService{
skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling},
},
events: make(chan service.SkillProgress),
}
h := NewSandboxSkillHandler(svc, nil)
h.pollInterval = time.Hour
h.maxDuration = 20 * time.Millisecond
router := newSkillTestRouter(h)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
"/sandbox-configs/cfg-a/skills/skill-1/install-events", nil))
events := decodeSSEEvents(t, w.Body.String())
require.NotEmpty(t, events)
final := events[len(events)-1]
require.Equal(t, true, final["done"])
require.Equal(t, types.SkillStatusInstalling, final["status"],
"giving up on following must not be reported as a finished install")
}
// The transcript locators are the only way the console can find an install's
// conversation, so they must survive the outward projection.
func TestToSkillResponseCarriesTranscriptLocators(t *testing.T) {
got := toSkillResponse(&types.TenantSkillEntity{
ID: "sk-1",
Name: "pdf-tools",
Status: types.SkillStatusReady,
InstallSessionID: "sess-1",
InstallMessageID: "msg-1",
})
require.Equal(t, "sess-1", got.InstallSessionID)
require.Equal(t, "msg-1", got.InstallMessageID)
}
// A skill installed before this feature shipped has no locators; the fields
// must be absent rather than empty so the console can hide the entry point.
func TestToSkillResponseOmitsMissingTranscriptLocators(t *testing.T) {
raw, err := json.Marshal(toSkillResponse(&types.TenantSkillEntity{ID: "sk-1"}))
require.NoError(t, err)
require.NotContains(t, string(raw), "install_session_id")
require.NotContains(t, string(raw), "install_message_id")
}
// transcriptStreamManager is the installer's event log. Appends land in the
// same slice reads serve, so a test can grow the log while the handler tails it.
type transcriptStreamManager struct {
mu sync.Mutex
key string
events []interfaces.StreamEvent
err error
}
func (m *transcriptStreamManager) AppendEvent(
_ context.Context, sessionID, messageID string, evt interfaces.StreamEvent,
) error {
m.mu.Lock()
defer m.mu.Unlock()
m.key = sessionID + "/" + messageID
m.events = append(m.events, evt)
return nil
}
func (m *transcriptStreamManager) GetEvents(
_ context.Context, sessionID, messageID string, from int,
) ([]interfaces.StreamEvent, int, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.err != nil {
return nil, 0, m.err
}
// Recording the key on read as well is what proves the handler addressed
// the log by the skill's stored locators rather than by anything else.
m.key = sessionID + "/" + messageID
if from >= len(m.events) {
return nil, len(m.events), nil
}
out := append([]interfaces.StreamEvent(nil), m.events[from:]...)
return out, len(m.events), nil
}
func (m *transcriptStreamManager) readKey() string {
m.mu.Lock()
defer m.mu.Unlock()
return m.key
}
func transcriptSkillService() *fakeSandboxSkillService {
return &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {
ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusInstalling,
InstallSessionID: "sess-9", InstallMessageID: "msg-9",
},
}}
}
func transcriptRequest(configID, skillID string) *http.Request {
return httptest.NewRequest(http.MethodGet,
"/sandbox-configs/"+configID+"/skills/"+skillID+"/transcript", nil)
}
// The whole point of the endpoint: everything the installer did, in order,
// shaped like the chat stream so the console renders it with the components it
// already has.
func TestSandboxSkillTranscriptReplaysTheInstallerConversation(t *testing.T) {
streams := &transcriptStreamManager{}
ctx := context.Background()
for _, evt := range []interfaces.StreamEvent{
{ID: "p", Type: types.ResponseTypeInstallPrompt, Content: "install web-search", Done: true},
{ID: "t", Type: types.ResponseTypeThinking, Content: "check for uv"},
{
ID: "c", Type: types.ResponseTypeToolCall, Content: "Calling tool: shell_exec",
Data: map[string]interface{}{"tool_name": "shell_exec"},
},
{
ID: "r", Type: types.ResponseTypeToolResult, Content: "uv 0.4.0",
Data: map[string]interface{}{"success": true},
},
{ID: "done", Type: types.ResponseTypeComplete, Done: true},
} {
require.NoError(t, streams.AppendEvent(ctx, "sess-9", "msg-9", evt))
}
router := newSkillTestRouter(NewSandboxSkillHandler(transcriptSkillService(), streams))
w := httptest.NewRecorder()
router.ServeHTTP(w, transcriptRequest("cfg-a", "skill-1"))
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
require.Equal(t, "sess-9/msg-9", streams.readKey())
frames := parseTranscriptFrames(t, w.Body.String())
require.Equal(t, []string{"install_prompt", "thinking", "tool_call", "tool_result", "complete"},
transcriptTypes(frames))
require.Equal(t, "install web-search", frames[0].Content)
// Every frame names the same turn, or the console would scatter one install
// across five messages.
for _, frame := range frames {
require.Equal(t, "msg-9", frame.ID)
require.Equal(t, "msg-9", frame.AssistantMessageID)
require.Equal(t, "sess-9", frame.SessionID)
}
require.Equal(t, "shell_exec", frames[2].Data["tool_name"])
}
// A running install is the case the user actually watches: the handler must
// keep the connection open and push what the agent does next.
func TestSandboxSkillTranscriptTailsARunningInstall(t *testing.T) {
streams := &transcriptStreamManager{}
ctx := context.Background()
require.NoError(t, streams.AppendEvent(ctx, "sess-9", "msg-9", interfaces.StreamEvent{
ID: "p", Type: types.ResponseTypeInstallPrompt, Content: "install web-search", Done: true,
}))
router := newSkillTestRouter(NewSandboxSkillHandler(transcriptSkillService(), streams))
// The engine keeps working after the console attaches.
go func() {
time.Sleep(30 * time.Millisecond)
_ = streams.AppendEvent(ctx, "sess-9", "msg-9", interfaces.StreamEvent{
ID: "t", Type: types.ResponseTypeThinking, Content: "creating the venv",
})
_ = streams.AppendEvent(ctx, "sess-9", "msg-9", interfaces.StreamEvent{
ID: "done", Type: types.ResponseTypeComplete, Done: true,
})
}()
w := httptest.NewRecorder()
router.ServeHTTP(w, transcriptRequest("cfg-a", "skill-1"))
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, []string{"install_prompt", "thinking", "complete"},
transcriptTypes(parseTranscriptFrames(t, w.Body.String())))
}
// Refusing before the SSE headers go out is what lets the console fall back to
// the durable message history instead of rendering an empty conversation.
func TestSandboxSkillTranscriptWithExpiredLogReturns404(t *testing.T) {
router := newSkillTestRouter(
NewSandboxSkillHandler(transcriptSkillService(), &transcriptStreamManager{}),
)
w := httptest.NewRecorder()
router.ServeHTTP(w, transcriptRequest("cfg-a", "skill-1"))
require.Equal(t, http.StatusNotFound, w.Code, "body=%s", w.Body.String())
require.NotContains(t, w.Header().Get("Content-Type"), "event-stream")
}
func TestSandboxSkillTranscriptWithoutLocatorsReturns404(t *testing.T) {
svc := &fakeSandboxSkillService{skills: map[string]*types.TenantSkillEntity{
"skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Status: types.SkillStatusReady},
}}
router := newSkillTestRouter(NewSandboxSkillHandler(svc, &transcriptStreamManager{}))
w := httptest.NewRecorder()
router.ServeHTTP(w, transcriptRequest("cfg-a", "skill-1"))
require.Equal(t, http.StatusNotFound, w.Code, "body=%s", w.Body.String())
}
// The skill lookup is this endpoint's authorization: an install transcript can
// hold command output from another workspace's image build.
func TestSandboxSkillTranscriptOfAnotherConfigReturns404(t *testing.T) {
streams := &transcriptStreamManager{}
require.NoError(t, streams.AppendEvent(context.Background(), "sess-9", "msg-9",
interfaces.StreamEvent{ID: "p", Type: types.ResponseTypeInstallPrompt, Content: "secret"}))
router := newSkillTestRouter(NewSandboxSkillHandler(transcriptSkillService(), streams))
w := httptest.NewRecorder()
router.ServeHTTP(w, transcriptRequest("cfg-b", "skill-1"))
require.Equal(t, http.StatusNotFound, w.Code, "body=%s", w.Body.String())
require.NotContains(t, w.Body.String(), "secret")
}
func parseTranscriptFrames(t *testing.T, body string) []types.StreamResponse {
t.Helper()
var frames []types.StreamResponse
for _, line := range strings.Split(body, "\n") {
payload, ok := strings.CutPrefix(line, "data:")
if !ok {
continue
}
var frame types.StreamResponse
require.NoError(t, json.Unmarshal([]byte(strings.TrimSpace(payload)), &frame), "line=%q", line)
frames = append(frames, frame)
}
return frames
}
func transcriptTypes(frames []types.StreamResponse) []string {
out := make([]string, 0, len(frames))
for _, frame := range frames {
out = append(out, string(frame.ResponseType))
}
return out
}

View File

@ -129,7 +129,7 @@ func (h *Handler) CreateSession(c *gin.Context) {
createdSession := &types.Session{
TenantID: tenantID.(uint64),
Title: request.Title,
Description: request.Description,
Description: types.SanitizeClientSessionDescription(request.Description, ""),
}
// Attach the calling user as the session owner when available.
// API-key callers scope sessions per external user when configured;

View File

@ -1,23 +1,29 @@
package handler
import (
"context"
"net/http"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// usableSkillLister returns the installed skills a chat turn can actually
// invoke on one sandbox config. The @ picker and the agent editor both read
// this set so they cannot offer a skill the running image does not carry.
type usableSkillLister interface {
ListUsableSkills(ctx context.Context, tenantID uint64, configID string) []*types.TenantSkillEntity
}
// SkillHandler handles skill-related HTTP requests
type SkillHandler struct {
skillService interfaces.SkillService
usableSkills usableSkillLister
}
// NewSkillHandler creates a new skill handler
func NewSkillHandler(skillService interfaces.SkillService) *SkillHandler {
func NewSkillHandler(usableSkills usableSkillLister) *SkillHandler {
return &SkillHandler{
skillService: skillService,
usableSkills: usableSkills,
}
}
@ -28,40 +34,45 @@ type SkillInfoResponse struct {
}
// ListSkills godoc
// @Summary 获取预装Skills列表
// @Description 获取所有预装的Agent Skills元数据
// @Summary 获取当前沙盒配置上可执行的 Skills
// @Description 返回指定沙盒配置镜像内、智能体实际能调用的已安装技能(ready 且启用)。不传 sandbox_config_id 时列表为空。
// @Tags Skills
// @Accept json
// @Produce json
// @Param sandbox_config_id query string false "Sandbox config ID"
// @Success 200 {object} map[string]interface{} "Skills列表"
// @Failure 500 {object} errors.AppError "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /skills [get]
func (h *SkillHandler) ListSkills(c *gin.Context) {
ctx := c.Request.Context()
skillsMetadata, err := h.skillService.ListPreloadedSkills(ctx)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to list skills: " + err.Error()))
configID := c.Query("sandbox_config_id")
if configID == "" || h.usableSkills == nil {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": []SkillInfoResponse{},
"skills_available": false,
})
return
}
// Convert to response format
var response []SkillInfoResponse
for _, meta := range skillsMetadata {
rows := h.usableSkills.ListUsableSkills(
c.Request.Context(), sandboxConfigTenantID(c), configID,
)
response := make([]SkillInfoResponse, 0, len(rows))
for _, row := range rows {
if row == nil {
continue
}
response = append(response, SkillInfoResponse{
Name: meta.Name,
Description: meta.Description,
Name: row.Name,
Description: row.Description,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": response,
// Skills can be selected before a workspace sandbox is configured; the
// execution path remains disabled until the agent chooses a config.
"success": true,
"data": response,
"skills_available": true,
})
}

View File

@ -0,0 +1,96 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
)
type fakeUsableSkillLister struct {
tenantID uint64
configID string
skills []*types.TenantSkillEntity
}
func (f *fakeUsableSkillLister) ListUsableSkills(
_ context.Context, tenantID uint64, configID string,
) []*types.TenantSkillEntity {
f.tenantID = tenantID
f.configID = configID
if configID == "" {
return nil
}
return f.skills
}
func newChatSkillRouter(h *SkillHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), testSkillTenantID)
c.Next()
})
r.GET("/skills", h.ListSkills)
return r
}
func TestListSkillsHidesThePickerWhenNoSandboxConfigIsSelected(t *testing.T) {
lister := &fakeUsableSkillLister{
skills: []*types.TenantSkillEntity{{Name: "ppt-generator", Description: "make ppt"}},
}
router := newChatSkillRouter(NewSkillHandler(lister))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/skills", nil))
require.Equal(t, http.StatusOK, w.Code)
var body struct {
Success bool `json:"success"`
Data []SkillInfoResponse
SkillsAvailable bool `json:"skills_available"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.True(t, body.Success)
require.Empty(t, body.Data, "preloaded and unscoped skills must not appear in @")
require.False(t, body.SkillsAvailable)
require.Empty(t, lister.configID)
}
func TestListSkillsReturnsUsableInstalledSkillsForTheSelectedConfig(t *testing.T) {
lister := &fakeUsableSkillLister{
skills: []*types.TenantSkillEntity{
{Name: "ppt-generator", Description: "make ppt"},
},
}
router := newChatSkillRouter(NewSkillHandler(lister))
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(
http.MethodGet, "/skills?sandbox_config_id=cfg-1", nil,
))
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, testSkillTenantID, lister.tenantID)
require.Equal(t, "cfg-1", lister.configID)
var body struct {
Success bool `json:"success"`
Data []SkillInfoResponse
SkillsAvailable bool `json:"skills_available"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.True(t, body.Success)
require.True(t, body.SkillsAvailable)
require.Equal(t, []SkillInfoResponse{
{Name: "ppt-generator", Description: "make ppt"},
}, body.Data)
}

View File

@ -385,6 +385,10 @@ func (a *apiKeyRouteGroup) PUT(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodPut, rel, h...)
}
func (a *apiKeyRouteGroup) PATCH(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodPatch, rel, h...)
}
func (a *apiKeyRouteGroup) DELETE(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodDelete, rel, h...)
}

View File

@ -57,6 +57,7 @@ type RouterParams struct {
ModelHandler *handler.ModelHandler
ModelCredentialsHandler *handler.ModelCredentialsHandler
SandboxConfigHandler *handler.SandboxConfigHandler
SandboxSkillHandler *handler.SandboxSkillHandler
EvaluationHandler *handler.EvaluationHandler
AuthHandler *handler.AuthHandler
InitializationHandler *handler.InitializationHandler
@ -264,7 +265,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterChatRoutes(v1, params.SessionHandler, rbacGuards)
RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards)
RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards)
RegisterSandboxConfigRoutes(v1, params.SandboxConfigHandler, rbacGuards)
RegisterSandboxConfigRoutes(v1, params.SandboxConfigHandler, params.SandboxSkillHandler, rbacGuards)
RegisterEvaluationRoutes(v1, params.EvaluationHandler, rbacGuards)
RegisterInitializationRoutes(v1, params.InitializationHandler, rbacGuards)
params.SystemHandler.BindDeploymentCapabilities(deploymentCapabilitiesFromRouter(params))

View File

@ -342,7 +342,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
RegisterWebSearchProviderRoutes(v1, &handler.WebSearchProviderHandler{}, &handler.WebSearchProviderCredentialsHandler{}, g)
RegisterVectorStoreRoutes(v1, &handler.VectorStoreHandler{}, g)
RegisterStorageBackendRoutes(v1, &handler.StorageBackendHandler{}, g)
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, &handler.SandboxSkillHandler{}, g)
RegisterEmbedChannelRoutes(v1, &handler.EmbedChannelHandler{}, g)
RegisterIMChannelRoutes(v1, &handler.IMHandler{}, g)
RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
@ -390,7 +390,7 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, g)
RegisterSandboxConfigRoutes(v1, &handler.SandboxConfigHandler{}, &handler.SandboxSkillHandler{}, g)
cases := []struct {
method string
@ -403,6 +403,15 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {
{http.MethodPut, "/api/v1/sandbox-configs/:id"},
{http.MethodDelete, "/api/v1/sandbox-configs/:id"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/sandboxes"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills"},
{http.MethodPost, "/api/v1/sandbox-configs/:id/skills"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId"},
{http.MethodPatch, "/api/v1/sandbox-configs/:id/skills/:skillId"},
{http.MethodDelete, "/api/v1/sandbox-configs/:id/skills/:skillId"},
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/install-events"},
// The transcript replays the root shell session that built the image,
// so it must not be reachable by a scoped key either.
{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/transcript"},
}
for _, tc := range cases {

View File

@ -46,6 +46,7 @@ func RegisterModelRoutes(
func RegisterSandboxConfigRoutes(
r *gin.RouterGroup,
h *handler.SandboxConfigHandler,
skills *handler.SandboxSkillHandler,
g *rbacGuards,
) {
configs := g.apiKeyGroup(r.Group("/sandbox-configs"), apiKeyFullAccess())
@ -58,6 +59,16 @@ func RegisterSandboxConfigRoutes(
configs.PUT("/:id", g.Admin(), h.Update)
configs.DELETE("/:id", g.Admin(), h.Delete)
configs.GET("/:id/sandboxes", g.Admin(), h.Inventory)
// Skills are Admin+ throughout, reads included: an upload drives a
// root shell whose output is baked into the image every session of
// this config boots, and the listing names what that image carries.
configs.GET("/:id/skills", g.Admin(), skills.List)
configs.POST("/:id/skills", g.Admin(), skills.Upload)
configs.GET("/:id/skills/:skillId", g.Admin(), skills.Get)
configs.PATCH("/:id/skills/:skillId", g.Admin(), skills.Patch)
configs.DELETE("/:id/skills/:skillId", g.Admin(), skills.Delete)
configs.GET("/:id/skills/:skillId/install-events", g.Admin(), skills.InstallEvents)
configs.GET("/:id/skills/:skillId/transcript", g.Admin(), skills.InstallTranscript)
}
}

View File

@ -114,3 +114,12 @@ type SessionDestroyer interface {
type SessionInstallCapabilityProvider interface {
SessionInstallShellExecutor() SessionInstallShellExecutor
}
// SessionTurnHolder marks the start and end of one chat turn on a session's
// sandbox. While the turn is open, a stale image mark waits: the first
// resolve of the turn may rebuild, later resolves of the same turn keep the
// sandbox so /workspace scratch and in-flight execs survive an admin install.
type SessionTurnHolder interface {
BeginSessionTurn(ctx context.Context, sessionID string) error
EndSessionTurn(ctx context.Context, sessionID string) error
}

View File

@ -606,7 +606,7 @@ func (c *CubeRemoteClient) MakeDir(
return err
}
if _, err := sb.Files().MakeDir(ctx, path); err != nil {
return normalizeCubeError("MakeDir", err)
return ignoreExistingDir(normalizeCubeError("MakeDir", err))
}
return nil
}

View File

@ -870,7 +870,7 @@ func (c *E2BRemoteClient) MakeDir(
return e2bInvalidRequest("MakeDir", "path is required", nil)
}
if err := sandbox.Filesystem.MakeDir(ctx, path, e2b.WithFileUser(DefaultSandboxExecUser)); err != nil {
return normalizeE2BError("MakeDir", err)
return ignoreExistingDir(normalizeE2BError("MakeDir", err))
}
return nil
}

View File

@ -401,6 +401,10 @@ type RemoteSandboxClient interface {
WriteFile(ctx context.Context, handle RemoteSandboxHandle, path string, content []byte) error
ReadFile(ctx context.Context, handle RemoteSandboxHandle, path string) ([]byte, error)
ListDir(ctx context.Context, handle RemoteSandboxHandle, path string) ([]RemoteDirEntry, error)
// MakeDir creates path, including parents. A directory that already
// exists is success: envd's MakeDir is not mkdir -p, and adapters must
// hide that so writing a second file into the same folder (or seeding
// SKILL.md after resetSkillDir) does not fail.
MakeDir(ctx context.Context, handle RemoteSandboxHandle, path string) error
Remove(ctx context.Context, handle RemoteSandboxHandle, path string) error
Stat(ctx context.Context, handle RemoteSandboxHandle, path string) (*RemoteStatEntry, error)

View File

@ -184,6 +184,32 @@ func IsRemoteInvalidRequest(err error) bool {
return remoteKind(err) == RemoteErrorKindInvalidRequest
}
// IsRemoteDirAlreadyExists reports whether MakeDir failed because the
// directory is already present. Cube's envd MakeDir is not mkdir -p: a
// directory created by a previous call (or by a shell `mkdir -p` in
// resetSkillDir) comes back as an internal error instead of success, and
// seeding SKILL.md would otherwise abort on a directory it is supposed to
// write into.
func IsRemoteDirAlreadyExists(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
if strings.Contains(msg, "directory already exists") {
return true
}
return remoteKind(err) == RemoteErrorKindConflict && strings.Contains(msg, "already exists")
}
// ignoreExistingDir turns an exist-ok MakeDir failure into success so callers
// can treat MakeDir as mkdir -p.
func ignoreExistingDir(err error) error {
if IsRemoteDirAlreadyExists(err) {
return nil
}
return err
}
// CanReplaceRemoteBinding reports whether the error proves that the bound
// remote sandbox is permanently gone. This is intentionally allow-list based:
// unknown and newly introduced errors preserve bindings by default.

View File

@ -128,3 +128,52 @@ func TestRemoteErrorDiagnostics(t *testing.T) {
t.Fatal("expected plain error text")
}
}
func TestIsRemoteDirAlreadyExists(t *testing.T) {
t.Parallel()
cubeSeedErr := NewRemoteError(
SandboxTypeCube, "MakeDir", RemoteErrorKindInternal,
"failed to make dir /opt/weknora/tenant/skills/sk-1: directory already exists: /opt/weknora/tenant/skills/sk-1",
nil,
)
tests := []struct {
name string
err error
want bool
}{
{name: "nil", err: nil, want: false},
{name: "cube envd already exists", err: cubeSeedErr, want: true},
{
name: "wrapped cube error",
err: fmt.Errorf("sandbox: create install directory: %w", cubeSeedErr),
want: true,
},
{
name: "e2b conflict already exists",
err: NewRemoteError(
SandboxTypeE2B, "MakeDir", RemoteErrorKindConflict, "already exists", nil,
),
want: true,
},
{
name: "unrelated internal",
err: NewRemoteError(SandboxTypeCube, "MakeDir", RemoteErrorKindInternal, "disk full", nil),
want: false,
},
{
name: "conflict without already exists",
err: NewRemoteError(SandboxTypeCube, "Delete", RemoteErrorKindConflict, "busy", nil),
want: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := IsRemoteDirAlreadyExists(tt.err); got != tt.want {
t.Fatalf("IsRemoteDirAlreadyExists() = %v, want %v", got, tt.want)
}
})
}
}

View File

@ -55,9 +55,10 @@ type fakeRemoteClient struct {
afterCreate func(RemoteSandboxHandle)
deleteHook func(context.Context, string) error
makeDirPaths []string
execRequests []RemoteExecRequest
writeFiles []fakeRemoteWriteFile
makeDirPaths []string
failMakeDirIfExists bool
execRequests []RemoteExecRequest
writeFiles []fakeRemoteWriteFile
// snapshots maps snapshotID -> source sandboxID.
snapshots map[string]string
@ -282,8 +283,19 @@ func (c *fakeRemoteClient) ListDir(
func (c *fakeRemoteClient) MakeDir(_ context.Context, _ RemoteSandboxHandle, path string) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.failMakeDirIfExists {
for _, existing := range c.makeDirPaths {
if existing == path {
return NewRemoteError(
c.provider, "MakeDir", RemoteErrorKindInternal,
fmt.Sprintf("failed to make dir %s: directory already exists: %s", path, path),
nil,
)
}
}
}
c.makeDirPaths = append(c.makeDirPaths, path)
c.mu.Unlock()
return nil
}

View File

@ -44,6 +44,21 @@ type SessionSandboxBinding struct {
SandboxID string `json:"sandbox_id"`
TemplateID string `json:"template_id"`
CreatedAt time.Time `json:"created_at"`
// ConfigID is the sandbox config the sandbox was created from. It is what
// makes "every sandbox of this config" answerable from the binding store:
// the sandbox itself carries the same value in provider metadata, but a
// staleness mark must not depend on the provider being reachable.
//
// Bindings written before this field existed carry an empty value. They are
// deliberately still valid — refusing them would break every live session
// on upgrade — and simply match no config until they are rebuilt.
ConfigID string `json:"config_id,omitempty"`
// StaleAt marks a binding whose sandbox boots an image the config has
// since replaced. The sandbox keeps serving until the session's next
// resolve, which destroys and recreates it; see InvalidateByConfig.
StaleAt *time.Time `json:"stale_at,omitempty"`
}
// Validate checks a binding against the current schema and authoritative key.
@ -92,6 +107,132 @@ type SessionSandboxBindingStore interface {
// ownership context. The ownership context survives caller cancellation
// but is canceled when exclusive lock ownership is lost.
WithLifecycleLock(context.Context, SessionSandboxKey, func(context.Context) error) error
// InvalidateByConfig marks every binding of one workspace's sandbox config
// stale and reports how many it marked. Already-marked bindings are not
// counted again.
InvalidateByConfig(ctx context.Context, tenantID uint64, configID string) (int, error)
}
// sessionTurnLeaseStore is the optional turn-lease half of a binding store.
// A resolve that sees a stale binding consults it so an in-flight chat turn
// keeps its sandbox, and only the first resolve of the next turn rebuilds.
type sessionTurnLeaseStore interface {
BeginTurn(ctx context.Context, key SessionSandboxKey) error
EndTurn(ctx context.Context, key SessionSandboxKey) error
TurnState(ctx context.Context, key SessionSandboxKey) (active, rebuildOnce bool, err error)
ConsumeTurnRebuild(ctx context.Context, key SessionSandboxKey) error
}
// bindingInvalidateLockTimeout bounds the wait for ONE session's lifecycle
// lock while marking. The caller runs inside the per-config install lock, so a
// single session that happens to be creating a sandbox right now must cost only
// its own mark rather than everyone else's.
const bindingInvalidateLockTimeout = 2 * time.Second
// bindingInvalidateMarkTimeout bounds the marking itself, once the lock is
// held. It is deliberately separate from the wait: sharing one budget would
// leave a mark that waited most of bindingInvalidateLockTimeout for the lock
// with milliseconds for its read plus compare-and-set, failing with a deadline
// error indistinguishable from a Redis fault.
const bindingInvalidateMarkTimeout = 3 * time.Second
// tenantBindingScanner is the store-specific half of InvalidateByConfig:
// enumerating one workspace's bindings and writing the mark. The serialisation
// and matching rules are shared, in invalidateBindingsByConfig.
type tenantBindingScanner interface {
SessionSandboxBindingStore
// listTenantBindingKeys returns the keys of every binding the store holds
// for tenantID. Bindings that disappear before they are marked are
// expected, not an error.
listTenantBindingKeys(ctx context.Context, tenantID uint64) ([]SessionSandboxKey, error)
// markBindingStale sets StaleAt only while the binding still names
// expected's provider and sandbox ID, and reports whether it wrote.
markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error)
}
// invalidateBindingsByConfig marks one config's bindings stale, one session at
// a time under that session's lifecycle lock.
//
// The lock is what makes the mark reliable: resolve reads the binding, decides
// whether to replace the sandbox, and rebinds all inside it, so marking outside
// would silently lose against a resolve running at the same moment. The mark
// itself is only ever an added field — the binding is never deleted here — so a
// concurrent resolve can lose a mark but never a sandbox.
//
// One session that cannot be marked does not stop the others: the image pointer
// has already moved by the time this runs, and an unmarked session serves the
// previous image until it ends, which is strictly better than leaving the rest
// of the workspace unmarked too. The failures are still returned so the caller
// can say which sessions are affected.
func invalidateBindingsByConfig(
ctx context.Context,
store tenantBindingScanner,
tenantID uint64,
configID string,
) (int, error) {
if tenantID == 0 {
return 0, errors.New("sandbox binding invalidation requires a tenant")
}
keys, err := store.listTenantBindingKeys(ctx, tenantID)
if err != nil {
return 0, err
}
wanted := NormalizeConfigID(configID)
marked := 0
var failures []error
for _, key := range keys {
if err := ctx.Err(); err != nil {
failures = append(failures, err)
break
}
// The cap applies to acquiring the lock only: the timer is stopped once
// fn runs, and the work below gets a budget of its own. Cancelling
// waitCtx is how the wait is abandoned, so the timer cannot simply be
// a deadline on the context fn is given.
waitCtx, cancel := context.WithCancel(ctx)
acquireTimer := time.AfterFunc(bindingInvalidateLockTimeout, cancel)
err := store.WithLifecycleLock(waitCtx, key, func(lockCtx context.Context) error {
// A false Stop means the cap fired as the lock was granted; then
// lockCtx is already cancelled and the calls below fail, which is
// the same outcome as losing the wait.
acquireTimer.Stop()
markCtx, cancelMark := context.WithTimeout(lockCtx, bindingInvalidateMarkTimeout)
defer cancelMark()
binding, err := store.Get(markCtx, key)
if err != nil || binding == nil {
return err
}
if binding.ConfigID != wanted || binding.StaleAt != nil {
return nil
}
wrote, err := store.markBindingStale(
markCtx, key, *binding, time.Now().UTC(),
)
if err != nil {
return err
}
if wrote {
marked++
}
return nil
})
acquireTimer.Stop()
cancel()
if err != nil {
failures = append(failures, fmt.Errorf("mark session %s stale: %w", key.SessionID, err))
}
}
return marked, errors.Join(failures...)
}
type lifecycleOwnershipContextKey struct{}
@ -117,12 +258,18 @@ type memoryLifecycleLock struct {
users int
}
type memoryTurnLease struct {
refs int
rebuildOnce bool
}
// MemorySessionSandboxBindingStore is a process-local implementation intended
// for tests and explicitly configured single-process deployments.
type MemorySessionSandboxBindingStore struct {
mu sync.Mutex
bindings map[SessionSandboxKey]SessionSandboxBinding
locks map[SessionSandboxKey]*memoryLifecycleLock
turns map[SessionSandboxKey]*memoryTurnLease
}
// NewMemorySessionSandboxBindingStore creates an empty in-memory store.
@ -130,6 +277,7 @@ func NewMemorySessionSandboxBindingStore() *MemorySessionSandboxBindingStore {
return &MemorySessionSandboxBindingStore{
bindings: make(map[SessionSandboxKey]SessionSandboxBinding),
locks: make(map[SessionSandboxKey]*memoryLifecycleLock),
turns: make(map[SessionSandboxKey]*memoryTurnLease),
}
}
@ -201,6 +349,56 @@ func (s *MemorySessionSandboxBindingStore) DeleteIfMatch(
return true, nil
}
// InvalidateByConfig marks this process's bindings of one config stale.
func (s *MemorySessionSandboxBindingStore) InvalidateByConfig(
ctx context.Context,
tenantID uint64,
configID string,
) (int, error) {
return invalidateBindingsByConfig(ctx, s, tenantID, configID)
}
func (s *MemorySessionSandboxBindingStore) listTenantBindingKeys(
ctx context.Context,
tenantID uint64,
) ([]SessionSandboxKey, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
var keys []SessionSandboxKey
for key := range s.bindings {
if key.TenantID == tenantID {
keys = append(keys, key)
}
}
return keys, nil
}
func (s *MemorySessionSandboxBindingStore) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
s.mu.Lock()
defer s.mu.Unlock()
binding, exists := s.bindings[key]
if !exists ||
binding.Provider != expected.Provider ||
binding.SandboxID != expected.SandboxID {
return false, nil
}
marked := staleAt
binding.StaleAt = &marked
s.bindings[key] = binding
return true, nil
}
// WithLifecycleLock runs fn while holding the process-local lock for key.
func (s *MemorySessionSandboxBindingStore) WithLifecycleLock(
ctx context.Context,
@ -269,6 +467,99 @@ func validateBindingMatch(
return nil
}
// BeginTurn opens a chat-turn lease. The first increment of a session's
// refcount allows the next resolve to rebuild a stale sandbox.
func (s *MemorySessionSandboxBindingStore) BeginTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
lease := s.turns[key]
if lease == nil {
lease = &memoryTurnLease{}
s.turns[key] = lease
}
if lease.refs == 0 {
lease.rebuildOnce = true
}
lease.refs++
return nil
}
// EndTurn releases one chat-turn lease. The last release drops the lease so
// a later resolve may rebuild a stale sandbox immediately.
func (s *MemorySessionSandboxBindingStore) EndTurn(
_ context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
lease := s.turns[key]
if lease == nil {
return nil
}
lease.refs--
if lease.refs <= 0 {
delete(s.turns, key)
}
return nil
}
// TurnState reports whether a chat turn is open and whether its first
// resolve may still rebuild a stale sandbox.
func (s *MemorySessionSandboxBindingStore) TurnState(
ctx context.Context,
key SessionSandboxKey,
) (bool, bool, error) {
if err := key.Validate(); err != nil {
return false, false, err
}
if err := ctx.Err(); err != nil {
return false, false, err
}
s.mu.Lock()
defer s.mu.Unlock()
lease := s.turns[key]
if lease == nil || lease.refs <= 0 {
return false, false, nil
}
return true, lease.rebuildOnce, nil
}
// ConsumeTurnRebuild spends the one rebuild allowed for the current turn.
func (s *MemorySessionSandboxBindingStore) ConsumeTurnRebuild(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if lease := s.turns[key]; lease != nil {
lease.rebuildOnce = false
}
return nil
}
var (
_ tenantBindingScanner = (*MemorySessionSandboxBindingStore)(nil)
_ sessionTurnLeaseStore = (*MemorySessionSandboxBindingStore)(nil)
)
func isRemoteProvider(provider RemoteProvider) bool {
switch provider {
case SandboxTypeCube, SandboxTypeE2B, SandboxTypeDocker:

View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"unicode"
@ -30,6 +31,52 @@ end
return 0
`)
var markBindingStaleIfMatchScript = redis.NewScript(`
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local value = cjson.decode(raw)
if value['provider'] ~= ARGV[1] or value['sandbox_id'] ~= ARGV[2] then
return 0
end
redis.call('SET', KEYS[1], ARGV[3])
return 1
`)
// sessionTurnLeaseTTL bounds a leaked turn if EndSessionTurn never runs
// (process crash). After it expires the next resolve may rebuild a stale
// image, which is what we want once no turn is actually using the sandbox.
const sessionTurnLeaseTTL = 30 * time.Minute
var beginTurnScript = redis.NewScript(`
local refs = redis.call('HINCRBY', KEYS[1], 'refs', 1)
if refs == 1 then
redis.call('HSET', KEYS[1], 'rebuild', '1')
end
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return refs
`)
var endTurnScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
local refs = redis.call('HINCRBY', KEYS[1], 'refs', -1)
if refs <= 0 then
redis.call('DEL', KEYS[1])
return 0
end
return refs
`)
var consumeTurnRebuildScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end
redis.call('HSET', KEYS[1], 'rebuild', '0')
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return 1
`)
// redisBindingScanCount is the SCAN batch size. Bindings are one small key per
// live session, so a workspace's whole set is normally a single batch.
const redisBindingScanCount = 200
// RedisSessionSandboxBindingStore is the authoritative distributed store for
// persistent remote-session bindings.
type RedisSessionSandboxBindingStore struct {
@ -157,6 +204,183 @@ func (s *RedisSessionSandboxBindingStore) WithLifecycleLock(
)
}
// InvalidateByConfig marks every binding of one workspace's config stale.
func (s *RedisSessionSandboxBindingStore) InvalidateByConfig(
ctx context.Context,
tenantID uint64,
configID string,
) (int, error) {
return invalidateBindingsByConfig(ctx, s, tenantID, configID)
}
// listTenantBindingKeys SCANs the workspace's binding keys.
//
// SCAN rather than a maintained index: the index would be a second key that
// every create and delete has to keep in step across processes, and a drifted
// index silently under-reports exactly when it matters. The cost is bounded
// because the pattern is anchored on the workspace's own prefix.
//
// A single-node Redis (what the container wires) answers this completely. On a
// Redis Cluster, SCAN reaches one node, so bindings living on the others would
// go unmarked and their sessions would keep the previous image until they end.
func (s *RedisSessionSandboxBindingStore) listTenantBindingKeys(
ctx context.Context,
tenantID uint64,
) ([]SessionSandboxKey, error) {
prefix := fmt.Sprintf(
"weknora:sandbox:session:{%s:%d:", s.namespace, tenantID,
)
const suffix = "}:binding"
pattern := escapeRedisGlob(prefix) + "*" + suffix
var keys []SessionSandboxKey
var cursor uint64
for {
batch, next, err := s.client.Scan(ctx, cursor, pattern, redisBindingScanCount).Result()
if err != nil {
return nil, fmt.Errorf("scan sandbox bindings: %w", err)
}
for _, raw := range batch {
sessionID := strings.TrimSuffix(strings.TrimPrefix(raw, prefix), suffix)
key := SessionSandboxKey{TenantID: tenantID, SessionID: sessionID}
if key.Validate() != nil {
continue
}
keys = append(keys, key)
}
if next == 0 {
return keys, nil
}
cursor = next
}
}
// markBindingStale writes the marked binding back only while the stored one
// still names the same sandbox.
func (s *RedisSessionSandboxBindingStore) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if err := validateBindingMatch(key, expected.Provider, expected.SandboxID); err != nil {
return false, err
}
marked := expected
marked.StaleAt = &staleAt
payload, err := json.Marshal(marked)
if err != nil {
return false, fmt.Errorf("encode stale sandbox binding: %w", err)
}
wrote, err := markBindingStaleIfMatchScript.Run(
ctx,
s.client,
[]string{s.bindingKey(key)},
string(expected.Provider),
expected.SandboxID,
payload,
).Int64()
if err != nil {
return false, fmt.Errorf("mark sandbox binding stale: %w", err)
}
return wrote != 0, nil
}
// escapeRedisGlob quotes the characters SCAN's MATCH treats as wildcards. The
// namespace is operator-supplied and only screened for braces and control
// characters, so a namespace containing "*" would otherwise widen the pattern
// past the workspace it is meant to anchor.
func escapeRedisGlob(literal string) string {
var out strings.Builder
out.Grow(len(literal))
for _, r := range literal {
switch r {
case '\\', '*', '?', '[', ']', '^':
out.WriteByte('\\')
}
out.WriteRune(r)
}
return out.String()
}
// BeginTurn opens a chat-turn lease. The first increment of a session's
// refcount allows the next resolve to rebuild a stale sandbox.
func (s *RedisSessionSandboxBindingStore) BeginTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
ttlMS := sessionTurnLeaseTTL.Milliseconds()
if ttlMS <= 0 {
ttlMS = (30 * time.Minute).Milliseconds()
}
if err := beginTurnScript.Run(ctx, s.client, []string{s.turnKey(key)}, ttlMS).Err(); err != nil {
return fmt.Errorf("begin sandbox turn lease: %w", err)
}
return nil
}
// EndTurn releases one chat-turn lease. The last release drops the lease so
// a later resolve may rebuild a stale sandbox immediately.
func (s *RedisSessionSandboxBindingStore) EndTurn(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := endTurnScript.Run(ctx, s.client, []string{s.turnKey(key)}).Err(); err != nil {
return fmt.Errorf("end sandbox turn lease: %w", err)
}
return nil
}
// TurnState reports whether a chat turn is open and whether its first
// resolve may still rebuild a stale sandbox.
func (s *RedisSessionSandboxBindingStore) TurnState(
ctx context.Context,
key SessionSandboxKey,
) (bool, bool, error) {
if err := key.Validate(); err != nil {
return false, false, err
}
values, err := s.client.HGetAll(ctx, s.turnKey(key)).Result()
if err != nil {
return false, false, fmt.Errorf("read sandbox turn lease: %w", err)
}
if len(values) == 0 {
return false, false, nil
}
_ = s.client.PExpire(ctx, s.turnKey(key), sessionTurnLeaseTTL).Err()
refs, _ := strconv.Atoi(values["refs"])
if refs <= 0 {
return false, false, nil
}
return true, values["rebuild"] == "1", nil
}
// ConsumeTurnRebuild spends the one rebuild allowed for the current turn.
func (s *RedisSessionSandboxBindingStore) ConsumeTurnRebuild(
ctx context.Context,
key SessionSandboxKey,
) error {
if err := key.Validate(); err != nil {
return err
}
if err := consumeTurnRebuildScript.Run(
ctx, s.client, []string{s.turnKey(key)}, sessionTurnLeaseTTL.Milliseconds(),
).Err(); err != nil {
return fmt.Errorf("consume sandbox turn rebuild: %w", err)
}
return nil
}
func (s *RedisSessionSandboxBindingStore) turnKey(key SessionSandboxKey) string {
return "weknora:sandbox:session:{" + s.hashTag(key) + "}:turn"
}
func (s *RedisSessionSandboxBindingStore) bindingKey(key SessionSandboxKey) string {
return "weknora:sandbox:session:{" + s.hashTag(key) + "}:binding"
}
@ -171,6 +395,11 @@ func (s *RedisSessionSandboxBindingStore) hashTag(key SessionSandboxKey) string
return fmt.Sprintf("%s:%d:%s", s.namespace, key.TenantID, key.SessionID)
}
var (
_ tenantBindingScanner = (*RedisSessionSandboxBindingStore)(nil)
_ sessionTurnLeaseStore = (*RedisSessionSandboxBindingStore)(nil)
)
func validateRedisNamespace(namespace string) error {
if strings.ContainsAny(namespace, "{}") {
return errors.New("WEKNORA_REDIS_NAMESPACE must not contain braces")

View File

@ -45,6 +45,22 @@ func TestRedisSessionSandboxBindingStoreContract(t *testing.T) {
testSessionSandboxBindingStore(t, store)
}
func TestRedisSessionSandboxBindingStoreTurnLease(t *testing.T) {
store, client, _ := newRedisBindingTestStore(t)
testSessionTurnLeaseStore(t, store)
key := SessionSandboxKey{TenantID: 42, SessionID: "session-missing-turn"}
require.NoError(t, store.ConsumeTurnRebuild(context.Background(), key))
exists, err := client.Exists(context.Background(), store.turnKey(key)).Result()
require.NoError(t, err)
require.Zero(t, exists, "consuming a missing turn must not create a lease key")
}
func TestRedisSessionSandboxBindingStoreInvalidatesByConfig(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingInvalidateByConfig(t, store)
}
func TestRedisSessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
store, _, _ := newRedisBindingTestStore(t)
testSessionSandboxBindingTenantIsolation(t, store)

View File

@ -78,11 +78,217 @@ func testSessionSandboxBindingTenantIsolation(t *testing.T, store SessionSandbox
require.Equal(t, "sandbox-b", second.SandboxID)
}
// testSessionSandboxBindingInvalidateByConfig is a store-level contract: both
// implementations have to find every binding of one workspace's config without
// enumerating another workspace's, and mark it in place.
func testSessionSandboxBindingInvalidateByConfig(t *testing.T, store SessionSandboxBindingStore) {
t.Helper()
ctx := context.Background()
target := SessionSandboxKey{TenantID: 42, SessionID: "session-target"}
otherConfig := SessionSandboxKey{TenantID: 42, SessionID: "session-other-config"}
otherTenant := SessionSandboxKey{TenantID: 43, SessionID: "session-other-tenant"}
// A binding written before ConfigID existed - the one case a rolling
// upgrade actually produces. It must match no config at all, rather than
// every config, or the first install after an upgrade rebuilds the whole
// deployment's sandboxes.
legacy := SessionSandboxKey{TenantID: 42, SessionID: "session-pre-upgrade"}
create := func(key SessionSandboxKey, configID string) {
binding := validSessionSandboxBinding(key, "sandbox-"+key.SessionID)
binding.ConfigID = configID
created, err := store.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
}
create(target, "cfg-1")
create(otherConfig, "cfg-2")
create(otherTenant, "cfg-1")
create(legacy, "")
marked, err := store.InvalidateByConfig(ctx, 42, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, marked)
got, err := store.Get(ctx, target)
require.NoError(t, err)
require.NotNil(t, got.StaleAt)
require.Equal(t, "sandbox-"+target.SessionID, got.SandboxID,
"marking must not disturb the rest of the binding")
legacyMarked, err := store.InvalidateByConfig(ctx, 42, "")
require.NoError(t, err)
require.Zero(t, legacyMarked,
"an empty ConfigID means 'unknown', not 'the deployment default config'")
got, err = store.Get(ctx, legacy)
require.NoError(t, err)
require.Nil(t, got.StaleAt, "a pre-upgrade binding must survive an install untouched")
for _, key := range []SessionSandboxKey{otherConfig, otherTenant, legacy} {
got, err = store.Get(ctx, key)
require.NoError(t, err)
require.Nil(t, got.StaleAt, "binding %s must be untouched", key.SessionID)
}
marked, err = store.InvalidateByConfig(ctx, 42, "cfg-1")
require.NoError(t, err)
require.Zero(t, marked, "an already marked binding is not marked again")
}
// bindingMarkBudgetSpy reports the budget the marking work is given, once the
// session's lifecycle lock is held.
type bindingMarkBudgetSpy struct {
*MemorySessionSandboxBindingStore
markBudget time.Duration
markHadBudget bool
}
func (s *bindingMarkBudgetSpy) WithLifecycleLock(
ctx context.Context, key SessionSandboxKey, fn func(context.Context) error,
) error {
return s.MemorySessionSandboxBindingStore.WithLifecycleLock(
ctx, key, func(lockCtx context.Context) error {
return fn(lockCtx)
},
)
}
func (s *bindingMarkBudgetSpy) markBindingStale(
ctx context.Context,
key SessionSandboxKey,
expected SessionSandboxBinding,
staleAt time.Time,
) (bool, error) {
if deadline, ok := ctx.Deadline(); ok {
s.markHadBudget = true
s.markBudget = time.Until(deadline)
}
return s.MemorySessionSandboxBindingStore.markBindingStale(ctx, key, expected, staleAt)
}
// The lock-wait cap must not double as the work budget: a mark that waited most
// of the cap for the lock would otherwise be left with a few milliseconds for
// its read plus compare-and-set, and fail with a deadline error that reads like
// a Redis fault.
func TestInvalidateGivesTheMarkItsOwnBudget(t *testing.T) {
t.Parallel()
spy := &bindingMarkBudgetSpy{MemorySessionSandboxBindingStore: NewMemorySessionSandboxBindingStore()}
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-a"}
binding := validSessionSandboxBinding(key, "sandbox-a")
binding.ConfigID = "cfg-1"
created, err := spy.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
marked, err := invalidateBindingsByConfig(ctx, spy, 42, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, marked)
require.True(t, spy.markHadBudget, "the mark still has to be bounded")
require.Greater(t, spy.markBudget, bindingInvalidateLockTimeout,
"the mark must get its own budget, not what is left of the lock-wait cap")
}
// The wait for one session's lock stays capped: the caller holds the per-config
// install lock, so a session that happens to be creating a sandbox right now
// must cost only its own mark.
func TestInvalidateStopsWaitingForALockedSession(t *testing.T) {
t.Parallel()
store := NewMemorySessionSandboxBindingStore()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-busy"}
binding := validSessionSandboxBinding(key, "sandbox-a")
binding.ConfigID = "cfg-1"
created, err := store.Create(ctx, key, binding)
require.NoError(t, err)
require.True(t, created)
held := make(chan struct{})
release := make(chan struct{})
go func() {
_ = store.WithLifecycleLock(ctx, key, func(context.Context) error {
close(held)
<-release
return nil
})
}()
<-held
defer close(release)
start := time.Now()
marked, err := store.InvalidateByConfig(ctx, 42, "cfg-1")
elapsed := time.Since(start)
require.Error(t, err, "the session that could not be marked is reported")
require.Zero(t, marked)
require.Less(t, elapsed, bindingInvalidateLockTimeout+time.Second,
"waiting on one busy session must not hold up the rest of the workspace")
require.GreaterOrEqual(t, elapsed, bindingInvalidateLockTimeout)
}
func TestMemorySessionSandboxBindingStoreInvalidatesByConfig(t *testing.T) {
t.Parallel()
testSessionSandboxBindingInvalidateByConfig(t, NewMemorySessionSandboxBindingStore())
}
func TestMemorySessionSandboxBindingStoreContract(t *testing.T) {
t.Parallel()
testSessionSandboxBindingStore(t, NewMemorySessionSandboxBindingStore())
}
func TestMemorySessionSandboxBindingStoreTurnLease(t *testing.T) {
t.Parallel()
testSessionTurnLeaseStore(t, NewMemorySessionSandboxBindingStore())
}
func testSessionTurnLeaseStore(t *testing.T, store sessionTurnLeaseStore) {
t.Helper()
ctx := context.Background()
key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn"}
active, rebuildOnce, err := store.TurnState(ctx, key)
require.NoError(t, err)
require.False(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.BeginTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.True(t, rebuildOnce)
require.NoError(t, store.BeginTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.True(t, rebuildOnce, "a nested BeginTurn must not reset rebuildOnce")
require.NoError(t, store.ConsumeTurnRebuild(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.EndTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.True(t, active)
require.False(t, rebuildOnce)
require.NoError(t, store.EndTurn(ctx, key))
active, rebuildOnce, err = store.TurnState(ctx, key)
require.NoError(t, err)
require.False(t, active)
require.False(t, rebuildOnce)
cancelled, cancel := context.WithCancel(ctx)
cancel()
require.Error(t, store.BeginTurn(cancelled, key))
}
func TestMemorySessionSandboxBindingStoreSeparatesTenants(t *testing.T) {
t.Parallel()
testSessionSandboxBindingTenantIsolation(t, NewMemorySessionSandboxBindingStore())

View File

@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"log"
"sort"
"strconv"
"strings"
@ -176,6 +177,26 @@ func (l *remoteSessionLifecycle) resolveLocked(
binding = nil
}
// A stale binding is one whose sandbox boots an image the config has since
// replaced. Rebuild waits for a turn boundary: the first resolve of a new
// chat turn may destroy and recreate, later resolves of that same turn
// keep the sandbox so /workspace scratch and in-flight execs survive an
// install that landed mid-turn. A resolve with no turn lease (no AgentQA
// in flight) still rebuilds immediately.
//
// Destroying before rebuilding is not optional: the recovery pass below
// adopts any live sandbox carrying this session's metadata, so a surviving
// one would simply be picked up again.
if binding != nil && binding.StaleAt != nil && l.shouldRebuildStaleBinding(ctx, key) {
if err := l.destroyBindingLocked(ctx, key, *binding); err != nil {
return nil, fmt.Errorf("release stale sandbox binding: %w", err)
}
binding = nil
}
// First resolve of a turn spends rebuildOnce even when nothing was stale,
// so a later install in the same turn cannot tear the sandbox down.
l.consumeTurnRebuild(ctx, key)
if binding != nil {
handle, replace, err := l.connectBinding(ctx, *binding)
if err != nil {
@ -576,6 +597,7 @@ func (l *remoteSessionLifecycle) newBinding(
SandboxID: sandboxID,
TemplateID: templateID,
CreatedAt: createdAt.UTC(),
ConfigID: l.sandboxConfigID,
}
}
@ -589,6 +611,48 @@ func (l *remoteSessionLifecycle) metadata(key SessionSandboxKey) map[string]stri
}
}
// shouldRebuildStaleBinding reports whether this resolve may tear down a
// stale sandbox. No turn, or the first resolve of a new turn, rebuilds. A
// turn that has already used the sandbox keeps it. A lease we cannot read is
// treated as an in-flight turn so a Redis blip cannot destroy /workspace.
func (l *remoteSessionLifecycle) shouldRebuildStaleBinding(
ctx context.Context,
key SessionSandboxKey,
) bool {
leaser, ok := l.bindings.(sessionTurnLeaseStore)
if !ok {
return true
}
active, rebuildOnce, err := leaser.TurnState(ctx, key)
if err != nil {
log.Printf(
"[sandbox] turn lease of session %s unavailable (%v); keeping the current sandbox",
key.SessionID, err,
)
return false
}
if !active {
return true
}
return rebuildOnce
}
func (l *remoteSessionLifecycle) consumeTurnRebuild(
ctx context.Context,
key SessionSandboxKey,
) {
leaser, ok := l.bindings.(sessionTurnLeaseStore)
if !ok {
return
}
if err := leaser.ConsumeTurnRebuild(ctx, key); err != nil {
log.Printf(
"[sandbox] consume turn rebuild of session %s failed: %v",
key.SessionID, err,
)
}
}
func metadataMatches(candidate, required map[string]string) bool {
for key, value := range required {
if candidate[key] != value {

View File

@ -128,6 +128,14 @@ func (s *bindingStoreFaults) DeleteIfMatch(
return s.base.DeleteIfMatch(ctx, key, provider, sandboxID)
}
func (s *bindingStoreFaults) InvalidateByConfig(
ctx context.Context,
tenantID uint64,
configID string,
) (int, error) {
return s.base.InvalidateByConfig(ctx, tenantID, configID)
}
func (s *bindingStoreFaults) WithLifecycleLock(
ctx context.Context,
key SessionSandboxKey,
@ -884,6 +892,186 @@ func TestLifecycleTagsGlobalDefaultConfigWithSentinel(t *testing.T) {
"an empty config ID must still be tagged, so listing can target it")
}
// lifecycleFixture is the smallest complete lifecycle: one memory binding
// store, one fake provider, one live session bound to config "cfg-1".
type lifecycleFixture struct {
lifecycle *remoteSessionLifecycle
bindings *MemorySessionSandboxBindingStore
client *fakeRemoteClient
checker *fakeSessionExistenceChecker
key SessionSandboxKey
}
func newLifecycleFixture(t *testing.T) *lifecycleFixture {
t.Helper()
client := newFakeRemoteClient(SandboxTypeCube)
bindings := NewMemorySessionSandboxBindingStore()
checker := &fakeSessionExistenceChecker{exists: true}
lifecycle, err := newRemoteSessionLifecycle(
client,
bindings,
checker,
RemoteCreateRequest{TemplateID: "template-a"},
time.Minute,
"cfg-1",
)
require.NoError(t, err)
return &lifecycleFixture{
lifecycle: lifecycle,
bindings: bindings,
client: client,
checker: checker,
key: SessionSandboxKey{TenantID: 42, SessionID: "session-a"},
}
}
func TestResolveRecreatesSandboxAfterImageChange(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
first, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
second, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.NotEqual(t, first.ID(), second.ID(),
"a session must pick up the new skill image on its next sandbox use")
require.Contains(t, fx.client.deleteIDs, first.ID(),
"the stale sandbox must be released, not leaked")
}
func TestResolveKeepsStaleSandboxDuringAnOpenTurn(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
require.NoError(t, fx.bindings.BeginTurn(ctx, fx.key))
first, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
second, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.Equal(t, first.ID(), second.ID(),
"a turn already using the sandbox must keep it after an install")
require.NotContains(t, fx.client.deleteIDs, first.ID())
}
func TestResolveRebuildsStaleSandboxOnFirstUseOfNextTurn(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
require.NoError(t, fx.bindings.BeginTurn(ctx, fx.key))
first, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
require.NoError(t, fx.bindings.EndTurn(ctx, fx.key))
require.NoError(t, fx.bindings.BeginTurn(ctx, fx.key))
second, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.NotEqual(t, first.ID(), second.ID(),
"the next turn's first resolve must pick up the new skill image")
require.Contains(t, fx.client.deleteIDs, first.ID())
third, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.Equal(t, second.ID(), third.ID(),
"later resolves of the new turn must keep the rebuilt sandbox")
}
func TestInvalidateDoesNotDisturbOtherConfigs(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
_, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-other")
require.NoError(t, err)
require.Zero(t, n)
}
// Marking is not the same as tearing down: a turn already running in the old
// sandbox must keep working, and the new image arrives on its next use.
func TestInvalidateLeavesTheRunningSandboxAlone(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
handle, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
require.True(t, fx.client.hasSandbox(handle.ID()),
"invalidation must not destroy a sandbox a turn may be using")
binding, err := fx.bindings.Get(ctx, fx.key)
require.NoError(t, err)
require.NotNil(t, binding, "the binding is marked, never dropped outside the lock")
require.NotNil(t, binding.StaleAt)
}
// A second invalidation between two uses must not report the same binding
// twice: the caller logs the count as "how many sessions were affected".
func TestInvalidateSkipsBindingsAlreadyMarked(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
_, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, n)
n, err = fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
require.Zero(t, n)
}
// The rebuilt sandbox must not inherit the mark, or every later use would
// destroy and recreate a perfectly current sandbox.
func TestResolveClearsStalenessAfterRecreating(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
_, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
_, err = fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID, "cfg-1")
require.NoError(t, err)
second, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
binding, err := fx.bindings.Get(ctx, fx.key)
require.NoError(t, err)
require.NotNil(t, binding)
require.Nil(t, binding.StaleAt)
require.Equal(t, "cfg-1", binding.ConfigID,
"the rebuilt binding must record the config it belongs to")
third, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
require.Equal(t, second.ID(), third.ID())
}
// Another workspace's session may sit on the same config ID; marking must stay
// inside the workspace whose image changed.
func TestInvalidateStaysWithinTheWorkspace(t *testing.T) {
ctx := context.Background()
fx := newLifecycleFixture(t)
_, err := fx.lifecycle.Resolve(ctx, fx.key)
require.NoError(t, err)
n, err := fx.bindings.InvalidateByConfig(ctx, fx.key.TenantID+1, "cfg-1")
require.NoError(t, err)
require.Zero(t, n)
}
func newTestLifecycleWithConfigID(t *testing.T, configID string) *remoteSessionLifecycle {
t.Helper()
lifecycle, err := newRemoteSessionLifecycle(

View File

@ -389,6 +389,23 @@ func (m *SessionBoundManager) DestroySession(ctx context.Context, sessionID stri
return m.lifecycle.Destroy(ctx, key)
}
// InvalidateConfigSandboxes marks every session sandbox this config owns stale,
// so each session rebuilds its sandbox from the config's current image on its
// next use, and reports how many bindings were marked.
//
// It is the image-maintenance counterpart to DestroySession: nothing is torn
// down here, so marking cannot delete a sandbox that is executing right now.
// The replacement happens at the session's next resolve, which may be the next
// operation of a turn already in flight; see resolveLocked for that limitation.
func (m *SessionBoundManager) InvalidateConfigSandboxes(
ctx context.Context, tenantID uint64, configID string,
) (int, error) {
if err := m.requireRemoteBackend(); err != nil {
return 0, err
}
return m.bindings.InvalidateByConfig(ctx, tenantID, configID)
}
// CreateSnapshot forwards provider snapshot creation for the live sandbox bound
// to sessionID. Session execution never uses this optional capability; it is
// reserved for skill image maintenance.
@ -448,7 +465,7 @@ func (m *SessionBoundManager) EnsureSessionDir(ctx context.Context, sessionID, d
if err != nil || !ok {
return err
}
if err := m.client.MakeDir(ctx, handle, dir); err != nil {
if err := ignoreExistingDir(m.client.MakeDir(ctx, handle, dir)); err != nil {
return fmt.Errorf("sandbox: ensure session dir %s: %w", dir, err)
}
return nil
@ -475,7 +492,7 @@ func (m *SessionBoundManager) WriteSessionInputFile(
if err != nil {
return err
}
if err := m.client.MakeDir(ctx, handle, path.Dir(clean)); err != nil {
if err := ignoreExistingDir(m.client.MakeDir(ctx, handle, path.Dir(clean))); err != nil {
return fmt.Errorf("sandbox: create input directory: %w", err)
}
if err := m.client.WriteFile(ctx, handle, clean, content); err != nil {
@ -581,7 +598,10 @@ func (m *SessionBoundManager) WriteSessionFile(
if err != nil {
return err
}
if err := m.client.MakeDir(ctx, handle, path.Dir(clean)); err != nil {
// resetSkillDir already created this folder with mkdir -p. Cube's MakeDir
// then reports the existing directory as an error; ignoreExistingDir keeps
// that from aborting the seed of SKILL.md.
if err := ignoreExistingDir(m.client.MakeDir(ctx, handle, path.Dir(clean))); err != nil {
return fmt.Errorf("sandbox: create install directory: %w", err)
}
if err := m.client.WriteFile(ctx, handle, clean, content); err != nil {
@ -756,6 +776,43 @@ func (m *SessionBoundManager) Cleanup(ctx context.Context) error {
// --- internal helpers --------------------------------------------------------
// BeginSessionTurn opens the chat-turn lease for sessionID. The first
// resolve after this may rebuild a stale image; later resolves of the same
// turn keep the sandbox.
func (m *SessionBoundManager) BeginSessionTurn(ctx context.Context, sessionID string) error {
if m == nil {
return nil
}
leaser, ok := m.bindings.(sessionTurnLeaseStore)
if !ok {
return nil
}
key, err := m.sessionKey(ctx, sessionID)
if err != nil {
return err
}
return leaser.BeginTurn(ctx, key)
}
// EndSessionTurn closes the chat-turn lease. It ignores request cancellation
// so a disconnected client still releases the lease.
func (m *SessionBoundManager) EndSessionTurn(ctx context.Context, sessionID string) error {
if m == nil {
return nil
}
leaser, ok := m.bindings.(sessionTurnLeaseStore)
if !ok {
return nil
}
key, err := m.sessionKey(ctx, sessionID)
if err != nil {
return err
}
return leaser.EndTurn(context.WithoutCancel(ctx), key)
}
var _ SessionTurnHolder = (*SessionBoundManager)(nil)
// resolveSession resolves (or lazily creates) the remote sandbox bound to
// sessionID. Persistent path only.
func (m *SessionBoundManager) resolveSession(

View File

@ -211,6 +211,89 @@ func TestExecShellCommandRejectsInvalidWorkDir(t *testing.T) {
require.Contains(t, err.Error(), SessionWorkspaceRoot)
}
// The manager is what the skill install flow holds, so the path from "the
// image changed" to "this session runs on a new sandbox" has to work through
// it, not only through the lifecycle it wraps.
func TestSessionBoundManagerInvalidateConfigSandboxesRebuildsOnNextUse(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
client := newFakeRemoteClient(SandboxTypeCube)
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: client,
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
ConfigID: "cfg-1",
})
require.NoError(t, err)
_, err = mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "", time.Second, nil)
require.NoError(t, err)
before, err := store.Get(ctx, SessionSandboxKey{TenantID: 10000, SessionID: "sess-1"})
require.NoError(t, err)
require.NotNil(t, before)
marked, err := mgr.InvalidateConfigSandboxes(ctx, 10000, "cfg-1")
require.NoError(t, err)
require.Equal(t, 1, marked)
_, err = mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "", time.Second, nil)
require.NoError(t, err)
after, err := store.Get(ctx, SessionSandboxKey{TenantID: 10000, SessionID: "sess-1"})
require.NoError(t, err)
require.NotEqual(t, before.SandboxID, after.SandboxID)
require.False(t, client.hasSandbox(before.SandboxID),
"the sandbox on the old image must be released, not left billing")
}
func TestSessionBoundManagerEndSessionTurnIgnoresCancel(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
store := NewMemorySessionSandboxBindingStore()
cfg := DefaultConfig()
cfg.CubeTemplate = "tpl-test"
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
Config: cfg,
Client: newFakeRemoteClient(SandboxTypeCube),
Store: store,
Checker: &fakeSessionExistenceChecker{exists: true},
SkipHealthProbe: true,
})
require.NoError(t, err)
cancelled, cancel := context.WithCancel(ctx)
require.NoError(t, mgr.BeginSessionTurn(cancelled, "sess-1"))
cancel()
require.NoError(t, mgr.EndSessionTurn(cancelled, "sess-1"))
active, _, err := store.TurnState(ctx, SessionSandboxKey{TenantID: 10000, SessionID: "sess-1"})
require.NoError(t, err)
require.False(t, active)
}
func TestWriteSessionFileSucceedsWhenInstallDirectoryAlreadyExists(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
mgr, client := newSessionManagerExecTestHarness(t)
client.failMakeDirIfExists = true
skillDir, err := SkillDirFor("0d3390ab-6fba-4c8f-8571-30076da51010")
require.NoError(t, err)
require.NoError(t, client.MakeDir(ctx, nil, skillDir),
"resetSkillDir has already created this directory via mkdir -p")
require.NoError(t,
mgr.WriteSessionFile(ctx, "sess-1", skillDir+"/SKILL.md", []byte("---\nname: pptx\n")),
"seeding SKILL.md must not fail just because the skill dir exists")
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
client.mu.Unlock()
require.Len(t, writes, 1)
require.Equal(t, skillDir+"/SKILL.md", writes[0].path)
}
func newSessionManagerExecTestHarness(t *testing.T) (*SessionBoundManager, *fakeRemoteClient) {
t.Helper()

View File

@ -21,6 +21,51 @@ func SkillImageFingerprint(provider, apiKey, apiURL string) string {
return hex.EncodeToString(sum[:])
}
// SkillImageActive reports whether a config's stored snapshot is the image its
// sessions actually boot.
//
// It exists so the agent side can ask the same question the session side
// already answers, from the same inputs: a skill announced to the model while
// sessions keep booting the base template is a skill that cannot be invoked,
// and one hidden while the image carries it is an install nobody can use. It is
// false for backends that cannot snapshot at all, which is what "the base
// template is kept" means for them.
func SkillImageActive(tenantCfg *types.TenantSandboxConfig) bool {
if tenantCfg == nil {
return false
}
// The credentials are read from the stored provider block because
// ResolveEffectiveConfig clears the baseline's before applying it, so
// these are the ones the override is computed from there too.
//
// This switch is on the stored SandboxType alone, while
// ResolveEffectiveConfig falls back to the GLOBAL type when that field is
// empty - so in principle a config with no stored type could boot as e2b
// here and be judged "no image" there. The two agree today only because
// the install flow's skillOwnerFingerprint also returns "" for an empty
// SandboxType, and an empty OwnerFingerprint forces the override to "":
// such a config can never hold a usable image in the first place. That
// agreement is accidental. Keep the fingerprint guard, or make this switch
// take the global fallback too.
switch SandboxType(tenantCfg.SandboxType) {
case SandboxTypeCube:
if tenantCfg.Cube == nil {
return false
}
return skillImageTemplateOverride(
tenantCfg.SkillImage, "cube", tenantCfg.Cube.APIKey, tenantCfg.Cube.APIURL,
) != ""
case SandboxTypeE2B:
if tenantCfg.E2B == nil {
return false
}
return skillImageTemplateOverride(
tenantCfg.SkillImage, "e2b", tenantCfg.E2B.APIKey, tenantCfg.E2B.APIURL,
) != ""
}
return false
}
// skillImageTemplateOverride returns the snapshot ID that should replace the
// base template, or "" when the base template must be kept.
func skillImageTemplateOverride(

View File

@ -368,6 +368,91 @@ func TestResolveEffectiveConfigUsesSkillSnapshotAsE2BTemplate(t *testing.T) {
})
}
// SkillImageActive is what the agent side asks before telling a model about an
// installed skill, so it must agree with the template ResolveEffectiveConfig
// actually boots. Any disagreement means either skills that are announced and
// cannot run, or skills that are in the image and hidden.
func TestSkillImageActiveAgreesWithTheResolvedTemplate(t *testing.T) {
global := DefaultConfig()
cube := func() *types.TenantSandboxConfig {
return &types.TenantSandboxConfig{
SandboxType: "cube",
Cube: &types.CubeSandboxConfig{
APIURL: "https://203.0.113.10", ProxyURL: "https://203.0.113.11",
SandboxDomain: "cube.example.com", APIKey: "key-1", TemplateID: "tpl-base",
},
}
}
fp := SkillImageFingerprint("cube", "key-1", "https://203.0.113.10")
cases := map[string]struct {
config *types.TenantSandboxConfig
want bool
}{
"snapshot owned by the live credentials": {
config: func() *types.TenantSandboxConfig {
cfg := cube()
cfg.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: fp}
return cfg
}(),
want: true,
},
"snapshot from another account": {
config: func() *types.TenantSandboxConfig {
cfg := cube()
cfg.SkillImage = &types.SkillImageConfig{
SnapshotID: "snap-1", OwnerFingerprint: "another-account",
}
return cfg
}(),
want: false,
},
"snapshot with no recorded owner": {
config: func() *types.TenantSandboxConfig {
cfg := cube()
cfg.SkillImage = &types.SkillImageConfig{SnapshotID: "snap-1"}
return cfg
}(),
want: false,
},
"no snapshot yet": {
config: cube(),
want: false,
},
"backend that cannot snapshot": {
config: &types.TenantSandboxConfig{
SandboxType: "docker",
Docker: &types.DockerSandboxConfig{Image: "img"},
SkillImage: &types.SkillImageConfig{
SnapshotID: "snap-1", OwnerFingerprint: fp,
},
},
want: false,
},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
active := SkillImageActive(tc.config)
require.Equal(t, tc.want, active)
eff, err := ResolveEffectiveConfig(tc.config, global)
require.NoError(t, err)
booted := EffectiveTemplateID(eff)
if active {
require.Equal(t, tc.config.SkillImage.SnapshotID, booted)
return
}
if tc.config.SkillImage != nil && tc.config.SkillImage.SnapshotID != "" {
require.NotEqual(t, tc.config.SkillImage.SnapshotID, booted,
"a skill declared unusable must not be the image the session boots")
}
})
}
require.False(t, SkillImageActive(nil))
}
func TestSkillImageFingerprintIsStableAndDiscriminating(t *testing.T) {
a := SkillImageFingerprint("cube", "key-1", "https://a.example.com")
require.Equal(t, a, SkillImageFingerprint("cube", "key-1", "https://a.example.com"))

View File

@ -56,6 +56,11 @@ type AgentConfig struct {
// Runtime-only fields (not persisted)
VLMModelID string `json:"-"` // VLM model ID for tool result image analysis (set from CustomAgent config)
SandboxConfigID string `json:"-"` // Workspace sandbox config ID for skill execution (set from CustomAgent config)
// TenantSkills are the skills installed into the selected sandbox config's
// snapshot image, already narrowed to the ones this run can actually
// invoke. Runtime only: it is derived per turn from the config the agent
// selected, never stored on the agent record.
TenantSkills []*TenantSkillEntity `json:"-"`
// Per-request @mention pins (runtime only; injected as <must_use> in the user message).
PinnedMCPServiceIDs []string `json:"-"`
PinnedSkillNames []string `json:"-"`

View File

@ -235,6 +235,12 @@ const (
// MemoryRecalled: the long-term memories injected into this answer, so
// the UI can show and let the user delete what influenced it.
ResponseTypeMemoryRecalled ResponseType = "memory_recalled"
// ResponseTypeInstallPrompt is the instruction a skill install handed to
// the installer agent. Only the skill install transcript emits this, and
// it emits it first, so replaying the log alone shows what was asked for
// — the console does not have to read the durable prompt row to caption
// the run.
ResponseTypeInstallPrompt ResponseType = "install_prompt"
)
// StreamResponse stream response

View File

@ -307,7 +307,8 @@ func SandboxConfigForResponse(cfg *TenantSandboxConfig, maskSecrets bool) *Tenan
// MergeSandboxConfigForUpdate resolves redacted placeholders in incoming
// against the currently stored config, so a client that never received the
// real secret can submit the rest of the form without wiping it.
// real secret can submit the rest of the form without wiping it. Pointers
// the editor does not own (SkillImage, VolumeMount) are kept from existing.
func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *TenantSandboxConfig {
if incoming == nil {
return nil
@ -346,15 +347,30 @@ func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *Tenan
out.EnvVars = envVars
}
// SkillImage is owned by the skill install/remove path, not the sandbox
// settings form. The editor rebuilds the payload without this field, and a
// crafted PUT must not plant or wipe a snapshot pointer. Copy from the
// stored row (or clear on create) and ignore whatever the client sent.
if existing != nil && existing.SkillImage != nil {
image := *existing.SkillImage
out.SkillImage = &image
} else {
out.SkillImage = nil
// SkillImage and VolumeMount are owned by the install / volume paths, not
// by the sandbox settings form. The editor rebuilds the payload without
// either field, so copying incoming as-is would wipe a live snapshot on
// every runtime save and leave sessions booting the base template while the
// skill rows still claim ready. Reading them from the stored row instead —
// and clearing when there is no stored row — also means a crafted PUT can
// neither plant nor wipe a pointer.
out.SkillImage = nil
out.VolumeMount = nil
if existing != nil {
if existing.SkillImage != nil {
image := *existing.SkillImage
out.SkillImage = &image
}
if existing.VolumeMount != nil {
mount := *existing.VolumeMount
out.VolumeMount = &mount
}
// The runtime form omits skill_rollout. An empty incoming value must
// not reset a saved "new_session" choice; the skills panel sends the
// explicit next_turn token when the admin switches back.
if strings.TrimSpace(out.SkillRollout) == "" {
out.SkillRollout = existing.SkillRollout
}
}
return &out

View File

@ -111,6 +111,67 @@ func TestMergeSandboxConfigForUpdateIgnoresIncomingSkillImageOnCreate(t *testing
require.Nil(t, out.SkillImage, "create must not accept a client-supplied skill image")
}
// The editor never sends skill_image: that pointer is written only by an
// install or a removal. A merge that copied the incoming payload as-is would
// therefore wipe a live snapshot on every "保存运行配置", leaving the skill
// rows in place while every session fell back to the base template. VolumeMount
// is covered here too because the editor omits it for the same reason.
func TestMergeSandboxConfigForUpdateKeepsSkillImageWhenEditorOmitsIt(t *testing.T) {
existing := &TenantSandboxConfig{
SandboxType: "cube",
SkillImage: &SkillImageConfig{
SnapshotID: "snap-2",
Generation: 2,
BaseTemplateID: "base-template",
OwnerFingerprint: "fp-1",
},
VolumeMount: &VolumeMountConfig{Enabled: true, VolumeID: "vol-1"},
}
incoming := &TenantSandboxConfig{
SandboxType: "cube",
Cube: &CubeSandboxConfig{APIURL: "https://cube.example.com"},
}
out := MergeSandboxConfigForUpdate(incoming, existing)
require.NotNil(t, out.SkillImage)
require.Equal(t, "snap-2", out.SkillImage.SnapshotID)
require.Equal(t, 2, out.SkillImage.Generation)
require.Equal(t, "base-template", out.SkillImage.BaseTemplateID)
require.Equal(t, "fp-1", out.SkillImage.OwnerFingerprint)
require.NotNil(t, out.VolumeMount)
require.Equal(t, "vol-1", out.VolumeMount.VolumeID)
out.SkillImage.SnapshotID = "mutated"
require.Equal(t, "snap-2", existing.SkillImage.SnapshotID,
"merge must copy the stored image, not share the pointer")
}
func TestMergeSandboxConfigForUpdateKeepsSkillRolloutWhenEditorOmitsIt(t *testing.T) {
existing := &TenantSandboxConfig{
SandboxType: "cube",
SkillRollout: SkillRolloutNewSession,
}
incoming := &TenantSandboxConfig{
SandboxType: "cube",
Cube: &CubeSandboxConfig{APIURL: "https://cube.example.com"},
}
out := MergeSandboxConfigForUpdate(incoming, existing)
require.Equal(t, SkillRolloutNewSession, out.SkillRollout,
"a runtime save must not reset the skills-panel rollout choice")
}
func TestMergeSandboxConfigForUpdateHonoursExplicitSkillRollout(t *testing.T) {
existing := &TenantSandboxConfig{SkillRollout: SkillRolloutNewSession}
incoming := &TenantSandboxConfig{SkillRollout: SkillRolloutNextTurn}
out := MergeSandboxConfigForUpdate(incoming, existing)
require.Equal(t, SkillRolloutNextTurn, out.SkillRollout)
}
func TestMergeSandboxConfigForUpdateDoesNotMutateInputs(t *testing.T) {
existing := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: "old-e2b"}}
incoming := &TenantSandboxConfig{

View File

@ -175,9 +175,35 @@ func SessionRequiresAdminConsoleRead(s *Session, imPlatform string) bool {
strings.HasPrefix(s.UserID, PrincipalEmbedSession+":") {
return true
}
// Defence in depth for skill maintenance transcripts: the listing hides
// them, and this keeps a leaked session id from being opened by a
// non-admin who happens to own the row.
if IsSkillMaintenanceDescription(s.Description) {
return true
}
return strings.TrimSpace(imPlatform) != ""
}
// IsSkillMaintenanceDescription reports whether description is the reserved
// prefix that hides skill-install sessions from the console list.
func IsSkillMaintenanceDescription(description string) bool {
return strings.HasPrefix(description, SkillMaintenanceSessionMarker)
}
// SanitizeClientSessionDescription keeps the skill-maintenance marker off
// client-writable descriptions. A row that is already a maintenance session
// keeps its stored description so a PUT cannot un-hide it; any other row
// drops a planted marker rather than accepting it.
func SanitizeClientSessionDescription(incoming, existing string) string {
if IsSkillMaintenanceDescription(existing) {
return existing
}
if IsSkillMaintenanceDescription(incoming) {
return ""
}
return incoming
}
// SessionListQuery bundles the parameters for listing sessions.
// UserID empty means "tenant-wide" (used by API-key callers / legacy rows).
// Keyword matches title ILIKE '%keyword%'.

View File

@ -48,8 +48,29 @@ func TestSessionRequiresAdminConsoleRead(t *testing.T) {
t.Fatal("IM-mapped session should require admin")
}
maintenance := &Session{Description: SkillMaintenanceSessionMarker + "install"}
if !SessionRequiresAdminConsoleRead(maintenance, "") {
t.Fatal("maintenance session should require admin")
}
web := &Session{UserID: "alice", Title: "my chat"}
if SessionRequiresAdminConsoleRead(web, "") {
t.Fatal("personal web session should not require admin")
}
}
func TestSanitizeClientSessionDescription(t *testing.T) {
planted := SkillMaintenanceSessionMarker + "install"
if got := SanitizeClientSessionDescription(planted, ""); got != "" {
t.Fatalf("planted marker on create = %q, want empty", got)
}
if got := SanitizeClientSessionDescription(planted, "ordinary"); got != "" {
t.Fatalf("planted marker on update = %q, want empty", got)
}
if got := SanitizeClientSessionDescription("hello", "ordinary"); got != "hello" {
t.Fatalf("ordinary update = %q, want hello", got)
}
if got := SanitizeClientSessionDescription("unhide", planted); got != planted {
t.Fatalf("maintenance row must keep its marker, got %q", got)
}
}

View File

@ -660,6 +660,13 @@ type TenantSandboxConfig struct {
// so a settings-form save cannot wipe or plant the pointer.
SkillImage *SkillImageConfig `json:"skill_image,omitempty"`
// SkillRollout decides whether sessions that already hold a sandbox of
// this config rebuild after a skill install or removal. Empty and
// SkillRolloutNextTurn rebuild on the next chat turn. SkillRolloutNewSession
// leaves those sandboxes on the previous image; only sessions that start
// afterwards boot the new snapshot.
SkillRollout string `json:"skill_rollout,omitempty"`
// ── 后端专属配置(同一时刻只有一个生效,由 SandboxType 决定)───
Cube *CubeSandboxConfig `json:"cube,omitempty"`
@ -793,6 +800,25 @@ type VolumeMountConfig struct {
VolumeOwnerFingerprint string `json:"volume_owner_fingerprint,omitempty"`
}
const (
// SkillRolloutNextTurn rebuilds a live session's sandbox on its next chat
// turn after the skill image changes. This is the default.
SkillRolloutNextTurn = "next_turn"
// SkillRolloutNewSession leaves live sandboxes on the previous image.
// Only a session that starts after the install or removal boots the new one.
SkillRolloutNewSession = "new_session"
)
// RebuildsExistingOnSkillChange reports whether an install or removal should
// mark already-bound sandboxes stale. Unknown values fail toward rebuilding
// so a corrupted row cannot pin every session on a retired image.
func (c *TenantSandboxConfig) RebuildsExistingOnSkillChange() bool {
if c == nil {
return true
}
return strings.TrimSpace(c.SkillRollout) != SkillRolloutNewSession
}
// SkillImageConfig is the pointer to the snapshot that carries the skills
// installed on this sandbox config. Snapshot IDs double as template IDs, so
// nothing else is needed to boot sessions from it.

View File

@ -30,6 +30,14 @@ const (
SkillSnapshotTriggerRebuild = "rebuild"
)
// SkillMaintenanceSessionMarker tags the sessions that skill image operations
// run in. Those sessions carry a real agent transcript that is deliberately
// kept for troubleshooting, but they are infrastructure rather than
// conversations, so the console must never list them. This mirrors how embed
// sessions are classified (EmbedSessionMarkerPrefix): a description prefix,
// so no schema change is needed.
const SkillMaintenanceSessionMarker = "skill_maintenance:"
// TenantSkillEntity is one skill installed onto one sandbox config.
//
// There is deliberately no entry_script / interpreter / smoke_command column:
@ -63,6 +71,13 @@ type TenantSkillEntity struct {
// kept for audit and chain troubleshooting.
InstalledSnapshotID string `gorm:"type:varchar(255)"`
// InstallSessionID / InstallMessageID locate the installer agent's
// transcript for the most recent install of this skill. A re-install
// overwrites them: the previous run's conversation is superseded by the
// one that produced the image now in service.
InstallSessionID string `gorm:"type:varchar(36)"`
InstallMessageID string `gorm:"type:varchar(36)"`
Status string `gorm:"type:varchar(32);not null"`
Error string `gorm:"type:text"`
// InstallingSince drives the stuck-run reaper for both install and remove.

View File

@ -0,0 +1,4 @@
DO $$ BEGIN RAISE NOTICE '[Migration 000087] Dropping install transcript locators from tenant_skills'; END $$;
ALTER TABLE tenant_skills DROP COLUMN IF EXISTS install_session_id;
ALTER TABLE tenant_skills DROP COLUMN IF EXISTS install_message_id;

View File

@ -0,0 +1,10 @@
-- Description: Locators for the installer agent's transcript. The install runs
-- in a maintenance session whose messages are kept for troubleshooting; without
-- these columns the console has no way to find that conversation.
DO $$ BEGIN RAISE NOTICE '[Migration 000087] Adding install transcript locators to tenant_skills'; END $$;
ALTER TABLE tenant_skills ADD COLUMN IF NOT EXISTS install_session_id VARCHAR(36);
ALTER TABLE tenant_skills ADD COLUMN IF NOT EXISTS install_message_id VARCHAR(36);
COMMENT ON COLUMN tenant_skills.install_session_id IS 'Maintenance session of the most recent install; overwritten on re-install';
COMMENT ON COLUMN tenant_skills.install_message_id IS 'Assistant message the installer transcript was streamed into';