WeKnora/internal/handler/skill_handler_test.go

97 lines
2.6 KiB
Go
Raw Normal View History

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>
2026-08-25 03:28:12 +00:00
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"}},
}
fix(agent): scope the @Skill and @MCP pickers to the agent that will run (#3475) * fix(agent): scope the @Skill and @MCP pickers to the agent that will run Both pickers listed the caller's own workspace, but a shared agent invokes its OWNER's skills and MCP services. The two never line up, so for every shared agent: * @Skill was always empty, in every skills mode. GET /skills resolves the sandbox config with (tenant, id), and the agent's config id does not exist in the borrower's workspace - effectiveTenantSkills short-circuits before it reads a single skill row. The response still reported skills_available: true, so the category appeared with nothing under it. * @MCP in "selected" mode was empty for the same reason: the preset holds the owner's service ids, which match nothing in the borrower's catalog. * @MCP in "all" mode was worse than empty. isMCPAllowedByAgent returns true for every enabled service, so the picker offered the BORROWER's own services; resolvePerRequestMCPScope then intersected the mention against the agent's preset, found nothing, and dropped it with only a warning. Resolve the agent when the request carries agent_id + agent_source_tenant_id and read its resources where they live. Only an explicit source workspace takes the share path, so an own-agent request is byte-for-byte unchanged; built-in agent ids exist in every workspace, and falling back to a share lookup without one would let an org member take over the caller's default agent, exactly as session.Handler.resolveAgent already documents. Both endpoints serve only what the agent can actually invoke: * skills: the sandbox config comes from the agent, never from the query, so a borrower cannot name another config in the owner's workspace and enumerate it; "selected" narrows to the configured names and a disabled picker never reaches the owner's inventory at all. * MCP: the agent's explicit preset and nothing else, because that is exactly what resolvePerRequestMCPScope accepts for a shared agent. "all" therefore offers nothing rather than offering services every mention would drop. Whether "all" should become mentionable is a separate decision about that guard, not about the picker. The cross-workspace MCP rows use a narrowed response built field by field. NewMCPServiceResponse reveals endpoint URL, headers, env vars and stdio command to an Admin, and a borrower can be an Admin of their own workspace - that shape must be narrow by construction, not by role. On the client the two lists now follow the selected agent: their cache keys carry it, and the chat input refetches on a switch behind a request token, so a slow response for the agent the user just left cannot overwrite the picker with another workspace's services. * fix(agent): check the c.Error return on the shared-agent picker paths golangci-lint judges pull requests on the lines they introduce, so the repository's older bare c.Error calls are grandfathered while these three are not. Match the _ = c.Error form already used in mcp_service.go.
2026-09-21 05:02:34 +00:00
router := newChatSkillRouter(NewSkillHandler(lister, nil, nil))
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>
2026-08-25 03:28:12 +00:00
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, "unscoped skills must not appear in @")
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>
2026-08-25 03:28:12 +00:00
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"},
},
}
fix(agent): scope the @Skill and @MCP pickers to the agent that will run (#3475) * fix(agent): scope the @Skill and @MCP pickers to the agent that will run Both pickers listed the caller's own workspace, but a shared agent invokes its OWNER's skills and MCP services. The two never line up, so for every shared agent: * @Skill was always empty, in every skills mode. GET /skills resolves the sandbox config with (tenant, id), and the agent's config id does not exist in the borrower's workspace - effectiveTenantSkills short-circuits before it reads a single skill row. The response still reported skills_available: true, so the category appeared with nothing under it. * @MCP in "selected" mode was empty for the same reason: the preset holds the owner's service ids, which match nothing in the borrower's catalog. * @MCP in "all" mode was worse than empty. isMCPAllowedByAgent returns true for every enabled service, so the picker offered the BORROWER's own services; resolvePerRequestMCPScope then intersected the mention against the agent's preset, found nothing, and dropped it with only a warning. Resolve the agent when the request carries agent_id + agent_source_tenant_id and read its resources where they live. Only an explicit source workspace takes the share path, so an own-agent request is byte-for-byte unchanged; built-in agent ids exist in every workspace, and falling back to a share lookup without one would let an org member take over the caller's default agent, exactly as session.Handler.resolveAgent already documents. Both endpoints serve only what the agent can actually invoke: * skills: the sandbox config comes from the agent, never from the query, so a borrower cannot name another config in the owner's workspace and enumerate it; "selected" narrows to the configured names and a disabled picker never reaches the owner's inventory at all. * MCP: the agent's explicit preset and nothing else, because that is exactly what resolvePerRequestMCPScope accepts for a shared agent. "all" therefore offers nothing rather than offering services every mention would drop. Whether "all" should become mentionable is a separate decision about that guard, not about the picker. The cross-workspace MCP rows use a narrowed response built field by field. NewMCPServiceResponse reveals endpoint URL, headers, env vars and stdio command to an Admin, and a borrower can be an Admin of their own workspace - that shape must be narrow by construction, not by role. On the client the two lists now follow the selected agent: their cache keys carry it, and the chat input refetches on a switch behind a request token, so a slow response for the agent the user just left cannot overwrite the picker with another workspace's services. * fix(agent): check the c.Error return on the shared-agent picker paths golangci-lint judges pull requests on the lines they introduce, so the repository's older bare c.Error calls are grandfathered while these three are not. Match the _ = c.Error form already used in mcp_service.go.
2026-09-21 05:02:34 +00:00
router := newChatSkillRouter(NewSkillHandler(lister, nil, nil))
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>
2026-08-25 03:28:12 +00:00
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)
}