diff --git a/frontend/src/api/skill/index.ts b/frontend/src/api/skill/index.ts index 03fb7643..5610fc66 100644 --- a/frontend/src/api/skill/index.ts +++ b/frontend/src/api/skill/index.ts @@ -15,6 +15,7 @@ export interface SkillCatalogInstall { status: string; enabled: boolean; error?: string; + bundle_sha256?: string; updated_at: string; } @@ -66,7 +67,7 @@ export function registerSkillCatalogFromFile( } export function installSkillCatalog(catalogId: string, sandboxConfigIds: string[]) { - return post<{ data: { installs: Record } }>( + return post<{ data: { installs: Record; errors?: Record } }>( `/api/v1/skills/catalog/${catalogId}/install`, { sandbox_config_ids: sandboxConfigIds }, ); diff --git a/frontend/src/components/SandboxSkillsPanel.test.mjs b/frontend/src/components/SandboxSkillsPanel.test.mjs index 68b819a1..0453746a 100644 --- a/frontend/src/components/SandboxSkillsPanel.test.mjs +++ b/frontend/src/components/SandboxSkillsPanel.test.mjs @@ -11,6 +11,7 @@ const manageBlock = source.slice( test('focused skill management expands env vars and transcript without a mid-page save button', () => { assert.match(manageBlock, /skillHasDeclaredEnvs\(managedSkill\)/) assert.match(manageBlock, /onEnvFieldBlur/) + assert.match(source, /isBusy\(skill\) \|\| !hasEnvEdits\(skill\)/) assert.match(manageBlock, /SkillInstallTimeline/) assert.match(manageBlock, /settings\.skills\.manageUninstall/) assert.match(manageBlock, /skill-manage__progress/) diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue index 5b61b15c..ac2e95f5 100644 --- a/frontend/src/components/SandboxSkillsPanel.vue +++ b/frontend/src/components/SandboxSkillsPanel.vue @@ -87,7 +87,7 @@ :value="managedSkill.enabled" :disabled="isBusy(managedSkill)" :loading="togglingId === managedSkill.id" - @change="(v: any) => toggleEnabled(managedSkill, Boolean(v))" + @change="(v: any) => managedSkill && toggleEnabled(managedSkill, Boolean(v))" /> @@ -841,6 +841,7 @@ function envSaveInFlight(skill: ConfigSkill): boolean { } async function saveEnvs(skill: ConfigSkill, silent = false) { + if (isBusy(skill)) return const envs = envPayload(skill) if (Object.keys(envs).length === 0) return if (Object.values(envs).some((value) => !isValidEnvValueLength(value))) { @@ -853,7 +854,7 @@ async function saveEnvs(skill: ConfigSkill, silent = false) { } function onEnvFieldBlur(skill: ConfigSkill) { - if (!hasEnvEdits(skill) || envSaveInFlight(skill)) return + if (isBusy(skill) || !hasEnvEdits(skill) || envSaveInFlight(skill)) return void saveEnvs(skill, true) } diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index a62b1e0c..4ff206bb 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1023,7 +1023,7 @@ export default { selectSkills: 'Select skills', selectSkillsDesc: 'Choose which skills to enable. Uninstalled or not-ready skills cannot be checked.', skillsAllListHint: 'Ready skills on this sandbox will be enabled. Uninstalled ones are not included until you install them.', - skillsListSummary: '{ready} ready, {pending} not installed on this sandbox', + skillsListSummary: '{ready} ready, {pending} not ready on this sandbox', skillsListSummaryReadyOnly: '{ready} ready', noSkillsAvailable: 'The workspace catalog has no skills yet.', skillsNeedSandbox: 'Select a sandbox first.', @@ -1432,6 +1432,8 @@ export default { deleteSuccess: 'Removed from catalog', registerAccepted: 'Added to catalog', installAccepted: 'Install started', + installPartial: 'Started on some sandboxes. {failed} could not start.', + installOutdated: 'Differs from catalog', loadFailed: 'Failed to load', }, mcpService: 'MCP Service', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index df02298b..6ba15a33 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -5329,6 +5329,8 @@ export default { deleteSuccess: '카탈로그에서 삭제했습니다', registerAccepted: '카탈로그에 추가했습니다', installAccepted: '설치를 시작했습니다', + installPartial: '일부 샌드박스에서 설치를 시작했습니다. {failed}곳은 시작하지 못했습니다.', + installOutdated: '카탈로그와 버전이 다름', loadFailed: '불러오지 못했습니다', }, mcpService: 'MCP 서비스', @@ -5733,7 +5735,7 @@ export default { selectSkills: '스킬 선택', selectSkillsDesc: '사용할 스킬을 선택하세요. 설치되지 않았거나 아직 준비되지 않은 스킬은 선택할 수 없습니다.', skillsAllListHint: '이 샌드박스에서 준비된 스킬이 사용됩니다. 설치되지 않은 스킬은 설치해야 「전체」에 포함됩니다.', - skillsListSummary: '준비됨 {ready}개, 이 샌드박스에 미설치 {pending}개', + skillsListSummary: '준비됨 {ready}개, 이 샌드박스에서 아직 사용 불가 {pending}개', skillsListSummaryReadyOnly: '준비됨 {ready}개', noSkillsAvailable: '워크스페이스 카탈로그에 스킬이 없습니다.', skillsNeedSandbox: '먼저 실행 샌드박스를 선택하세요.', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index d05986d5..0433f96d 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -5329,6 +5329,8 @@ export default { deleteSuccess: 'Удалено из каталога', registerAccepted: 'Добавлено в каталог', installAccepted: 'Установка начата', + installPartial: 'Установка начата на части песочниц. {failed} не удалось запустить.', + installOutdated: 'Отличается от каталога', loadFailed: 'Не удалось загрузить', }, mcpService: 'Сервис MCP', @@ -5733,7 +5735,7 @@ export default { selectSkills: 'Выбрать навыки', selectSkillsDesc: 'Отметьте навыки, которые нужно включить. Неустановленные или неготовые навыки выбрать нельзя.', skillsAllListHint: 'Будут включены готовые навыки в этой песочнице. Неустановленные не попадут в «Все», пока их не установить.', - skillsListSummary: '{ready} готовы, {pending} не установлены в эту песочницу', + skillsListSummary: '{ready} готовы, {pending} ещё нельзя включить в этой песочнице', skillsListSummaryReadyOnly: '{ready} готовы', noSkillsAvailable: 'В каталоге пространства ещё нет навыков.', skillsNeedSandbox: 'Сначала выберите песочницу.', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index a593a826..b6a573e5 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -5331,6 +5331,8 @@ export default { deleteSuccess: '已从目录删除', registerAccepted: '已添加到目录', installAccepted: '已开始安装', + installPartial: '部分沙箱已开始安装,{failed} 个未能开始。', + installOutdated: '与目录版本不同', loadFailed: '加载失败', }, mcpService: 'MCP服务', @@ -5735,7 +5737,7 @@ export default { selectSkills: '选择技能', selectSkillsDesc: '勾选要启用的技能。未安装或未就绪的不能勾选。', skillsAllListHint: '将启用此沙箱上已就绪的技能。未安装的不会自动带上,装好后才会纳入「全部」。', - skillsListSummary: '{ready} 个已就绪,{pending} 个未安装到此沙箱', + skillsListSummary: '{ready} 个已就绪,{pending} 个尚未可在此沙箱启用', skillsListSummaryReadyOnly: '{ready} 个已就绪', noSkillsAvailable: '空间目录里还没有技能。', skillsNeedSandbox: '请先选择运行沙箱。', diff --git a/frontend/src/views/agent/AgentEditorModal.test.mjs b/frontend/src/views/agent/AgentEditorModal.test.mjs index efe1908f..fa4b03b4 100644 --- a/frontend/src/views/agent/AgentEditorModal.test.mjs +++ b/frontend/src/views/agent/AgentEditorModal.test.mjs @@ -135,6 +135,8 @@ test('agent skill picker uses the catalog and only enables ready installs', () = assert.match(source, /showCatalogSkillList/) assert.match(source, /skillsSelectionMode\.value !== 'none'/) assert.match(source, /:disabled="!skill\.selectable"/) + assert.match(source, /catalogPendingCount/) + assert.match(source, /installPartial/) assert.match(source, /installCatalogToCurrent/) assert.match(source, /agent\.editor\.installToThisSandbox/) assert.match(source, /skill-pick-list/) diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index 26842053..06d2c370 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -2044,7 +2044,7 @@ const catalogReadyCount = computed(() => ) const catalogPendingCount = computed(() => - catalogSkillRows.value.filter((skill) => !skill.installed || skill.installStatus === 'failed').length, + catalogSkillRows.value.filter((skill) => !skill.selectable).length, ) const skillListSummary = computed(() => { @@ -2117,8 +2117,13 @@ async function installCatalogToCurrent(skill: CatalogSkillRow) { if (!configId || installingCatalogId.value) return installingCatalogId.value = skill.id try { - await installSkillCatalog(skill.id, [configId]) - MessagePlugin.success(t('settings.skills.installAccepted')) + const res = await installSkillCatalog(skill.id, [configId]) + const failed = Object.keys(res?.data?.errors || {}).length + if (failed > 0) { + MessagePlugin.warning(t('settings.skills.installPartial', { failed })) + } else { + MessagePlugin.success(t('settings.skills.installAccepted')) + } await syncInstalledSkills(true) } catch (e: any) { MessagePlugin.error(e?.message || t('settings.sandbox.skillUploadFailed')) diff --git a/frontend/src/views/settings/SkillSettings.test.mjs b/frontend/src/views/settings/SkillSettings.test.mjs index 58084c73..f76dba36 100644 --- a/frontend/src/views/settings/SkillSettings.test.mjs +++ b/frontend/src/views/settings/SkillSettings.test.mjs @@ -26,7 +26,10 @@ test('catalog cards can install onto sandboxes and manage one install', () => { assert.match(source, /skill-card__icon-btn/) assert.match(source, /openCatalogFiles/) assert.match(source, /SkillFilesDrawer/) - assert.match(source, /skill-card__chip-status/) + assert.match(source, /installPartial/) + assert.match(source, /installOutdated/) + assert.match(source, /skill-card__chip--stale/) + assert.match(source, /catalogInstallFailedCount/) assert.match(source, /chevron-right/) assert.match(source, /skill-card__heading/) assert.match(source, /align-items: center/) diff --git a/frontend/src/views/settings/SkillSettings.vue b/frontend/src/views/settings/SkillSettings.vue index 144f72bd..7335a53e 100644 --- a/frontend/src/views/settings/SkillSettings.vue +++ b/frontend/src/views/settings/SkillSettings.vue @@ -100,9 +100,9 @@ :key="inst.skill_id" type="button" class="skill-card__chip" - :class="installChipClass(inst)" + :class="installChipClass(item, inst)" :disabled="!recordFor(inst.sandbox_config_id)" - :title="installTooltip(inst)" + :title="installTooltip(item, inst)" :aria-label="$t('settings.skills.manageOnSandbox', { name: installName(inst) })" @click="openManage(item, inst)" > @@ -117,8 +117,8 @@ size="xs" /> {{ installName(inst) }} - - {{ installChipStatus(inst) }} + + {{ installChipStatus(item, inst) }} } } | null | undefined): number { + return Object.keys(res?.data?.errors || {}).length +} + async function handleAddPrimary() { if (addPrimaryLoading.value || addPrimaryDisabled.value) return if (addStep.value === 0) { @@ -835,8 +851,13 @@ async function handleAddPrimary() { installing.value = true try { await ensureInstallerModelIfNeeded(targets) - await installSkillCatalog(catalogId, targets) - MessagePlugin.success(t('settings.skills.installAccepted')) + const res = await installSkillCatalog(catalogId, targets) + const failed = catalogInstallFailedCount(res) + if (failed > 0) { + MessagePlugin.warning(t('settings.skills.installPartial', { failed })) + } else { + MessagePlugin.success(t('settings.skills.installAccepted')) + } showAdd.value = false await loadCatalog() revealCatalog(catalogId) @@ -865,8 +886,13 @@ async function confirmInstall() { installing.value = true try { await ensureInstallerModelIfNeeded(installTargetIds.value) - await installSkillCatalog(item.id, [...installTargetIds.value]) - MessagePlugin.success(t('settings.skills.installAccepted')) + const res = await installSkillCatalog(item.id, [...installTargetIds.value]) + const failed = catalogInstallFailedCount(res) + if (failed > 0) { + MessagePlugin.warning(t('settings.skills.installPartial', { failed })) + } else { + MessagePlugin.success(t('settings.skills.installAccepted')) + } showInstall.value = false await loadCatalog() revealCatalog(item.id) @@ -1284,6 +1310,12 @@ onUnmounted(() => { color: var(--td-text-color-placeholder); } + &--stale { + color: var(--td-warning-color); + background: color-mix(in srgb, var(--td-warning-color) 10%, transparent); + border-color: color-mix(in srgb, var(--td-warning-color) 24%, transparent); + } + &--add { padding: 3px 7px; border: 1px dashed var(--td-component-stroke); diff --git a/internal/application/service/tenant_skill_bundle.go b/internal/application/service/tenant_skill_bundle.go index a4a01b7d..bfe9a36c 100644 --- a/internal/application/service/tenant_skill_bundle.go +++ b/internal/application/service/tenant_skill_bundle.go @@ -271,17 +271,32 @@ func skillBundleFromFiles(archive []byte, files map[string][]byte) (*SkillBundle return nil, fmt.Errorf("%w: %v", ErrSkillBundleInvalid, err) } - sum := sha256.Sum256(archive) return &SkillBundle{ Name: skill.Name, Version: version, Description: skill.Description, Instructions: skill.Instructions, - SHA256: hex.EncodeToString(sum[:]), + SHA256: skillArchiveSHA256(archive), Files: files, }, nil } +func skillArchiveSHA256(archive []byte) string { + sum := sha256.Sum256(archive) + return hex.EncodeToString(sum[:]) +} + +// archiveMatchesSHA reports whether archive is the digest the row claims. +// An empty expected digest is treated as unknown, not as a match against +// whatever happens to be on disk — callers that want a fallback must opt in. +func archiveMatchesSHA(archive []byte, want string) bool { + want = strings.TrimSpace(want) + if want == "" || len(archive) == 0 { + return false + } + return skillArchiveSHA256(archive) == want +} + // zipSkillFiles writes a deterministic skill-root zip so a remote archive that // had to be re-rooted can go through the same InstallSkill path as an upload. func zipSkillFiles(files map[string][]byte) ([]byte, error) { diff --git a/internal/application/service/tenant_skill_catalog.go b/internal/application/service/tenant_skill_catalog.go index a83dfddc..ef9762b7 100644 --- a/internal/application/service/tenant_skill_catalog.go +++ b/internal/application/service/tenant_skill_catalog.go @@ -23,19 +23,20 @@ type SkillCatalogInstallView struct { Status string `json:"status"` Enabled bool `json:"enabled"` Error string `json:"error,omitempty"` + BundleSHA256 string `json:"bundle_sha256,omitempty"` UpdatedAt time.Time `json:"updated_at"` } // SkillCatalogView is a tenant skill definition plus its sandbox installations. type SkillCatalogView struct { - ID string `json:"id"` - Name string `json:"name"` - Version string `json:"version,omitempty"` - Description string `json:"description,omitempty"` - BundleSHA256 string `json:"bundle_sha256,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - Installations []SkillCatalogInstallView `json:"installations"` + ID string `json:"id"` + Name string `json:"name"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + BundleSHA256 string `json:"bundle_sha256,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + Installations []SkillCatalogInstallView `json:"installations"` } // ListCatalog returns every workspace skill definition and which sandbox @@ -81,13 +82,24 @@ func (s *TenantSkillService) ListCatalog( out := make([]SkillCatalogView, 0, len(catalogs)+len(unattached)) seenName := make(map[string]struct{}, len(catalogs)) + seenCatalog := make(map[string]struct{}, len(catalogs)) for _, cat := range catalogs { if cat == nil { continue } seenName[cat.Name] = struct{}{} + seenCatalog[cat.ID] = struct{}{} out = append(out, catalogView(cat, byCatalog[cat.ID], configByID)) } + // Installs whose catalog row was deleted (or never existed) would otherwise + // vanish: they are not unattached (catalog_id is set) and they are not + // rendered under any live definition. + for catalogID, rows := range byCatalog { + if _, ok := seenCatalog[catalogID]; ok { + continue + } + unattached = append(unattached, rows...) + } // Rows that predate catalog_id (or tests that insert installs directly) // still need to show up as definitions so the settings page is complete. for _, row := range unattached { @@ -142,6 +154,7 @@ func installView( Status: row.Status, Enabled: row.Enabled, Error: row.Error, + BundleSHA256: row.BundleSHA256, UpdatedAt: row.UpdatedAt, } if cfg := configByID[row.SandboxConfigID]; cfg != nil { @@ -174,12 +187,20 @@ func (s *TenantSkillService) RegisterCatalogFromSource( return s.RegisterCatalogFromArchive(ctx, tenantID, archive) } +// CatalogInstallResult is the per-sandbox outcome of one catalog install call. +// Partial success is a successful HTTP accept with Errors filled in, not a +// silent 202: the caller has to be able to tell which configs never started. +type CatalogInstallResult struct { + Installs map[string]string `json:"installs"` + Errors map[string]string `json:"errors,omitempty"` +} + // InstallCatalogToConfigs copies a catalog skill onto each named sandbox using // the existing image-install pipeline. Missing configs are skipped with an // error; partial success is returned so the caller can show per-config status. func (s *TenantSkillService) InstallCatalogToConfigs( ctx context.Context, tenantID uint64, catalogID string, configIDs []string, -) (map[string]string, error) { +) (*CatalogInstallResult, error) { catalog, err := s.resolveCatalog(ctx, tenantID, catalogID) if err != nil { return nil, err @@ -194,24 +215,31 @@ func (s *TenantSkillService) InstallCatalogToConfigs( return nil, apperrors.NewBadRequestError("at least one sandbox is required") } - accepted := make(map[string]string, len(ids)) + result := &CatalogInstallResult{ + Installs: make(map[string]string, len(ids)), + Errors: make(map[string]string), + } var firstErr error for _, configID := range ids { skillID, installErr := s.InstallSkill(ctx, tenantID, configID, archive) if installErr != nil { logger.Warnf(ctx, "[skill] install catalog %s onto config %s failed: %v", catalogID, configID, installErr) + result.Errors[configID] = skillUserErrorMessage(installErr) if firstErr == nil { firstErr = installErr } continue } - accepted[configID] = skillID + result.Installs[configID] = skillID } - if len(accepted) == 0 { - return nil, firstErr + if len(result.Errors) == 0 { + result.Errors = nil } - return accepted, nil + if len(result.Installs) == 0 { + return result, firstErr + } + return result, nil } // DeleteCatalog removes a definition that has no remaining installations. @@ -229,13 +257,10 @@ func (s *TenantSkillService) DeleteCatalog( if err != nil { return err } - live := 0 for _, row := range installs { - if row != nil && row.Status != types.SkillStatusRemoving { - live++ + if row == nil { + continue } - } - if live > 0 { return apperrors.NewConflictError( "remove this skill from every sandbox before deleting it from the catalog") } @@ -251,14 +276,18 @@ func (s *TenantSkillService) upsertCatalogFromBundle( } now := s.now() if existing != nil { + stored, err := s.storeCatalogBundle(ctx, tenantID, existing, archive, requireStore) + if err != nil { + return nil, err + } + if !stored { + return existing, nil + } existing.Version = bundle.Version existing.Description = bundle.Description existing.Instructions = bundle.Instructions existing.BundleSHA256 = bundle.SHA256 existing.UpdatedAt = now - if err := s.storeCatalogBundle(ctx, tenantID, existing, archive, requireStore); err != nil { - return nil, err - } if err := s.skills.UpdateCatalog(ctx, existing); err != nil { return nil, err } @@ -268,12 +297,16 @@ func (s *TenantSkillService) upsertCatalogFromBundle( row := &types.TenantSkillCatalogEntity{ ID: uuid.NewString(), TenantID: tenantID, Name: bundle.Name, Version: bundle.Version, Description: bundle.Description, - Instructions: bundle.Instructions, BundleSHA256: bundle.SHA256, - CreatedAt: now, UpdatedAt: now, + Instructions: bundle.Instructions, + CreatedAt: now, UpdatedAt: now, } - if err := s.storeCatalogBundle(ctx, tenantID, row, archive, requireStore); err != nil { + stored, err := s.storeCatalogBundle(ctx, tenantID, row, archive, requireStore) + if err != nil { return nil, err } + if stored { + row.BundleSHA256 = bundle.SHA256 + } if err := s.skills.CreateCatalog(ctx, row); err != nil { if !isSkillNameConflict(err) { return nil, err @@ -292,29 +325,40 @@ func (s *TenantSkillService) upsertCatalogFromBundle( func (s *TenantSkillService) storeCatalogBundle( ctx context.Context, tenantID uint64, catalog *types.TenantSkillCatalogEntity, archive []byte, requireStore bool, -) error { +) (bool, error) { if catalog == nil || len(archive) == 0 { - return nil + return false, nil } fs, err := s.fileServiceForTenant(ctx, tenantID) if err != nil { if requireStore { - return err + return false, err } logger.Warnf(ctx, "[skill] catalog bundle storage unavailable: %v", err) - return nil + return false, nil } ref, err := fs.SaveBytes(ctx, archive, tenantID, fmt.Sprintf("tenant-skills/catalog/%s.zip", catalog.ID), false) if err != nil { if requireStore { - return fmt.Errorf("store catalog bundle: %w", err) + return false, fmt.Errorf("store catalog bundle: %w", err) } logger.Warnf(ctx, "[skill] catalog bundle store failed: %v", err) - return nil + return false, nil } catalog.BundleRef = ref - return nil + return true, nil +} + +func skillUserErrorMessage(err error) string { + if err == nil { + return "" + } + var app *apperrors.AppError + if errors.As(err, &app) && strings.TrimSpace(app.Message) != "" { + return app.Message + } + return err.Error() } func (s *TenantSkillService) resolveCatalog( @@ -416,6 +460,7 @@ func (s *TenantSkillService) catalogBundleArchive( if catalog == nil { return nil, apperrors.NewNotFoundError("skill not found") } + wantSHA := strings.TrimSpace(catalog.BundleSHA256) tryRow := func(row *types.TenantSkillEntity) ([]byte, bool) { if row == nil || strings.TrimSpace(row.BundleRef) == "" { return nil, false @@ -424,6 +469,9 @@ func (s *TenantSkillService) catalogBundleArchive( if err != nil || len(archive) == 0 { return nil, false } + if wantSHA != "" && !archiveMatchesSHA(archive, wantSHA) { + return nil, false + } return archive, true } diff --git a/internal/application/service/tenant_skill_catalog_test.go b/internal/application/service/tenant_skill_catalog_test.go index ffa825d6..8afaaa02 100644 --- a/internal/application/service/tenant_skill_catalog_test.go +++ b/internal/application/service/tenant_skill_catalog_test.go @@ -2,9 +2,12 @@ package service import ( "context" + "errors" + "strings" "testing" "github.com/Tencent/WeKnora/internal/application/repository" + apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/types" "github.com/stretchr/testify/require" "gorm.io/driver/sqlite" @@ -63,3 +66,92 @@ func TestResolveCatalogFindsLegacySkillID(t *testing.T) { require.Equal(t, "pdf", cat.Name) require.Equal(t, "local://7/tenant-skills/sk-old.zip", cat.BundleRef) } + +func catalogTestRepo(t *testing.T, dsn string) repository.TenantSkillRepository { + t.Helper() + db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) + require.NoError(t, err) + require.NoError(t, db.AutoMigrate( + &types.TenantSkillEntity{}, &types.TenantSkillCatalogEntity{}, + &types.TenantSkillSnapshotEntity{}, &types.TenantUserEnvVar{}, + )) + return repository.NewTenantSkillRepository(db) +} + +func TestListCatalogShowsInstallsWhoseCatalogWasDeleted(t *testing.T) { + repo := catalogTestRepo(t, "file:catalog-orphan?mode=memory&cache=shared") + ctx := context.Background() + require.NoError(t, repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{ + ID: "cat-gone", TenantID: 7, Name: "pdf", + })) + require.NoError(t, repo.CreateSkill(ctx, &types.TenantSkillEntity{ + ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-a", CatalogID: "cat-gone", + Name: "pdf", Status: types.SkillStatusReady, Enabled: true, + })) + require.NoError(t, repo.DeleteCatalog(ctx, 7, "cat-gone")) + + svc := NewTenantSkillService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + list, err := svc.ListCatalog(ctx, 7) + require.NoError(t, err) + require.Len(t, list, 1) + require.Equal(t, "pdf", list[0].Name) + require.Len(t, list[0].Installations, 1) + require.Equal(t, "sk-1", list[0].Installations[0].SkillID) +} + +func TestDeleteCatalogRefusesWhileARemovalIsInFlight(t *testing.T) { + repo := catalogTestRepo(t, "file:catalog-removing?mode=memory&cache=shared") + ctx := context.Background() + require.NoError(t, repo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{ + ID: "cat-pdf", TenantID: 7, Name: "pdf", + })) + require.NoError(t, repo.CreateSkill(ctx, &types.TenantSkillEntity{ + ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-a", CatalogID: "cat-pdf", + Name: "pdf", Status: types.SkillStatusRemoving, Enabled: true, + })) + + svc := NewTenantSkillService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + err := svc.DeleteCatalog(ctx, 7, "cat-pdf") + require.Error(t, err) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok) + require.Equal(t, 409, appErr.HTTPCode) +} + +func TestUpsertCatalogDoesNotStampSHAWhenStoreFails(t *testing.T) { + fx := newInstallFixture(t) + fx.saveErr = errors.New("disk full") + ctx := context.Background() + oldSHA := strings.Repeat("c", 64) + require.NoError(t, fx.skillRepo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{ + ID: "cat-1", TenantID: 7, Name: "pdf-tools", + BundleRef: "file://old.zip", BundleSHA256: oldSHA, + })) + archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD}) + bundle, err := ParseSkillBundle(archive) + require.NoError(t, err) + require.NotEqual(t, oldSHA, bundle.SHA256) + + got, err := fx.svc.upsertCatalogFromBundle(ctx, 7, bundle, archive, false) + require.NoError(t, err) + require.Equal(t, oldSHA, got.BundleSHA256) + require.Equal(t, "file://old.zip", got.BundleRef) +} + +func TestInstallCatalogToConfigsReportsPartialFailure(t *testing.T) { + fx := newInstallFixture(t) + ctx := context.Background() + archive := zipBundle(t, map[string]string{ + "SKILL.md": validSkillMD, + "scripts/extract.py": "print('hi')\n", + }) + cat, err := fx.svc.RegisterCatalogFromArchive(ctx, 7, archive) + require.NoError(t, err) + require.NotNil(t, cat) + + result, err := fx.svc.InstallCatalogToConfigs(ctx, 7, cat.ID, []string{"cfg-1", "missing"}) + require.NoError(t, err) + require.NotNil(t, result) + require.Contains(t, result.Installs, "cfg-1") + require.Equal(t, "sandbox config not found", result.Errors["missing"]) +} diff --git a/internal/application/service/tenant_skill_files.go b/internal/application/service/tenant_skill_files.go index c1875c60..79fcb05e 100644 --- a/internal/application/service/tenant_skill_files.go +++ b/internal/application/service/tenant_skill_files.go @@ -100,9 +100,19 @@ func (s *TenantSkillService) skillBundleArchive( if skill == nil { return nil, apperrors.NewNotFoundError("skill not found") } + hasRef := strings.TrimSpace(skill.BundleRef) != "" if archive, ok := s.trySkillBundle(ctx, tenantID, skill); ok { return archive, nil } + if hasRef { + // The install named a blob that we could not read. Only substitute the + // catalog copy when it is the same digest — otherwise the admin would + // be looking at a different version than the image. + if archive, err := s.sameDigestCatalogArchive(ctx, tenantID, skill); err == nil && len(archive) > 0 { + return archive, nil + } + return nil, apperrors.NewNotFoundError("skill files are not available") + } if cid := strings.TrimSpace(skill.CatalogID); cid != "" { if archive, err := s.loadCatalogArchive(ctx, tenantID, cid); err == nil && len(archive) > 0 { return archive, nil @@ -114,6 +124,26 @@ func (s *TenantSkillService) skillBundleArchive( return nil, apperrors.NewNotFoundError("skill files are not available") } +func (s *TenantSkillService) sameDigestCatalogArchive( + ctx context.Context, tenantID uint64, skill *types.TenantSkillEntity, +) ([]byte, error) { + if skill == nil || strings.TrimSpace(skill.BundleSHA256) == "" { + return nil, apperrors.NewNotFoundError("skill files are not available") + } + cid := strings.TrimSpace(skill.CatalogID) + if cid == "" { + cid = skill.ID + } + archive, err := s.loadCatalogArchive(ctx, tenantID, cid) + if err != nil { + return nil, err + } + if !archiveMatchesSHA(archive, skill.BundleSHA256) { + return nil, apperrors.NewNotFoundError("skill files are not available") + } + return archive, nil +} + func (s *TenantSkillService) trySkillBundle( ctx context.Context, tenantID uint64, skill *types.TenantSkillEntity, ) ([]byte, bool) { diff --git a/internal/application/service/tenant_skill_files_test.go b/internal/application/service/tenant_skill_files_test.go index 386b8c86..32af40d2 100644 --- a/internal/application/service/tenant_skill_files_test.go +++ b/internal/application/service/tenant_skill_files_test.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/base64" + "strings" "sync" "testing" @@ -171,6 +172,32 @@ func TestProjectSkillFileContentMarksBinaryWithoutInlining(t *testing.T) { require.Empty(t, got.Content) } +func TestListSkillFilesDoesNotFallbackToADifferentCatalogBundle(t *testing.T) { + fx := newInstallFixture(t) + ctx := context.Background() + other := zipBundle(t, map[string]string{ + "SKILL.md": validSkillMD, + "scripts/extract.py": "print('other')\n", + }) + fx.storedBundles = map[string][]byte{"file://catalog.zip": other} + require.NoError(t, fx.skillRepo.CreateCatalog(ctx, &types.TenantSkillCatalogEntity{ + ID: "cat-1", TenantID: 7, Name: "pdf-tools", + BundleRef: "file://catalog.zip", BundleSHA256: skillArchiveSHA256(other), + })) + skill, err := fx.skillRepo.GetSkill(ctx, 7, "cfg-1", "sk-1") + require.NoError(t, err) + skill.CatalogID = "cat-1" + skill.BundleRef = "file://missing.zip" + skill.BundleSHA256 = strings.Repeat("a", 64) + require.NoError(t, fx.skillRepo.UpdateSkill(ctx, skill)) + + _, err = fx.svc.ListSkillFiles(ctx, 7, "cfg-1", "sk-1") + require.Error(t, err) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok) + require.Equal(t, 404, appErr.HTTPCode) +} + func (f *installFixture) seedStoredSkillBundle(t *testing.T) { t.Helper() archive, err := zipSkillFiles(map[string][]byte{ diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.go index 792534ad..90438d99 100644 --- a/internal/application/service/tenant_skill_install.go +++ b/internal/application/service/tenant_skill_install.go @@ -72,9 +72,20 @@ func (s *TenantSkillService) InstallSkill( return "", err } if s.canSkipInstall(ctx, existing, bundle) { + catalog, catalogErr := s.upsertCatalogFromBundle(ctx, tenantID, bundle, archive, false) + if catalogErr != nil { + return "", fmt.Errorf("record skill catalog: %w", catalogErr) + } if err := s.refreshSkippedBundle(ctx, existing, archive); err != nil { return "", fmt.Errorf("store bundle for skill %s: %w", existing.ID, err) } + if catalog != nil && existing.CatalogID != catalog.ID { + if err := s.updateSkillFields(ctx, tenantID, configID, existing.ID, func(e *types.TenantSkillEntity) { + e.CatalogID = catalog.ID + }); err != nil { + return "", err + } + } return existing.ID, nil } @@ -100,7 +111,7 @@ func (s *TenantSkillService) InstallSkill( if err := s.skills.CreateSkill(ctx, &types.TenantSkillEntity{ ID: skillID, TenantID: tenantID, SandboxConfigID: configID, CatalogID: catalogID, - Name: bundle.Name, Version: bundle.Version, + Name: bundle.Name, Version: bundle.Version, Description: bundle.Description, Instructions: bundle.Instructions, BundleSHA256: bundle.SHA256, Enabled: true, Status: types.SkillStatusInstalling, InstallingSince: &now, diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index 635df9ac..342e803c 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -565,9 +565,11 @@ func TestInstallSkillSkipsWhenReadyWithTheSameArchive(t *testing.T) { require.Empty(t, fx.sessionCalls, "the same bytes must not boot a billed sandbox") require.NotContains(t, fx.events, "create-snapshot") require.Nil(t, fx.configRepo.saved, "the image pointer must stay where it is") - require.Equal(t, 1, fx.savedBundles, + require.GreaterOrEqual(t, fx.savedBundles, 1, "a no-op re-upload must still refresh the stored archive for read_skill") require.Equal(t, "file://bundle.zip", skill.BundleRef) + require.NotEmpty(t, skill.CatalogID, + "a skip must still attach the install to the workspace catalog") } func TestInstallSkillRetriesAFailedSkillWithTheSameArchive(t *testing.T) { diff --git a/internal/handler/skill_catalog.go b/internal/handler/skill_catalog.go index 89100dad..333947aa 100644 --- a/internal/handler/skill_catalog.go +++ b/internal/handler/skill_catalog.go @@ -8,6 +8,7 @@ import ( "github.com/gin-gonic/gin" + "github.com/Tencent/WeKnora/internal/application/service" apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/types" secutils "github.com/Tencent/WeKnora/internal/utils" @@ -141,14 +142,24 @@ func (h *SkillHandler) InstallCatalog(c *gin.Context) { _ = c.Error(apperrors.NewBadRequestError("invalid install request")) return } - accepted, err := h.catalog.InstallCatalogToConfigs( + result, err := h.catalog.InstallCatalogToConfigs( c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), req.SandboxConfigIDs, ) if err != nil { respondSkillServiceError(c, err) return } - c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"installs": accepted}}) + if result == nil { + result = &service.CatalogInstallResult{} + } + data := gin.H{"installs": result.Installs} + if len(result.Errors) > 0 { + data["errors"] = result.Errors + } + c.JSON(http.StatusAccepted, gin.H{ + "success": len(result.Errors) == 0, + "data": data, + }) } // DeleteCatalog godoc diff --git a/internal/handler/skill_catalog_test.go b/internal/handler/skill_catalog_test.go index cb1d54f7..8648489a 100644 --- a/internal/handler/skill_catalog_test.go +++ b/internal/handler/skill_catalog_test.go @@ -19,11 +19,12 @@ import ( ) type fakeSkillCatalog struct { - list []service.SkillCatalogView - registerID string - installs map[string]string - deleteErr error - source string + list []service.SkillCatalogView + registerID string + installs map[string]string + installErrs map[string]string + deleteErr error + source string } func (f *fakeSkillCatalog) ListCatalog(context.Context, uint64) ([]service.SkillCatalogView, error) { @@ -45,8 +46,8 @@ func (f *fakeSkillCatalog) RegisterCatalogFromSource( func (f *fakeSkillCatalog) InstallCatalogToConfigs( context.Context, uint64, string, []string, -) (map[string]string, error) { - return f.installs, nil +) (*service.CatalogInstallResult, error) { + return &service.CatalogInstallResult{Installs: f.installs, Errors: f.installErrs}, nil } func (f *fakeSkillCatalog) DeleteCatalog(context.Context, uint64, string) error { @@ -131,6 +132,34 @@ func TestInstallCatalogAcceptsPerConfigIDs(t *testing.T) { require.Equal(t, http.StatusAccepted, w.Code) } +func TestInstallCatalogIncludesPerConfigErrors(t *testing.T) { + catalog := &fakeSkillCatalog{ + installs: map[string]string{"cfg-1": "sk-1"}, + installErrs: map[string]string{"cfg-2": "sandbox config not found"}, + } + router := newCatalogRouter(NewSkillHandler(&fakeUsableSkillLister{}, catalog)) + + body, err := json.Marshal(map[string][]string{"sandbox_config_ids": {"cfg-1", "cfg-2"}}) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/skills/catalog/cat-1/install", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusAccepted, w.Code) + + var payload struct { + Success bool `json:"success"` + Data struct { + Installs map[string]string `json:"installs"` + Errors map[string]string `json:"errors"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload)) + require.False(t, payload.Success) + require.Equal(t, "sk-1", payload.Data.Installs["cfg-1"]) + require.Equal(t, "sandbox config not found", payload.Data.Errors["cfg-2"]) +} + func TestDeleteCatalogRefusesWhileInstalled(t *testing.T) { catalog := &fakeSkillCatalog{ deleteErr: apperrors.NewConflictError("remove this skill from every sandbox"), diff --git a/internal/handler/skill_handler.go b/internal/handler/skill_handler.go index 53db4e97..9f84c86c 100644 --- a/internal/handler/skill_handler.go +++ b/internal/handler/skill_handler.go @@ -26,7 +26,7 @@ type skillCatalogService interface { ListCatalog(ctx context.Context, tenantID uint64) ([]service.SkillCatalogView, error) RegisterCatalogFromArchive(ctx context.Context, tenantID uint64, archive []byte) (*types.TenantSkillCatalogEntity, error) RegisterCatalogFromSource(ctx context.Context, tenantID uint64, source string) (*types.TenantSkillCatalogEntity, error) - InstallCatalogToConfigs(ctx context.Context, tenantID uint64, catalogID string, configIDs []string) (map[string]string, error) + InstallCatalogToConfigs(ctx context.Context, tenantID uint64, catalogID string, configIDs []string) (*service.CatalogInstallResult, error) DeleteCatalog(ctx context.Context, tenantID uint64, catalogID string) error ListCatalogFiles(ctx context.Context, tenantID uint64, catalogID string) ([]service.SkillFileEntry, error) ReadCatalogFile(ctx context.Context, tenantID uint64, catalogID, relativePath string) (*service.SkillFileContent, error) diff --git a/migrations/versioned/000090_skill_catalog.up.sql b/migrations/versioned/000090_skill_catalog.up.sql index bdb3da65..a8c4f724 100644 --- a/migrations/versioned/000090_skill_catalog.up.sql +++ b/migrations/versioned/000090_skill_catalog.up.sql @@ -29,9 +29,10 @@ ALTER TABLE tenant_skills ADD COLUMN IF NOT EXISTS catalog_id VARCHAR(36); CREATE INDEX IF NOT EXISTS idx_tenant_skills_catalog ON tenant_skills (catalog_id); --- One catalog row per (tenant, name), using the oldest live install as the id --- so existing rows keep a stable identity. Later installs of the same name --- point at it via catalog_id. +-- One catalog row per (tenant, name). Names are the workspace identity, so +-- same-name installs on different sandboxes collapse here. Prefer a row that +-- still has a stored archive, then the most recently updated one, so the +-- definition matches what operators last wrote rather than the first upload. INSERT INTO tenant_skill_catalog ( id, tenant_id, name, version, description, instructions, bundle_ref, bundle_sha256, created_at, updated_at @@ -41,7 +42,10 @@ SELECT DISTINCT ON (tenant_id, name) bundle_ref, bundle_sha256, created_at, updated_at FROM tenant_skills WHERE deleted_at IS NULL -ORDER BY tenant_id, name, created_at ASC +ORDER BY tenant_id, name, + CASE WHEN bundle_ref IS NULL OR bundle_ref = '' THEN 1 ELSE 0 END, + updated_at DESC, + created_at DESC ON CONFLICT (id) DO NOTHING; UPDATE tenant_skills AS s