From ebfd5ef0fba44b5ed13b4e5ef71b2fa255fd3b30 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 25 Aug 2026 19:56:12 +0800 Subject: [PATCH] feat(sandbox): browse installed skill files from settings Read the stored skill bundle without booting a sandbox, and open a resizable secondary drawer with a file tree and markdown preview. --- client/README.md | 15 + client/README_EN.md | 15 + client/skill.go | 78 ++ docs/api/skill.md | 47 + docs/docs.go | 135 +++ docs/swagger.json | 135 +++ docs/swagger.yaml | 87 ++ frontend/src/api/system/index.ts | 34 + .../src/components/SandboxSkillsPanel.vue | 167 +++- frontend/src/components/SkillFilesDrawer.vue | 306 +++++++ frontend/src/components/SkillFilesPanel.vue | 833 ++++++++++++++++++ frontend/src/i18n/locales/en-US.ts | 10 + frontend/src/i18n/locales/ko-KR.ts | 10 + frontend/src/i18n/locales/ru-RU.ts | 10 + frontend/src/i18n/locales/zh-CN.ts | 10 + .../application/service/tenant_skill_files.go | 216 +++++ .../service/tenant_skill_files_test.go | 133 +++ .../service/tenant_skill_install_test.go | 22 +- internal/handler/sandbox_skill.go | 57 ++ internal/handler/sandbox_skill_test.go | 127 +++ .../router_api_key_capabilities_test.go | 2 + internal/router/routes_infra.go | 2 + 22 files changed, 2402 insertions(+), 49 deletions(-) create mode 100644 frontend/src/components/SkillFilesDrawer.vue create mode 100644 frontend/src/components/SkillFilesPanel.vue create mode 100644 internal/application/service/tenant_skill_files.go create mode 100644 internal/application/service/tenant_skill_files_test.go diff --git a/client/README.md b/client/README.md index dfc03710..de2a2bc6 100644 --- a/client/README.md +++ b/client/README.md @@ -400,6 +400,21 @@ if err != nil { _ = skillID // 用 skillID 订阅 /sandbox-configs/{id}/skills/{skillID}/install-events ``` +### 示例:查看已安装技能的文件 + +```go +files, err := apiClient.ListSandboxSkillFiles(context.Background(), sandboxConfigID, skillID) +if err != nil { + // 处理错误 +} +content, err := apiClient.GetSandboxSkillFile(context.Background(), sandboxConfigID, skillID, "SKILL.md") +if err != nil { + // 处理错误 +} +_ = files +_ = content +``` + ## 完整示例 请参考 `example.go` 文件中的 `ExampleUsage` 函数,其中展示了客户端的完整使用流程。 \ No newline at end of file diff --git a/client/README_EN.md b/client/README_EN.md index 7ee448f1..0f454993 100644 --- a/client/README_EN.md +++ b/client/README_EN.md @@ -213,6 +213,21 @@ if err != nil { _ = skillID // follow /sandbox-configs/{id}/skills/{skillID}/install-events ``` +### Example: Browse files of an installed skill + +```go +files, err := apiClient.ListSandboxSkillFiles(context.Background(), sandboxConfigID, skillID) +if err != nil { + // Handle error +} +content, err := apiClient.GetSandboxSkillFile(context.Background(), sandboxConfigID, skillID, "SKILL.md") +if err != nil { + // Handle error +} +_ = files +_ = content +``` + ## Complete Example Please refer to the `ExampleUsage` function in the `example.go` file, which demonstrates the complete usage flow of the client. diff --git a/client/skill.go b/client/skill.go index b8f7b9cc..ce15f472 100644 --- a/client/skill.go +++ b/client/skill.go @@ -118,3 +118,81 @@ func (c *Client) UploadSandboxSkill( } return response.Data.SkillID, nil } + +// SandboxSkillFile is one path in an installed skill's stored archive. +type SandboxSkillFile struct { + Path string `json:"path"` + Size int64 `json:"size"` +} + +// SandboxSkillFileContent is one file opened from an installed skill. +type SandboxSkillFileContent struct { + Path string `json:"path"` + Size int64 `json:"size"` + Encoding string `json:"encoding"` + Content string `json:"content,omitempty"` + MediaType string `json:"media_type,omitempty"` + Truncated bool `json:"truncated,omitempty"` + Binary bool `json:"binary,omitempty"` +} + +type sandboxSkillFilesResponse struct { + Success bool `json:"success"` + Data []SandboxSkillFile `json:"data"` +} + +type sandboxSkillFileContentResponse struct { + Success bool `json:"success"` + Data SandboxSkillFileContent `json:"data"` +} + +// ListSandboxSkillFiles lists the stored archive of one installed skill. +func (c *Client) ListSandboxSkillFiles( + ctx context.Context, configID, skillID string, +) ([]SandboxSkillFile, 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) + "/files" + resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) + if err != nil { + return nil, err + } + var response sandboxSkillFilesResponse + if err := parseResponse(resp, &response); err != nil { + return nil, err + } + return response.Data, nil +} + +// GetSandboxSkillFile reads one skill-root-relative file from an installed skill. +func (c *Client) GetSandboxSkillFile( + ctx context.Context, configID, skillID, filePath string, +) (*SandboxSkillFileContent, error) { + if configID == "" { + return nil, fmt.Errorf("sandbox config ID is required") + } + if skillID == "" { + return nil, fmt.Errorf("skill ID is required") + } + if filePath == "" { + return nil, fmt.Errorf("skill file path is required") + } + path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) + + "/skills/" + url.PathEscape(skillID) + "/files/content" + query := url.Values{} + query.Set("path", filePath) + resp, err := c.doRequest(ctx, http.MethodGet, path, nil, query) + if err != nil { + return nil, err + } + var response sandboxSkillFileContentResponse + if err := parseResponse(resp, &response); err != nil { + return nil, err + } + return &response.Data, nil +} diff --git a/docs/api/skill.md b/docs/api/skill.md index fa2b2042..a835ad24 100644 --- a/docs/api/skill.md +++ b/docs/api/skill.md @@ -6,6 +6,8 @@ | ---- | --------- | ------------------ | | GET | `/skills` | 获取预装 Skills 列表 | | POST | `/sandbox-configs/{id}/skills` | 安装技能(zip 上传或托管平台 source) | +| GET | `/sandbox-configs/{id}/skills/{skillId}/files` | 列出已安装技能的文件 | +| GET | `/sandbox-configs/{id}/skills/{skillId}/files/content` | 读取已安装技能中的单个文件 | ## GET `/skills` - 获取预装 Skills 列表 @@ -100,3 +102,48 @@ curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \ } } ``` + +## GET `/sandbox-configs/{id}/skills/{skillId}/files` - 列出技能文件 + +返回该技能存档里的文件路径与大小。路径相对技能根目录(`SKILL.md` 所在目录),不启动沙箱。 + +```curl +curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills/{skillId}/files' \ +--header 'X-API-Key: sk-xxxxx' +``` + +**响应**: + +```json +{ + "success": true, + "data": [ + { "path": "SKILL.md", "size": 412 }, + { "path": "scripts/extract.py", "size": 1280 } + ] +} +``` + +## GET `/sandbox-configs/{id}/skills/{skillId}/files/content` - 读取技能文件 + +`path` 为技能根目录相对路径。文本以 UTF-8 返回;较小的图片为 base64;其它二进制文件不返回正文,并设置 `binary: true`。 + +```curl +curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills/{skillId}/files/content?path=SKILL.md' \ +--header 'X-API-Key: sk-xxxxx' +``` + +**响应**: + +```json +{ + "success": true, + "data": { + "path": "SKILL.md", + "size": 412, + "encoding": "utf-8", + "media_type": "text/markdown", + "content": "---\nname: pdf-tools\n..." + } +} +``` diff --git a/docs/docs.go b/docs/docs.go index cfab866f..aeeeafc0 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -11885,6 +11885,135 @@ const docTemplate = `{ } } }, + "/sandbox-configs/{id}/skills/{skillId}/files": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "List files in the stored skill bundle without starting a sandbox.", + "produces": [ + "application/json" + ], + "tags": [ + "SandboxConfig" + ], + "summary": "List files of an installed skill", + "parameters": [ + { + "type": "string", + "description": "Sandbox config ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill ID", + "name": "skillId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Skill files", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Skill or files not found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, + "/sandbox-configs/{id}/skills/{skillId}/files/content": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Read one skill file as UTF-8, a small base64 image, or binary.", + "produces": [ + "application/json" + ], + "tags": [ + "SandboxConfig" + ], + "summary": "Read one file of an installed skill", + "parameters": [ + { + "type": "string", + "description": "Sandbox config ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill ID", + "name": "skillId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill-root-relative file path", + "name": "path", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Skill file", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid path", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Skill or file not found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/sandbox-configs/{id}/skills/{skillId}/install-events": { "get": { "security": [ @@ -11983,6 +12112,12 @@ const docTemplate = `{ "type": "string" } }, + "204": { + "description": "Install is still preparing; retry once locators exist", + "schema": { + "type": "string" + } + }, "401": { "description": "Unauthorized", "schema": { diff --git a/docs/swagger.json b/docs/swagger.json index 14e2fc59..36f5256a 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -11878,6 +11878,135 @@ } } }, + "/sandbox-configs/{id}/skills/{skillId}/files": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "List files in the stored skill bundle without starting a sandbox.", + "produces": [ + "application/json" + ], + "tags": [ + "SandboxConfig" + ], + "summary": "List files of an installed skill", + "parameters": [ + { + "type": "string", + "description": "Sandbox config ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill ID", + "name": "skillId", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Skill files", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Skill or files not found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, + "/sandbox-configs/{id}/skills/{skillId}/files/content": { + "get": { + "security": [ + { + "Bearer": [] + }, + { + "ApiKeyAuth": [] + } + ], + "description": "Read one skill file as UTF-8, a small base64 image, or binary.", + "produces": [ + "application/json" + ], + "tags": [ + "SandboxConfig" + ], + "summary": "Read one file of an installed skill", + "parameters": [ + { + "type": "string", + "description": "Sandbox config ID", + "name": "id", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill ID", + "name": "skillId", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Skill-root-relative file path", + "name": "path", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "Skill file", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "Invalid path", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "401": { + "description": "Unauthorized", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "404": { + "description": "Skill or file not found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/sandbox-configs/{id}/skills/{skillId}/install-events": { "get": { "security": [ @@ -11976,6 +12105,12 @@ "type": "string" } }, + "204": { + "description": "Install is still preparing; retry once locators exist", + "schema": { + "type": "string" + } + }, "401": { "description": "Unauthorized", "schema": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 29ff4cbe..1847eaa7 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -13856,6 +13856,89 @@ paths: summary: Update an installed skill tags: - SandboxConfig + /sandbox-configs/{id}/skills/{skillId}/files: + get: + description: List files in the stored skill bundle without starting a sandbox. + parameters: + - description: Sandbox config ID + in: path + name: id + required: true + type: string + - description: Skill ID + in: path + name: skillId + required: true + type: string + produces: + - application/json + responses: + "200": + description: Skill files + schema: + additionalProperties: true + type: object + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Skill or files not found + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: List files of an installed skill + tags: + - SandboxConfig + /sandbox-configs/{id}/skills/{skillId}/files/content: + get: + description: Read one skill file as UTF-8, a small base64 image, or binary. + parameters: + - description: Sandbox config ID + in: path + name: id + required: true + type: string + - description: Skill ID + in: path + name: skillId + required: true + type: string + - description: Skill-root-relative file path + in: query + name: path + required: true + type: string + produces: + - application/json + responses: + "200": + description: Skill file + schema: + additionalProperties: true + type: object + "400": + description: Invalid path + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + "401": + description: Unauthorized + schema: + additionalProperties: true + type: object + "404": + description: Skill or file not found + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + security: + - Bearer: [] + - ApiKeyAuth: [] + summary: Read one file of an installed skill + tags: + - SandboxConfig /sandbox-configs/{id}/skills/{skillId}/install-events: get: description: |- @@ -13924,6 +14007,10 @@ paths: description: SSE stream of transcript events schema: type: string + "204": + description: Install is still preparing; retry once locators exist + schema: + type: string "401": description: Unauthorized schema: diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 0a7d541e..92fb5a41 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -1084,3 +1084,37 @@ export function configSkillInstallEventsUrl(configId: string, skillId: string): export function configSkillTranscriptUrl(configId: string, skillId: string): string { return `/api/v1/sandbox-configs/${configId}/skills/${skillId}/transcript` } + +export interface ConfigSkillFileEntry { + path: string + size: number +} + +export interface ConfigSkillFileContent { + path: string + size: number + encoding: 'utf-8' | 'base64' | 'binary' | string + content?: string + media_type?: string + truncated?: boolean + binary?: boolean +} + +export function listConfigSkillFiles( + configId: string, + skillId: string, +): Promise<{ data: ConfigSkillFileEntry[] }> { + return get(`/api/v1/sandbox-configs/${configId}/skills/${skillId}/files`) as unknown as Promise<{ + data: ConfigSkillFileEntry[] + }> +} + +export function getConfigSkillFile( + configId: string, + skillId: string, + path: string, +): Promise<{ data: ConfigSkillFileContent }> { + return get(`/api/v1/sandbox-configs/${configId}/skills/${skillId}/files/content`, { + params: { path }, + }) as unknown as Promise<{ data: ConfigSkillFileContent }> +} diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue index 101c88ed..c94de6e3 100644 --- a/frontend/src/components/SandboxSkillsPanel.vue +++ b/frontend/src/components/SandboxSkillsPanel.vue @@ -173,6 +173,18 @@ @change="(v: any) => toggleEnabled(skill, Boolean(v))" /> + + + + - - - + + @@ -288,6 +303,7 @@ import { useI18n } from 'vue-i18n' import { fetchEventSource } from '@microsoft/fetch-event-source' import ModelSelector from '@/components/ModelSelector.vue' import SkillInstallTimeline from '@/components/SkillInstallTimeline.vue' +import SkillFilesDrawer from '@/components/SkillFilesDrawer.vue' import { getAgentById, updateAgent, @@ -335,6 +351,9 @@ const deletingId = ref('') // Only one install timeline is open at a time: each one holds an SSE // connection, and two runs' worth of agent steps in a drawer is unreadable. const expandedSkillId = ref('') +const filesSkillId = ref('') +const filesSkillName = ref('') +const filesDrawerVisible = ref(false) const expandedCopyIds = ref>(new Set()) const transcriptEpoch = ref(0) const focusedSkillId = ref('') @@ -440,6 +459,7 @@ function revealSkill(skillId: string) { function onTranscriptVisible(skill: ConfigSkill, visible: boolean) { if (visible) { + filesDrawerVisible.value = false if (expandedSkillId.value !== skill.id) { expandedSkillId.value = skill.id // A run that finished while the popup was closed was tailed from the @@ -453,6 +473,17 @@ function onTranscriptVisible(skill: ConfigSkill, visible: boolean) { } } +function openSkillFiles(skill: ConfigSkill) { + expandedSkillId.value = '' + if (filesDrawerVisible.value && filesSkillId.value === skill.id) { + filesDrawerVisible.value = false + return + } + filesSkillId.value = skill.id + filesSkillName.value = skill.name || skill.id + filesDrawerVisible.value = true +} + function progressOf(skill: ConfigSkill): number { const percent = progressById.value[skill.id]?.percent if (typeof percent === 'number' && Number.isFinite(percent)) { @@ -1021,10 +1052,6 @@ onUnmounted(() => { box-shadow: 0 0 0 2px var(--td-brand-color-focus, rgba(0, 168, 112, 0.18)); } -.skill-transcript-toggle--on { - color: var(--td-brand-color); -} - .skill-status-ring { width: 16px; height: 16px; @@ -1084,13 +1111,22 @@ onUnmounted(() => { .skill-item__desc, .skill-item__error { - margin: 6px 0 0; + margin: 0; font-size: 12px; line-height: 1.5; word-break: break-word; } +.skill-item__copy { + display: flex; + align-items: flex-end; + gap: 8px; + margin-top: 6px; +} + .skill-item__desc { + min-width: 0; + flex: 1; color: var(--td-text-color-secondary); } @@ -1103,33 +1139,72 @@ onUnmounted(() => { } .skill-item__error { + margin-top: 6px; color: var(--td-error-color); } .skill-item__toggle { - margin-top: 4px; + flex-shrink: 0; + margin: 0; padding: 0; border: 0; background: none; font-size: 12px; line-height: 1.5; - color: var(--td-brand-color); + color: var(--td-text-color-placeholder); cursor: pointer; + + &:hover { + color: var(--td-brand-color); + } } .skill-item__actions { display: flex; align-items: center; - gap: 4px; + gap: 2px; flex-shrink: 0; } -.skill-item__icon-btn { - width: 24px; - height: 24px; +.skill-item__actions-divider { + width: 1px; + height: 12px; + margin: 0 4px; + background: var(--td-component-stroke); +} - :deep(.t-button__icon) { - margin: 0; +.skill-item__icon-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--td-text-color-placeholder); + cursor: pointer; + transition: background 0.15s ease, color 0.15s ease; + + &:hover:not(:disabled) { + background: var(--td-bg-color-secondarycontainer); + color: var(--td-text-color-primary); + } + + &:disabled { + cursor: not-allowed; + opacity: 0.4; + } + + &.is-on { + background: var(--td-bg-color-secondarycontainer); + color: var(--td-brand-color); + } + + &--danger:hover:not(:disabled) { + background: var(--td-error-color-1, var(--td-bg-color-secondarycontainer)); + color: var(--td-error-color); } } diff --git a/frontend/src/components/SkillFilesDrawer.vue b/frontend/src/components/SkillFilesDrawer.vue new file mode 100644 index 00000000..999f4a17 --- /dev/null +++ b/frontend/src/components/SkillFilesDrawer.vue @@ -0,0 +1,306 @@ + + + + + + + diff --git a/frontend/src/components/SkillFilesPanel.vue b/frontend/src/components/SkillFilesPanel.vue new file mode 100644 index 00000000..b7ce66ad --- /dev/null +++ b/frontend/src/components/SkillFilesPanel.vue @@ -0,0 +1,833 @@ + + + + + + + diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 9a28be51..bfb97f01 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -1310,6 +1310,16 @@ export default { skillTranscriptHide: 'Hide install run', skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + skillFiles: 'View files', + skillFilesTitle: 'Files', + skillFilesEmpty: 'This skill has no files to browse yet.', + skillFilesLoadFailed: 'Failed to load skill files', + skillFilesFileLoadFailed: 'Could not read this file', + skillFilesBinary: 'This file is binary and cannot be previewed.', + skillFilesTruncated: 'The file is large; only the beginning is shown.', + skillFilesSelectHint: 'Select a file on the left to view it', + skillFilesPreview: 'Preview', + skillFilesSource: 'Source', skillLoadFailed: 'Failed to load skills', skillToggleFailed: 'Failed to update the skill', skillDeleteAccepted: 'Skill removal started', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 94ba10d0..3b6f58ab 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -5161,6 +5161,16 @@ export default { skillTranscriptHide: 'Hide install run', skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + skillFiles: '파일 보기', + skillFilesTitle: '파일', + skillFilesEmpty: '이 스킬에서 볼 수 있는 파일이 아직 없습니다.', + skillFilesLoadFailed: '스킬 파일을 불러오지 못했습니다', + skillFilesFileLoadFailed: '이 파일을 읽을 수 없습니다', + skillFilesBinary: '이 파일은 바이너리라 미리볼 수 없습니다.', + skillFilesTruncated: '파일이 커서 앞부분만 표시합니다.', + skillFilesSelectHint: '왼쪽에서 파일을 선택하면 내용을 볼 수 있습니다', + skillFilesPreview: '미리보기', + skillFilesSource: '원본', skillLoadFailed: 'Failed to load skills', skillToggleFailed: 'Failed to update the skill', skillDeleteAccepted: 'Skill removal started', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 39709d8f..c889b3f9 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -5161,6 +5161,16 @@ export default { skillTranscriptHide: 'Hide install run', skillTranscriptEmpty: 'This install left no transcript.', skillTranscriptWaiting: 'Install has started. Waiting for the process log…', + skillFiles: 'Просмотреть файлы', + skillFilesTitle: 'Файлы', + skillFilesEmpty: 'У этого навыка пока нет файлов для просмотра.', + skillFilesLoadFailed: 'Не удалось загрузить файлы навыка', + skillFilesFileLoadFailed: 'Не удалось прочитать этот файл', + skillFilesBinary: 'Это двоичный файл, его нельзя просмотреть.', + skillFilesTruncated: 'Файл слишком большой, показана только начальная часть.', + skillFilesSelectHint: 'Выберите файл слева, чтобы просмотреть содержимое', + skillFilesPreview: 'Просмотр', + skillFilesSource: 'Исходник', skillLoadFailed: 'Failed to load skills', skillToggleFailed: 'Failed to update the skill', skillDeleteAccepted: 'Skill removal started', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 59fc7fb0..f69c09cd 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -5163,6 +5163,16 @@ export default { skillTranscriptHide: '收起安装过程', skillTranscriptEmpty: '这次安装没有留下记录。', skillTranscriptWaiting: '安装已开始,正在等待过程记录…', + skillFiles: '查看文件', + skillFilesTitle: '文件', + skillFilesEmpty: '该技能还没有可查看的文件。', + skillFilesLoadFailed: '加载技能文件失败', + skillFilesFileLoadFailed: '无法读取该文件', + skillFilesBinary: '该文件是二进制内容,无法在线预览。', + skillFilesTruncated: '文件较大,仅显示前一部分。', + skillFilesSelectHint: '选择左侧文件以查看内容', + skillFilesPreview: '预览', + skillFilesSource: '源码', skillLoadFailed: '加载技能列表失败', skillToggleFailed: '更新技能状态失败', skillDeleteAccepted: '已开始删除技能', diff --git a/internal/application/service/tenant_skill_files.go b/internal/application/service/tenant_skill_files.go new file mode 100644 index 00000000..3341a791 --- /dev/null +++ b/internal/application/service/tenant_skill_files.go @@ -0,0 +1,216 @@ +package service + +import ( + "bytes" + "context" + "encoding/base64" + "fmt" + "io" + "path" + "sort" + "strings" + "unicode/utf8" + + apperrors "github.com/Tencent/WeKnora/internal/errors" +) + +// skillFileTextLimit is how much of a text file the admin browser is given. +// The archive itself may hold up to maxSkillBundleFileBytes; dumping that +// into a JSON response would freeze the settings drawer. +const skillFileTextLimit = 1 << 20 // 1 MiB + +// skillFileImageLimit is the decoded size cap for an inline image preview. +const skillFileImageLimit = 2 << 20 // 2 MiB + +const ( + skillFileEncodingUTF8 = "utf-8" + skillFileEncodingBase64 = "base64" + skillFileEncodingBinary = "binary" +) + +// SkillFileEntry is one path in an installed skill's stored archive. +type SkillFileEntry struct { + Path string `json:"path"` + Size int64 `json:"size"` +} + +// SkillFileContent is one file the admin browser asked to open. +type SkillFileContent struct { + Path string `json:"path"` + Size int64 `json:"size"` + Encoding string `json:"encoding"` + Content string `json:"content,omitempty"` + MediaType string `json:"media_type,omitempty"` + Truncated bool `json:"truncated,omitempty"` + Binary bool `json:"binary,omitempty"` +} + +// ListSkillFiles lists the stored archive of one installed skill. The files +// come from the uploaded bundle rather than the live image: browsing must +// work while the skill is still installing, and without booting a sandbox. +func (s *TenantSkillService) ListSkillFiles( + ctx context.Context, tenantID uint64, configID, skillID string, +) ([]SkillFileEntry, error) { + files, err := s.skillBundleFiles(ctx, tenantID, configID, skillID) + if err != nil { + return nil, err + } + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + sort.Strings(names) + out := make([]SkillFileEntry, 0, len(names)) + for _, name := range names { + out = append(out, SkillFileEntry{Path: name, Size: int64(len(files[name]))}) + } + return out, nil +} + +// ReadSkillFile returns one file from the stored archive. Binary files are +// either inlined as base64 (images small enough to preview) or reported +// without a body so the UI can say they cannot be opened. +func (s *TenantSkillService) ReadSkillFile( + ctx context.Context, tenantID uint64, configID, skillID, relativePath string, +) (*SkillFileContent, error) { + clean, err := safeSkillFilePath(relativePath) + if err != nil { + return nil, apperrors.NewBadRequestError(err.Error()) + } + files, err := s.skillBundleFiles(ctx, tenantID, configID, skillID) + if err != nil { + return nil, err + } + body, ok := files[clean] + if !ok { + return nil, apperrors.NewNotFoundError("skill file not found") + } + return projectSkillFileContent(clean, body), nil +} + +func (s *TenantSkillService) skillBundleFiles( + ctx context.Context, tenantID uint64, configID, skillID string, +) (map[string][]byte, error) { + 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") + } + ref := strings.TrimSpace(skill.BundleRef) + if ref == "" { + return nil, apperrors.NewNotFoundError("skill files are not available") + } + fs, err := s.fileServiceForTenant(ctx, tenantID) + if err != nil { + return nil, err + } + reader, err := fs.GetFile(ctx, ref) + if err != nil { + return nil, fmt.Errorf("download bundle of skill %s: %w", skill.Name, err) + } + defer func() { _ = reader.Close() }() + archive, err := io.ReadAll(io.LimitReader(reader, maxSkillBundleTotalBytes+1)) + if err != nil { + return nil, fmt.Errorf("read bundle of skill %s: %w", skill.Name, err) + } + if len(archive) > maxSkillBundleTotalBytes { + return nil, fmt.Errorf("skill bundle %s is larger than the upload limit", ref) + } + bundle, err := ParseSkillBundle(archive) + if err != nil { + return nil, err + } + return bundle.Files, nil +} + +// safeSkillFilePath normalises a caller-supplied relative path and refuses +// anything that leaves the skill directory. +func safeSkillFilePath(relativePath string) (string, error) { + trimmed := strings.TrimSpace(relativePath) + if trimmed == "" { + return "", fmt.Errorf("skill file path is required") + } + if strings.Contains(trimmed, "\\") { + return "", fmt.Errorf("invalid skill file path: %s", relativePath) + } + if path.IsAbs(trimmed) { + return "", fmt.Errorf("invalid skill file path: %s", relativePath) + } + for _, seg := range strings.Split(trimmed, "/") { + if seg == ".." { + return "", fmt.Errorf("invalid skill file path: %s", relativePath) + } + } + clean := path.Clean(trimmed) + if clean == "." || clean == ".." || strings.HasPrefix(clean, "../") { + return "", fmt.Errorf("invalid skill file path: %s", relativePath) + } + return clean, nil +} + +func projectSkillFileContent(rel string, body []byte) *SkillFileContent { + out := &SkillFileContent{ + Path: rel, + Size: int64(len(body)), + } + if mediaType, ok := skillImageMediaType(rel); ok { + out.MediaType = mediaType + if len(body) > skillFileImageLimit { + out.Encoding = skillFileEncodingBinary + out.Binary = true + return out + } + out.Encoding = skillFileEncodingBase64 + out.Content = base64.StdEncoding.EncodeToString(body) + return out + } + if skillFileLooksBinary(body) { + out.Encoding = skillFileEncodingBinary + out.Binary = true + return out + } + out.Encoding = skillFileEncodingUTF8 + if ext := strings.ToLower(path.Ext(rel)); ext != "" { + out.MediaType = "text/plain" + if ext == ".md" || ext == ".markdown" { + out.MediaType = "text/markdown" + } + } + if len(body) > skillFileTextLimit { + out.Content = string(body[:skillFileTextLimit]) + out.Truncated = true + return out + } + out.Content = string(body) + return out +} + +func skillFileLooksBinary(body []byte) bool { + if bytes.IndexByte(body, 0) >= 0 { + return true + } + return !utf8.Valid(body) +} + +func skillImageMediaType(rel string) (string, bool) { + switch strings.ToLower(path.Ext(rel)) { + case ".png": + return "image/png", true + case ".jpg", ".jpeg": + return "image/jpeg", true + case ".gif": + return "image/gif", true + case ".webp": + return "image/webp", true + case ".bmp": + return "image/bmp", true + case ".ico": + return "image/x-icon", true + case ".svg": + return "image/svg+xml", true + default: + return "", false + } +} diff --git a/internal/application/service/tenant_skill_files_test.go b/internal/application/service/tenant_skill_files_test.go new file mode 100644 index 00000000..f3290092 --- /dev/null +++ b/internal/application/service/tenant_skill_files_test.go @@ -0,0 +1,133 @@ +package service + +import ( + "context" + "encoding/base64" + "testing" + + "github.com/stretchr/testify/require" + + apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/types" +) + +func TestListSkillFilesReadsTheStoredArchive(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + files, err := fx.svc.ListSkillFiles(context.Background(), 7, "cfg-1", "sk-1") + require.NoError(t, err) + require.Equal(t, []SkillFileEntry{ + {Path: "SKILL.md", Size: int64(len(validSkillMD))}, + {Path: "scripts/extract.py", Size: int64(len("print('hi')\n"))}, + }, files) +} + +func TestListSkillFilesRefusesAnotherWorkspace(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + _, err := fx.svc.ListSkillFiles(context.Background(), 8, "cfg-1", "sk-1") + require.Error(t, err) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok) + require.Equal(t, 404, appErr.HTTPCode) +} + +func TestListSkillFilesReportsMissingBundle(t *testing.T) { + fx := newInstallFixture(t) + + _, err := fx.svc.ListSkillFiles(context.Background(), 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 TestReadSkillFileReturnsTextContent(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + file, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "scripts/extract.py") + require.NoError(t, err) + require.Equal(t, "scripts/extract.py", file.Path) + require.Equal(t, skillFileEncodingUTF8, file.Encoding) + require.Equal(t, "print('hi')\n", file.Content) + require.False(t, file.Binary) +} + +func TestReadSkillFileRejectsPathTraversal(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + for _, rel := range []string{"../secret", "/etc/passwd", "scripts/../../SKILL.md", `scripts\extract.py`} { + _, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", rel) + require.Error(t, err, rel) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok, rel) + require.Equal(t, 400, appErr.HTTPCode, rel) + } +} + +func TestReadSkillFileReportsMissingPath(t *testing.T) { + fx := newInstallFixture(t) + fx.seedStoredSkillBundle(t) + + _, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "missing.txt") + require.Error(t, err) + appErr, ok := apperrors.IsAppError(err) + require.True(t, ok) + require.Equal(t, 404, appErr.HTTPCode) +} + +func TestReadSkillFileInlinesASmallImage(t *testing.T) { + fx := newInstallFixture(t) + png := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a} + archive := zipBundle(t, map[string]string{ + "SKILL.md": validSkillMD, + "assets/a.png": string(png), + }) + fx.storeSkillBundle(t, "sk-1", archive) + + file, err := fx.svc.ReadSkillFile(context.Background(), 7, "cfg-1", "sk-1", "assets/a.png") + require.NoError(t, err) + require.Equal(t, skillFileEncodingBase64, file.Encoding) + require.Equal(t, "image/png", file.MediaType) + decoded, err := base64.StdEncoding.DecodeString(file.Content) + require.NoError(t, err) + require.Equal(t, png, decoded) +} + +func TestProjectSkillFileContentMarksBinaryWithoutInlining(t *testing.T) { + got := projectSkillFileContent("scripts/tool.bin", []byte{0x00, 0x01, 0xff}) + require.True(t, got.Binary) + require.Equal(t, skillFileEncodingBinary, got.Encoding) + require.Empty(t, got.Content) +} + +func (f *installFixture) seedStoredSkillBundle(t *testing.T) { + t.Helper() + archive, err := zipSkillFiles(map[string][]byte{ + "SKILL.md": []byte(validSkillMD), + "scripts/extract.py": []byte("print('hi')\n"), + }) + require.NoError(t, err) + f.storeSkillBundle(t, "sk-1", archive) +} + +func (f *installFixture) storeSkillBundle(t *testing.T, skillID string, archive []byte) { + t.Helper() + ctx := context.Background() + skill, err := f.skillRepo.GetSkill(ctx, 7, "cfg-1", skillID) + require.NoError(t, err) + require.NotNil(t, skill) + skill.BundleRef = "file://bundle.zip" + skill.Status = types.SkillStatusReady + require.NoError(t, f.skillRepo.UpdateSkill(ctx, skill)) + if f.storedBundles == nil { + f.storedBundles = map[string][]byte{} + } + copied := make([]byte, len(archive)) + copy(copied, archive) + f.storedBundles["file://bundle.zip"] = copied +} diff --git a/internal/application/service/tenant_skill_install_test.go b/internal/application/service/tenant_skill_install_test.go index a472fbbd..bd4b8e37 100644 --- a/internal/application/service/tenant_skill_install_test.go +++ b/internal/application/service/tenant_skill_install_test.go @@ -1205,6 +1205,9 @@ type installFixture struct { // whose archive will later be unreadable. saveErr error savedBundles int + // storedBundles is what GetFile serves back, keyed by the SaveBytes + // reference, so ListSkillFiles / ReadSkillFile can open a stored archive. + storedBundles map[string][]byte } func newInstallFixture(t *testing.T) *installFixture { @@ -2208,17 +2211,30 @@ func (installFileService) SaveFile(context.Context, *multipart.FileHeader, uint6 return "", nil } -func (s installFileService) SaveBytes(context.Context, []byte, uint64, string, bool) (string, error) { +func (s installFileService) SaveBytes(_ context.Context, data []byte, _ uint64, _ string, _ bool) (string, error) { if s.fx != nil { s.fx.savedBundles++ if s.fx.saveErr != nil { return "", s.fx.saveErr } + if s.fx.storedBundles == nil { + s.fx.storedBundles = map[string][]byte{} + } + copied := make([]byte, len(data)) + copy(copied, data) + s.fx.storedBundles["file://bundle.zip"] = copied } return "file://bundle.zip", nil } -func (installFileService) GetFile(context.Context, string) (io.ReadCloser, error) { return nil, nil } -func (installFileService) GetFileURL(context.Context, string) (string, error) { return "", nil } +func (s installFileService) GetFile(_ context.Context, ref string) (io.ReadCloser, error) { + if s.fx != nil { + if data, ok := s.fx.storedBundles[ref]; ok { + return io.NopCloser(bytes.NewReader(data)), nil + } + } + return nil, errors.New("bundle not found") +} +func (installFileService) GetFileURL(context.Context, string) (string, error) { return "", nil } func (s installFileService) DeleteFile(_ context.Context, ref string) error { if s.fx != nil { s.fx.deletedBundles = append(s.fx.deletedBundles, ref) diff --git a/internal/handler/sandbox_skill.go b/internal/handler/sandbox_skill.go index a7f25fbb..b4012968 100644 --- a/internal/handler/sandbox_skill.go +++ b/internal/handler/sandbox_skill.go @@ -44,6 +44,12 @@ const ( type sandboxSkillService interface { ListSkills(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillEntity, error) GetSkill(ctx context.Context, tenantID uint64, configID, skillID string) (*types.TenantSkillEntity, error) + ListSkillFiles( + ctx context.Context, tenantID uint64, configID, skillID string, + ) ([]service.SkillFileEntry, error) + ReadSkillFile( + ctx context.Context, tenantID uint64, configID, skillID, relativePath string, + ) (*service.SkillFileContent, error) SetSkillEnabled( ctx context.Context, tenantID uint64, configID, skillID string, enabled bool, ) (*types.TenantSkillEntity, error) @@ -185,6 +191,57 @@ func (h *SandboxSkillHandler) Get(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": true, "data": toSkillResponse(skill)}) } +// ListFiles godoc +// @Summary List files of an installed skill +// @Description List files in the stored skill bundle without starting a sandbox. +// @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{} "Skill files" +// @Failure 401 {object} map[string]interface{} "Unauthorized" +// @Failure 404 {object} apperrors.AppError "Skill or files not found" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /sandbox-configs/{id}/skills/{skillId}/files [get] +func (h *SandboxSkillHandler) ListFiles(c *gin.Context) { + files, err := h.service.ListSkillFiles( + c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), c.Param("skillId"), + ) + if err != nil { + _ = c.Error(err) + return + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": files}) +} + +// GetFile godoc +// @Summary Read one file of an installed skill +// @Description Read one skill file as UTF-8, a small base64 image, or binary. +// @Tags SandboxConfig +// @Produce json +// @Param id path string true "Sandbox config ID" +// @Param skillId path string true "Skill ID" +// @Param path query string true "Skill-root-relative file path" +// @Success 200 {object} map[string]interface{} "Skill file" +// @Failure 400 {object} apperrors.AppError "Invalid path" +// @Failure 401 {object} map[string]interface{} "Unauthorized" +// @Failure 404 {object} apperrors.AppError "Skill or file not found" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /sandbox-configs/{id}/skills/{skillId}/files/content [get] +func (h *SandboxSkillHandler) GetFile(c *gin.Context) { + file, err := h.service.ReadSkillFile( + c.Request.Context(), sandboxConfigTenantID(c), + c.Param("id"), c.Param("skillId"), c.Query("path"), + ) + if err != nil { + _ = c.Error(err) + return + } + c.JSON(http.StatusOK, gin.H{"success": true, "data": file}) +} + // Upload godoc // @Summary Install a skill // @Description Install a skill onto this sandbox config's image. Send a zip diff --git a/internal/handler/sandbox_skill_test.go b/internal/handler/sandbox_skill_test.go index dd911b25..15fb3b55 100644 --- a/internal/handler/sandbox_skill_test.go +++ b/internal/handler/sandbox_skill_test.go @@ -17,6 +17,7 @@ import ( "github.com/stretchr/testify/require" "github.com/Tencent/WeKnora/internal/application/service" + apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/middleware" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -41,6 +42,12 @@ type fakeSandboxSkillService struct { sourceErr error removeErr error + files []service.SkillFileEntry + file *service.SkillFileContent + filesErr error + fileErr error + filePath string + last service.SkillProgress hasLast bool events chan service.SkillProgress @@ -115,6 +122,39 @@ func (f *fakeSandboxSkillService) SetSkillEnabled( return skill, nil } +func (f *fakeSandboxSkillService) ListSkillFiles( + _ context.Context, tenantID uint64, configID, skillID string, +) ([]service.SkillFileEntry, error) { + if f.filesErr != nil { + return nil, f.filesErr + } + skill, err := f.GetSkill(context.Background(), tenantID, configID, skillID) + if err != nil { + return nil, err + } + if skill == nil { + return nil, apperrors.NewNotFoundError("skill not found") + } + return f.files, nil +} + +func (f *fakeSandboxSkillService) ReadSkillFile( + _ context.Context, tenantID uint64, configID, skillID, relativePath string, +) (*service.SkillFileContent, error) { + f.filePath = relativePath + if f.fileErr != nil { + return nil, f.fileErr + } + skill, err := f.GetSkill(context.Background(), tenantID, configID, skillID) + if err != nil { + return nil, err + } + if skill == nil { + return nil, apperrors.NewNotFoundError("skill not found") + } + return f.file, nil +} + func (f *fakeSandboxSkillService) InstallSkill( _ context.Context, tenantID uint64, configID string, archive []byte, ) (string, error) { @@ -198,6 +238,8 @@ func newSkillTestRouter(h *SandboxSkillHandler) *gin.Engine { r.GET("/sandbox-configs/:id/skills", h.List) r.POST("/sandbox-configs/:id/skills", h.Upload) r.GET("/sandbox-configs/:id/skills/:skillId", h.Get) + r.GET("/sandbox-configs/:id/skills/:skillId/files", h.ListFiles) + r.GET("/sandbox-configs/:id/skills/:skillId/files/content", h.GetFile) 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) @@ -937,3 +979,88 @@ func transcriptTypes(frames []types.StreamResponse) []string { } return out } + +func TestSandboxSkillListFilesReturnsTheArchive(t *testing.T) { + svc := &fakeSandboxSkillService{ + skills: map[string]*types.TenantSkillEntity{ + "skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Name: "pdf"}, + }, + files: []service.SkillFileEntry{ + {Path: "SKILL.md", Size: 12}, + {Path: "scripts/run.py", Size: 20}, + }, + } + router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil)) + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/sandbox-configs/cfg-a/skills/skill-1/files", nil) + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + var body struct { + Success bool `json:"success"` + Data []service.SkillFileEntry `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.True(t, body.Success) + require.Equal(t, svc.files, body.Data) +} + +func TestSandboxSkillListFilesMissingSkillReturns404(t *testing.T) { + router := newSkillTestRouter(NewSandboxSkillHandler(&fakeSandboxSkillService{}, nil)) + + w := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/sandbox-configs/cfg-a/skills/missing/files", nil) + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusNotFound, w.Code, "body=%s", w.Body.String()) +} + +func TestSandboxSkillGetFileReturnsContent(t *testing.T) { + svc := &fakeSandboxSkillService{ + skills: map[string]*types.TenantSkillEntity{ + "skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a", Name: "pdf"}, + }, + file: &service.SkillFileContent{ + Path: "scripts/run.py", + Size: 11, + Encoding: "utf-8", + Content: "print('hi')", + }, + } + router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil)) + + w := httptest.NewRecorder() + req := httptest.NewRequest( + http.MethodGet, "/sandbox-configs/cfg-a/skills/skill-1/files/content?path=scripts/run.py", nil, + ) + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + require.Equal(t, "scripts/run.py", svc.filePath) + var body struct { + Success bool `json:"success"` + Data service.SkillFileContent `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Equal(t, "print('hi')", body.Data.Content) +} + +func TestSandboxSkillGetFileInvalidPathReturns400(t *testing.T) { + svc := &fakeSandboxSkillService{ + skills: map[string]*types.TenantSkillEntity{ + "skill-1": {ID: "skill-1", SandboxConfigID: "cfg-a"}, + }, + fileErr: apperrors.NewBadRequestError("invalid skill file path: ../secret"), + } + router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil)) + + w := httptest.NewRecorder() + req := httptest.NewRequest( + http.MethodGet, "/sandbox-configs/cfg-a/skills/skill-1/files/content?path=../secret", nil, + ) + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, "body=%s", w.Body.String()) + require.Equal(t, "../secret", svc.filePath) +} diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go index eae9f309..e2b970be 100644 --- a/internal/router/router_api_key_capabilities_test.go +++ b/internal/router/router_api_key_capabilities_test.go @@ -406,6 +406,8 @@ func TestSandboxConfigRoutesRequireFullAccessOnly(t *testing.T) { {http.MethodGet, "/api/v1/sandbox-configs/:id/skills"}, {http.MethodPost, "/api/v1/sandbox-configs/:id/skills"}, {http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId"}, + {http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/files"}, + {http.MethodGet, "/api/v1/sandbox-configs/:id/skills/:skillId/files/content"}, {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.go index 76a2fdd5..316287cc 100644 --- a/internal/router/routes_infra.go +++ b/internal/router/routes_infra.go @@ -65,6 +65,8 @@ func RegisterSandboxConfigRoutes( configs.GET("/:id/skills", g.Admin(), skills.List) configs.POST("/:id/skills", g.Admin(), skills.Upload) configs.GET("/:id/skills/:skillId", g.Admin(), skills.Get) + configs.GET("/:id/skills/:skillId/files", g.Admin(), skills.ListFiles) + configs.GET("/:id/skills/:skillId/files/content", g.Admin(), skills.GetFile) 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)