Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(skills): add StopSkill functionality to abort in-flight installs
wizardchen12c3465b9596
diff --git a/client/README.md b/client/README.mdindex c8b3446f5..02f49830f 100644--- a/client/README.md+++ b/client/README.md@@ -402,6 +402,18 @@ if err != nil {_ = skillID // 用 skillID 订阅 /sandbox-configs/{id}/skills/{skillID}/install-events```+### 示例:停止卡住的安装++服务重启后安装行可能一直停在 `installing`,界面无法重试或卸载。停止会立刻改写该行(进程内若还有 goroutine 也会取消),之后可以再调重试或卸载。++```go+skill, err := apiClient.StopSandboxSkill(context.Background(), sandboxConfigID, skillID)+if err != nil {+ // 处理错误+}+_ = skill+```+### 示例:重试失败的安装安装失败的原因常与安装包无关(沙箱不可达、依赖源超时)。服务端保留着原始安装包,重试无需再传一次。diff --git a/client/README_EN.md b/client/README_EN.mdindex 11456a189..ff714f404 100644--- a/client/README_EN.md+++ b/client/README_EN.md@@ -214,6 +214,18 @@ if err != nil {_ = skillID // follow /sandbox-configs/{id}/skills/{skillID}/install-events```+### Example: Stop a stuck install++After a process restart the row may sit at `installing` with nothing running, which hides retry and uninstall. Stop rewrites the row immediately (and cancels the in-process goroutine if one is still alive). Then retry or uninstall as usual.++```go+skill, err := apiClient.StopSandboxSkill(context.Background(), sandboxConfigID, skillID)+if err != nil {+ // Handle error+}+_ = skill+```+### Example: Retry a failed installInstalls usually fail for reasons the bundle cannot fix — an unreachablediff --git a/client/skill.go b/client/skill.goindex 7555ac072..d0dc0119d 100644--- a/client/skill.go+++ b/client/skill.go@@ -146,6 +146,32 @@ func (c *Client) ReinstallSandboxSkill(return response.Data.SkillID, nil}+// StopSandboxSkill aborts an in-flight install so the operator can retry or+// uninstall. After a process restart the row may still say installing with no+// live process; this rewrites it immediately instead of waiting for the+// stuck-run reaper. Removal is not stopped.+func (c *Client) StopSandboxSkill(+ ctx context.Context, configID, skillID string,+) (*SandboxSkill, error) {+ if configID == "" {+ return nil, fmt.Errorf("sandbox config ID is required")+ }+ if skillID == "" {+ return nil, fmt.Errorf("skill ID is required")+ }+ path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) ++ "/skills/" + url.PathEscape(skillID) + "/stop"+ resp, err := c.doRequest(ctx, http.MethodPost, path, nil, nil)+ if err != nil {+ return nil, err+ }+ var response sandboxSkillResponse+ if err := parseResponse(resp, &response); err != nil {+ return nil, err+ }+ return &response.Data, nil+}+// SandboxSkillEnv is one environment variable an installed skill declared. It// reports whether a workspace-wide value exists and never what it is.type SandboxSkillEnv struct {diff --git a/docs/api/skill.md b/docs/api/skill.mdindex b02684535..61f119d83 100644--- a/docs/api/skill.md+++ b/docs/api/skill.md@@ -7,6 +7,7 @@| GET | `/skills` | 获取预装 Skills 列表 || POST | `/sandbox-configs/{id}/skills` | 安装技能(zip 上传或托管平台 source) || POST | `/sandbox-configs/{id}/skills/{skillId}/reinstall` | 用已保存的安装包重试安装 |+| POST | `/sandbox-configs/{id}/skills/{skillId}/stop` | 停止卡住的安装 || GET | `/sandbox-configs/{id}/skills/{skillId}/files` | 列出已安装技能的文件 || GET | `/sandbox-configs/{id}/skills/{skillId}/files/content` | 读取已安装技能中的单个文件 || PATCH | `/sandbox-configs/{id}/skills/{skillId}` | 启用/停用技能,或设置空间级环境变量 |@@ -136,6 +137,33 @@ curl --location --request POST \}```+## POST `/sandbox-configs/{id}/skills/{skillId}/stop` - 停止安装++中止进行中的安装,之后可以重试或卸载。服务重启后安装行可能一直停在 `installing` 且没有存活进程,本接口会立刻改写该行,不必等 stuck-run reaper。卸载不受影响。++状态变为 `failed`,错误为「安装已停止」。++```curl+curl --location --request POST \+'http://localhost:8080/api/v1/sandbox-configs/{id}/skills/{skillId}/stop' \+--header 'X-API-Key: sk-xxxxx'+```++**响应**(200):++```json+{+ "success": true,+ "data": {+ "id": "...",+ "status": "failed",+ "error": "安装已停止"+ }+}+```++若技能不是 `installing`(且不是已经 `failed`),返回 400。已经 `failed` 的停止是幂等成功。+## GET `/sandbox-configs/{id}/skills/{skillId}/files` - 列出技能文件返回该技能存档里的文件路径与大小。路径相对技能根目录(`SKILL.md` 所在目录),不启动沙箱。diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.tsindex 127881046..5b5e64344 100644--- a/frontend/src/api/system/index.ts+++ b/frontend/src/api/system/index.ts@@ -1084,6 +1084,18 @@ export function reinstallConfigSkill() as unknown as Promise<{ data: { skill_id: string } }>}+// Aborts an in-flight install so retry/uninstall become available.+// After a process restart the row may still say installing with nothing running.+export function stopConfigSkill(+ configId: string,+ skillId: string,+): Promise<{ data: ConfigSkill }> {+ return post(+ `/api/v1/sandbox-configs/${configId}/skills/${skillId}/stop`,+ {},+ ) as unknown as Promise<{ data: ConfigSkill }>+}+/*** Partial update: an absent field is left alone. `envs` names only the* variables to write — an entry with an empty string clears the stored valuediff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vueindex 4e0dd0f40..9a6527f09 100644--- a/frontend/src/components/SandboxSkillsPanel.vue+++ b/frontend/src/components/SandboxSkillsPanel.vue@@ -76,6 +76,19 @@</section><section v-if="mode === 'list' && focusSkillId" class="skill-manage">+ <Teleport v-if="headerActionsTarget && showHeaderStop" :to="headerActionsTarget" defer>+ <t-button+ class="skill-header-stop"+ theme="default"+ variant="outline"+ size="small"+ :disabled="!managedSkill"+ :loading="!!managedSkill && stoppingId === managedSkill.id"+ @click="managedSkill && stopSkill(managedSkill)"+ >+ {{ $t('settings.sandbox.skillStop') }}+ </t-button>+ </Teleport><Teleport v-if="headerActionsTarget && showHeaderUninstall" :to="headerActionsTarget" defer><t-popconfirmtheme="warning"@@ -501,6 +514,21 @@<t-icon name="chat-bubble-history" size="14px" /></button></t-tooltip>+ <t-tooltip+ v-if="skill.status === 'installing'"+ :content="$t('settings.sandbox.skillStopHint')"+ placement="top"+ >+ <button+ type="button"+ class="skill-card__icon-btn"+ :disabled="stoppingId === skill.id"+ :aria-label="$t('settings.sandbox.skillStop')"+ @click="stopSkill(skill)"+ >+ <t-icon name="stop-circle" size="14px" />+ </button>+ </t-tooltip><t-tooltipv-if="skill.status === 'failed'":content="$t('settings.sandbox.skillRetryHint')"@@ -592,6 +620,7 @@ import {listConfigSkills,patchConfigSkill,reinstallConfigSkill,+ stopConfigSkill,uploadConfigSkill,installConfigSkillFromSource,type ConfigSkill,@@ -649,6 +678,7 @@ const skills = ref<ConfigSkill[]>([])const togglingId = ref('')const deletingId = ref('')const retryingId = ref('')+const stoppingId = ref('')const uninstallingId = ref('')const uninstallingName = ref('')const uninstallDone = ref(false)@@ -765,6 +795,13 @@ const showHeaderUninstall = computed(() => {return !isRemoving(skill)})+const showHeaderStop = computed(() => {+ if (!props.focusSkillId || uninstallDone.value) return false+ const skill = managedSkill.value+ if (!skill) return false+ return skill.status === 'installing'+})+watch(managedSkill, (skill) => {if (skill && skillHasDeclaredEnvs(skill)) ensureEnvDrafts(skill.id)}, { immediate: true })@@ -1366,6 +1403,25 @@ async function retrySkill(skill: ConfigSkill) {}}+async function stopSkill(skill: ConfigSkill) {+ if (!props.record) return+ stoppingId.value = skill.id+ forgetProgress(skill.id)+ try {+ const res = await stopConfigSkill(props.record.id, skill.id)+ const updated = res?.data+ if (updated) {+ skills.value = skills.value.map((item) => (item.id === skill.id ? { ...item, ...updated } : item))+ }+ MessagePlugin.success(t('settings.sandbox.skillStopAccepted'))+ await loadSkills()+ } catch (e: any) {+ MessagePlugin.error(e?.message || t('settings.sandbox.skillStopFailed'))+ } finally {+ stoppingId.value = ''+ }+}+async function removeSkill(skill: ConfigSkill) {if (!props.record || isBusy(skill) || deletingId.value) returndeletingId.value = skill.iddiff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 583f8790c..c58c47502 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1388,6 +1388,10 @@ export default {skillRetryHint: 'Retry with the stored bundle; no re-upload needed',skillRetryAccepted: 'Reinstall started',skillRetryFailed: 'Failed to start the reinstall',+ skillStop: 'Stop install',+ skillStopHint: 'Abort this install, then retry or uninstall',+ skillStopAccepted: 'Stopped',+ skillStopFailed: 'Failed to stop',skillEmpty: 'No skills installed yet. Paste a registry URL, or upload a zip.',skillVersion: 'Version',skillVersionEmpty: 'Not specified',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 561a5af3e..65aa641aa 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -5308,6 +5308,10 @@ export default {skillRetryHint: '저장된 번들로 재시도합니다. 다시 업로드할 필요가 없습니다',skillRetryAccepted: '재설치를 시작했습니다',skillRetryFailed: '재설치를 시작하지 못했습니다',+ skillStop: '설치 중지',+ skillStopHint: '설치를 중단한 뒤 다시 설치하거나 제거할 수 있습니다',+ skillStopAccepted: '중지했습니다',+ skillStopFailed: '중지하지 못했습니다',skillEmpty: '아직 설치된 스킬이 없습니다. 레지스트리 URL을 붙여넣거나 zip을 업로드하세요.',skillVersion: 'Version',skillVersionEmpty: 'Not specified',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 51531238c..5382e9b40 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -5308,6 +5308,10 @@ export default {skillRetryHint: 'Повторить с сохранённым пакетом — загружать заново не нужно',skillRetryAccepted: 'Переустановка запущена',skillRetryFailed: 'Не удалось запустить переустановку',+ skillStop: 'Остановить установку',+ skillStopHint: 'Прервать установку, затем повторить или удалить',+ skillStopAccepted: 'Остановлено',+ skillStopFailed: 'Не удалось остановить',skillEmpty: 'Навыки ещё не установлены. Вставьте URL реестра или загрузите zip.',skillVersion: 'Version',skillVersionEmpty: 'Not specified',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 341685b00..b5142d82f 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -5310,6 +5310,10 @@ export default {skillRetryHint: '用已保存的安装包重试,无需重新上传',skillRetryAccepted: '已开始重新安装',skillRetryFailed: '重新安装失败',+ skillStop: '停止安装',+ skillStopHint: '中止当前安装,之后可以重试或卸载',+ skillStopAccepted: '已停止',+ skillStopFailed: '停止失败',skillEmpty: '尚未安装技能。粘贴托管平台链接,或上传 zip。',skillVersion: '版本',skillVersionEmpty: '未填写',diff --git a/internal/application/service/tenant_skill_install.go b/internal/application/service/tenant_skill_install.goindex e3b5970c2..513c12194 100644--- a/internal/application/service/tenant_skill_install.go+++ b/internal/application/service/tenant_skill_install.go@@ -169,11 +169,11 @@ func (s *TenantSkillService) installParsedSkill(})// The install outlives the HTTP request, so it must not inherit its- // cancellation. It is not durable across a restart either - the stuck-run- // reaper (Task 17) is what closes that gap.+ // cancellation. It is not durable across a restart either - StopSkill+ // rewrites the row, and the stuck-run reaper is the backup.go func() {bgCtx := context.WithoutCancel(ctx)- if err := s.withConfigLock(bgCtx, tenantID, configID, func(lockCtx context.Context) error {+ if err := s.withSkillRunLock(bgCtx, tenantID, configID, skillID, func(lockCtx context.Context) error {return s.runInstall(lockCtx, tenantID, configID, skillID, bundle)}); err != nil {logger.Errorf(bgCtx, "[skill] install %s failed: %v", skillID, err)@@ -258,6 +258,7 @@ func (s *TenantSkillService) runInstall(// compensating work begins. Each consumer calls cleanupContext to start its// own budget at the moment it needs one.cleanupBase := context.WithoutCancel(ctx)+ handle := s.lookupSkillRun(tenantID, configID, skillID)// pointerSwitched marks the point of no return. Past it the skill is// installed, snapshotted and serving every new session, so a later failure@@ -273,6 +274,11 @@ func (s *TenantSkillService) runInstall(skillID, err)return}+ // StopSkill (or a retry) may already own the row; stamping failed on+ // that owner would hide the run the operator just started.+ if !s.skillRunStillBound(tenantID, configID, skillID, handle) {+ return+ }// The image pointer is deliberately untouched on failure: the previous// snapshot keeps serving every session.failCtx, cancelFail := s.cleanupContext(cleanupBase)@@ -416,6 +422,9 @@ func (s *TenantSkillService) runInstall(// Re-check after the minutes-long agent run: InstallSkill writes the row// outside this lock, so a newer upload or a queued remove may already own// it. Snapshotting anyway would bake a tree the ledger no longer names.+ if !s.skillRunStillBound(tenantID, configID, skillID, handle) {+ return nil+ }owned, err = s.installStillOwnsTheRow(ctx, tenantID, configID, skillID, bundle)if err != nil {return err@@ -1278,12 +1287,12 @@ func (s *TenantSkillService) failSkill(}// installStillOwnsTheRow is the lock-side counterpart of InstallSkill's-// optimistic row write. A remove that ran first deleted the row; a newer-// upload of the same name replaced BundleSHA256; a queued remove flipped the-// status; a sibling retry of the same archive found the first run had already-// landed in the live image. Any of those means this run must not snapshot —-// failSkill would stamp the newer owner's row, and a snapshot with no matching-// row is an orphan the ledger cannot name.+// optimistic row write. A remove that ran first deleted the row; StopSkill+// flipped it to failed; a newer upload of the same name replaced BundleSHA256;+// a queued remove flipped the status; a sibling retry of the same archive+// found the first run had already landed in the live image. Any of those means+// this run must not snapshot — failSkill would stamp the newer owner's row,+// and a snapshot with no matching row is an orphan the ledger cannot name.func (s *TenantSkillService) installStillOwnsTheRow(ctx context.Context, tenantID uint64, configID, skillID string, bundle *SkillBundle,) (bool, error) {@@ -1294,7 +1303,7 @@ func (s *TenantSkillService) installStillOwnsTheRow(if current == nil {return false, nil}- if current.Status == types.SkillStatusRemoving {+ if current.Status == types.SkillStatusRemoving || current.Status == types.SkillStatusFailed {return false, nil}if bundle != nil && current.BundleSHA256 != "" && current.BundleSHA256 != bundle.SHA256 {diff --git a/internal/application/service/tenant_skill_remove.go b/internal/application/service/tenant_skill_remove.goindex b8aa83a95..787486988 100644--- a/internal/application/service/tenant_skill_remove.go+++ b/internal/application/service/tenant_skill_remove.go@@ -43,10 +43,10 @@ func (s *TenantSkillService) RemoveSkill(// Like the install, the removal outlives the HTTP request and must not// inherit its cancellation. It is not durable across a restart either;- // that is the stuck-run reaper's job (Task 17).+ // StopSkill rewrites the row, and the stuck-run reaper is the backup.go func() {bgCtx := context.WithoutCancel(ctx)- if err := s.withConfigLock(bgCtx, tenantID, configID, func(lockCtx context.Context) error {+ if err := s.withSkillRunLock(bgCtx, tenantID, configID, skillID, func(lockCtx context.Context) error {return s.runRemove(lockCtx, tenantID, configID, skillID)}); err != nil {logger.Errorf(bgCtx, "[skill] remove %s failed: %v", skillID, err)@@ -102,6 +102,7 @@ func (s *TenantSkillService) runRemove(// detached here — each consumer calls cleanupContext so its budget starts// when its work does, because a removal can run for minutes.cleanupBase := context.WithoutCancel(ctx)+ handle := s.lookupSkillRun(tenantID, configID, skillID)// imageChanged marks the point of no return. Past it the skill is gone// from the image every new session boots, so restoring the row to ready@@ -117,6 +118,9 @@ func (s *TenantSkillService) runRemove(skillID, err)return}+ if !s.skillRunStillBound(tenantID, configID, skillID, handle) {+ return+ }// A half-removed skill is worse than a kept one: the image still has// it, so put the row back the way the operator can retry from.restoreCtx, cancelRestore := s.cleanupContext(cleanupBase)diff --git a/internal/application/service/tenant_skill_service.go b/internal/application/service/tenant_skill_service.goindex 6dabe2e6c..f7fb34c55 100644--- a/internal/application/service/tenant_skill_service.go+++ b/internal/application/service/tenant_skill_service.go@@ -107,6 +107,12 @@ type TenantSkillService struct {cron *cron.CroncronMu sync.Mutexstarted bool++ // runCancels lets StopSkill abort the goroutine that holds this skill's+ // install. The map is per-process: a restart or another replica has+ // nothing to cancel, and StopSkill then only rewrites the stuck row.+ runCancelMu sync.Mutex+ runCancels map[string]*skillRunCancel}// NewTenantSkillService wires the repositories and runtimes the install and@@ -144,6 +150,7 @@ func NewTenantSkillService(snapshotRetention: skillSnapshotRetention,installHeartbeat: skillInstallHeartbeatInterval,localLocks: newKeyedMutex(),+ runCancels: map[string]*skillRunCancel{},bundleCache: newSkillBundleArchiveCache(),cron: cron.New(cron.WithSeconds(), cron.WithChain(cron.Recover(cron.DefaultLogger),@@ -157,6 +164,10 @@ func NewTenantSkillService(// run's changes, and the config holds exactly one pointer. Two concurrent// installs would each snapshot a base that lacks the other's work, and whoever// wrote the pointer last would silently discard the other install.+//+// With Redis this is a 30s renewable lease, so every replica of the same+// workspace contends on one key. Without Redis it is a process-local mutex+// and two replicas can write the pointer independently.func (s *TenantSkillService) withConfigLock(ctx context.Context, tenantID uint64, configID string, fn func(context.Context) error,) error {diff --git a/internal/application/service/tenant_skill_stop.go b/internal/application/service/tenant_skill_stop.gonew file mode 100644index 000000000..c602dee9b--- /dev/null+++ b/internal/application/service/tenant_skill_stop.go@@ -0,0 +1,134 @@+package service++import (+ "context"+ "errors"+ "fmt"++ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/types"+)++const skillInstallStoppedMessage = "安装已停止"++var errSkillInstallStopped = errors.New(skillInstallStoppedMessage)++// skillRunCancel is one in-process install or remove. Pointer identity is what+// lets a superseded run tell itself apart from the retry that replaced it.+type skillRunCancel struct {+ cancel context.CancelFunc+}++func skillRunKey(tenantID uint64, configID, skillID string) string {+ return fmt.Sprintf("%d:%s:%s", tenantID, configID, skillID)+}++// bindSkillRun ties ctx to StopSkill for this skill. The returned unbind must+// run when the goroutine exits, including after StopSkill has already cancelled.+func (s *TenantSkillService) bindSkillRun(+ ctx context.Context, tenantID uint64, configID, skillID string,+) (context.Context, func()) {+ if s == nil {+ return ctx, func() {}+ }+ runCtx, cancel := context.WithCancel(ctx)+ handle := &skillRunCancel{cancel: cancel}+ key := skillRunKey(tenantID, configID, skillID)+ s.runCancelMu.Lock()+ if s.runCancels == nil {+ s.runCancels = map[string]*skillRunCancel{}+ }+ if prev := s.runCancels[key]; prev != nil && prev.cancel != nil {+ prev.cancel()+ }+ s.runCancels[key] = handle+ s.runCancelMu.Unlock()+ return runCtx, func() {+ cancel()+ s.runCancelMu.Lock()+ if s.runCancels[key] == handle {+ delete(s.runCancels, key)+ }+ s.runCancelMu.Unlock()+ }+}++func (s *TenantSkillService) lookupSkillRun(+ tenantID uint64, configID, skillID string,+) *skillRunCancel {+ if s == nil {+ return nil+ }+ s.runCancelMu.Lock()+ defer s.runCancelMu.Unlock()+ if s.runCancels == nil {+ return nil+ }+ return s.runCancels[skillRunKey(tenantID, configID, skillID)]+}++func (s *TenantSkillService) cancelSkillRun(tenantID uint64, configID, skillID string) {+ handle := s.lookupSkillRun(tenantID, configID, skillID)+ if handle != nil && handle.cancel != nil {+ handle.cancel()+ }+}++// skillRunStillBound reports whether handle is still the run registered for+// this skill. A nil handle means the caller never bound one (direct runInstall+// in tests) and is treated as still bound so those paths keep failing the row.+func (s *TenantSkillService) skillRunStillBound(+ tenantID uint64, configID, skillID string, handle *skillRunCancel,+) bool {+ if handle == nil {+ return true+ }+ return s.lookupSkillRun(tenantID, configID, skillID) == handle+}++// withSkillRunLock is withConfigLock plus a StopSkill-cancellable context.+func (s *TenantSkillService) withSkillRunLock(+ ctx context.Context, tenantID uint64, configID, skillID string,+ fn func(context.Context) error,+) error {+ runCtx, unbind := s.bindSkillRun(ctx, tenantID, configID, skillID)+ defer unbind()+ return s.withConfigLock(runCtx, tenantID, configID, fn)+}++// StopSkill aborts an in-flight install so the operator can retry or uninstall.+// After a process restart there is no goroutine to cancel; the row is still+// rewritten, which is what unblocks the UI. Removal is left alone.+func (s *TenantSkillService) StopSkill(+ ctx context.Context, tenantID uint64, configID, skillID string,+) (*types.TenantSkillEntity, error) {+ if s == nil || s.skills == nil {+ return nil, errors.New("skill service is not configured")+ }+ skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)+ if err != nil {+ return nil, err+ }+ if skill == nil {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ switch skill.Status {+ case types.SkillStatusFailed:+ return skill, nil+ case types.SkillStatusInstalling:+ default:+ return nil, apperrors.NewBadRequestError("skill is not installing")+ }++ s.cancelSkillRun(tenantID, configID, skillID)+ s.failSkill(ctx, tenantID, configID, skillID, nil, errSkillInstallStopped)++ updated, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)+ if err != nil {+ return nil, err+ }+ if updated == nil {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ return updated, nil+}diff --git a/internal/application/service/tenant_skill_stop_test.go b/internal/application/service/tenant_skill_stop_test.gonew file mode 100644index 000000000..e001c329f--- /dev/null+++ b/internal/application/service/tenant_skill_stop_test.go@@ -0,0 +1,103 @@+package service++import (+ "context"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++func TestStopSkillFailsAnAbandonedInstall(t *testing.T) {+ fx := newInstallFixture(t)++ got, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "sk-1")++ require.NoError(t, err)+ require.Equal(t, types.SkillStatusFailed, got.Status)+ require.Equal(t, skillInstallStoppedMessage, got.Error)+ require.Nil(t, got.InstallingSince)+}++func TestStopSkillIsIdempotentWhenAlreadyFailed(t *testing.T) {+ fx := newInstallFixture(t)+ require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",+ func(e *types.TenantSkillEntity) {+ e.Status = types.SkillStatusFailed+ e.Error = "python verification failed"+ e.InstallingSince = nil+ }))++ got, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "sk-1")++ require.NoError(t, err)+ require.Equal(t, types.SkillStatusFailed, got.Status)+ require.Equal(t, "python verification failed", got.Error,+ "a second stop must not overwrite the failure that already unblocked the UI")+}++func TestStopSkillRejectsAReadySkill(t *testing.T) {+ fx := newInstallFixture(t)+ require.NoError(t, fx.svc.updateSkillFields(context.Background(), 7, "cfg-1", "sk-1",+ func(e *types.TenantSkillEntity) {+ e.Status = types.SkillStatusReady+ e.InstallingSince = nil+ }))++ _, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "sk-1")++ require.ErrorContains(t, err, "not installing")+}++func TestStopSkillRejectsAnUnknownSkill(t *testing.T) {+ fx := newInstallFixture(t)++ _, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "nope")++ require.ErrorContains(t, err, "not found")+}++func TestStopSkillCancelsALiveInstall(t *testing.T) {+ fx := newInstallFixture(t)+ started := make(chan struct{})+ released := make(chan struct{})+ go func() {+ _ = fx.svc.withSkillRunLock(context.Background(), 7, "cfg-1", "sk-1",+ func(ctx context.Context) error {+ close(started)+ <-ctx.Done()+ close(released)+ return ctx.Err()+ })+ }()+ select {+ case <-started:+ case <-time.After(2 * time.Second):+ t.Fatal("live install never entered the lock")+ }++ got, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "sk-1")++ require.NoError(t, err)+ require.Equal(t, types.SkillStatusFailed, got.Status)+ require.Equal(t, skillInstallStoppedMessage, got.Error)+ select {+ case <-released:+ case <-time.After(2 * time.Second):+ t.Fatal("StopSkill did not cancel the live install")+ }+}++func TestStopSkillLeavesARemovingSkillAlone(t *testing.T) {+ fx := newInstallFixture(t)+ fx.seedInstalledSkill("sk-1", "snap-old", 3)++ _, err := fx.svc.StopSkill(context.Background(), 7, "cfg-1", "sk-1")++ require.ErrorContains(t, err, "not installing")+ skill, getErr := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")+ require.NoError(t, getErr)+ require.Equal(t, types.SkillStatusRemoving, skill.Status,+ "stop is install-only; a removal in flight must keep running")+}diff --git a/internal/handler/sandbox_skill.go b/internal/handler/sandbox_skill.goindex fbc223fb3..c382bb42b 100644--- a/internal/handler/sandbox_skill.go+++ b/internal/handler/sandbox_skill.go@@ -54,6 +54,7 @@ type sandboxSkillService interface {ctx context.Context, tenantID uint64, configID, source string,) (string, error)ReinstallSkill(ctx context.Context, tenantID uint64, configID, skillID string) (string, error)+ StopSkill(ctx context.Context, tenantID uint64, configID, skillID string) (*types.TenantSkillEntity, error)RemoveSkill(ctx context.Context, tenantID uint64, configID, skillID string) errorLastProgress(ctx context.Context, tenantID uint64, configID, skillID string,@@ -398,6 +399,35 @@ func (h *SandboxSkillHandler) Reinstall(c *gin.Context) {c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})}+// Stop godoc+// @Summary Stop a skill install+// @Description Abort an in-flight install so the operator can retry or uninstall. After a process restart the row may still say installing with no live process; this rewrites it immediately instead of waiting for the stuck-run reaper. Removal is not stopped.+// @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{} "Stopped skill"+// @Failure 400 {object} apperrors.AppError "Skill is not installing"+// @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}/stop [post]+func (h *SandboxSkillHandler) Stop(c *gin.Context) {+ skill, err := h.service.StopSkill(+ c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), c.Param("skillId"),+ )+ if err != nil {+ respondSkillServiceError(c, err)+ return+ }+ if skill == nil {+ _ = c.Error(apperrors.NewNotFoundError("skill not found"))+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": toSkillResponse(skill)})+}+func skillTooLargeError() error {return apperrors.NewBadRequestError(fmt.Sprintf("skill bundle cannot exceed %d MB", secutils.GetMaxSkillBundleSizeMB()))diff --git a/internal/handler/sandbox_skill_test.go b/internal/handler/sandbox_skill_test.goindex 19066d4f7..d73c3d397 100644--- a/internal/handler/sandbox_skill_test.go+++ b/internal/handler/sandbox_skill_test.go@@ -41,6 +41,7 @@ type fakeSandboxSkillService struct {installSource stringsourceErr errorreinstallErr error+ stopErr errorremoveErr errorfiles []service.SkillFileEntry@@ -67,6 +68,10 @@ type fakeSandboxSkillService struct {reinstallConfig stringreinstallSkill string+ stopTenant uint64+ stopConfig string+ stopSkill string+removeTenant uint64removeConfig stringremoveSkill string@@ -207,6 +212,23 @@ func (f *fakeSandboxSkillService) ReinstallSkill(return f.installID, f.reinstallErr}+func (f *fakeSandboxSkillService) StopSkill(+ _ context.Context, tenantID uint64, configID, skillID string,+) (*types.TenantSkillEntity, error) {+ f.stopTenant, f.stopConfig, f.stopSkill = tenantID, configID, skillID+ if f.stopErr != nil {+ return nil, f.stopErr+ }+ skill := f.skills[skillID]+ if skill == nil {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ if tenantID != testSkillTenantID || skill.SandboxConfigID != configID {+ return nil, apperrors.NewNotFoundError("skill not found")+ }+ return skill, nil+}+func (f *fakeSandboxSkillService) RemoveSkill(_ context.Context, tenantID uint64, configID, skillID string,) error {@@ -278,6 +300,7 @@ func newSkillTestRouter(h *SandboxSkillHandler) *gin.Engine {r.GET("/sandbox-configs/:id/skills/:skillId/files", h.ListFiles)r.GET("/sandbox-configs/:id/skills/:skillId/files/content", h.GetFile)r.POST("/sandbox-configs/:id/skills/:skillId/reinstall", h.Reinstall)+ r.POST("/sandbox-configs/:id/skills/:skillId/stop", h.Stop)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)@@ -630,6 +653,42 @@ func TestSandboxSkillReinstallIsAccepted(t *testing.T) {require.Contains(t, w.Body.String(), `"skill_id":"skill-1"`)}+func TestSandboxSkillStopReturnsTheSkill(t *testing.T) {+ svc := &fakeSandboxSkillService{+ skills: map[string]*types.TenantSkillEntity{+ "skill-1": {+ ID: "skill-1", SandboxConfigID: "cfg-a",+ Status: types.SkillStatusFailed, Enabled: true,+ },+ },+ }+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))++ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodPost,+ "/sandbox-configs/cfg-a/skills/skill-1/stop", nil))++ require.Equal(t, http.StatusOK, w.Code)+ require.Equal(t, testSkillTenantID, svc.stopTenant,+ "a stop must be scoped to the caller's workspace")+ require.Equal(t, "cfg-a", svc.stopConfig)+ require.Equal(t, "skill-1", svc.stopSkill)+ require.Contains(t, w.Body.String(), `"id":"skill-1"`)+}++func TestSandboxSkillStopReportsAMissingSkill(t *testing.T) {+ svc := &fakeSandboxSkillService{+ stopErr: apperrors.NewNotFoundError("skill not found"),+ }+ router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))++ w := httptest.NewRecorder()+ router.ServeHTTP(w, httptest.NewRequest(http.MethodPost,+ "/sandbox-configs/cfg-a/skills/nope/stop", nil))++ require.Equal(t, http.StatusNotFound, w.Code)+}+func TestSandboxSkillReinstallReportsAMissingSkill(t *testing.T) {svc := &fakeSandboxSkillService{reinstallErr: apperrors.NewNotFoundError("skill not found"),diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.goindex c9b9c421d..2289264cb 100644--- a/internal/router/router_api_key_capabilities_test.go+++ b/internal/router/router_api_key_capabilities_test.go@@ -408,6 +408,8 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) {{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId"},{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/files"},{http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/files/content"},+ {http.MethodPost, "/api/v1/sandbox-configs/:id/skills/:skillId/reinstall"},+ {http.MethodPost, "/api/v1/sandbox-configs/:id/skills/:skillId/stop"},{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"},diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.goindex 065d7346f..039018da4 100644--- a/internal/router/routes_infra.go+++ b/internal/router/routes_infra.go@@ -68,6 +68,7 @@ func RegisterSandboxConfigRoutes(configs.GET("/:id/skills/:skillId/files", g.Admin(), skills.ListFiles)configs.GET("/:id/skills/:skillId/files/content", g.Admin(), skills.GetFile)configs.POST("/:id/skills/:skillId/reinstall", g.Admin(), skills.Reinstall)+ configs.POST("/:id/skills/:skillId/stop", g.Admin(), skills.Stop)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)