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.main
parent
19bcc9b532
commit
ebfd5ef0fb
|
|
@ -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` 函数,其中展示了客户端的完整使用流程。
|
||||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
|||
135
docs/docs.go
135
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": {
|
||||
|
|
|
|||
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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 }>
|
||||
}
|
||||
|
|
|
|||
|
|
@ -173,6 +173,18 @@
|
|||
@change="(v: any) => toggleEnabled(skill, Boolean(v))"
|
||||
/>
|
||||
</t-tooltip>
|
||||
<span class="skill-item__actions-divider" />
|
||||
<t-tooltip :content="$t('settings.sandbox.skillFiles')" placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="skill-item__icon-btn"
|
||||
:class="{ 'is-on': filesDrawerVisible && filesSkillId === skill.id }"
|
||||
:aria-label="$t('settings.sandbox.skillFiles')"
|
||||
@click="openSkillFiles(skill)"
|
||||
>
|
||||
<t-icon name="folder" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-popup
|
||||
v-if="hasTranscript(skill)"
|
||||
:visible="expandedSkillId === skill.id"
|
||||
|
|
@ -185,17 +197,14 @@
|
|||
:overlay-inner-style="{ padding: '0' }"
|
||||
@visible-change="(visible: boolean) => onTranscriptVisible(skill, visible)"
|
||||
>
|
||||
<t-button
|
||||
variant="text"
|
||||
shape="square"
|
||||
<button
|
||||
type="button"
|
||||
class="skill-item__icon-btn"
|
||||
:class="{ 'skill-transcript-toggle--on': expandedSkillId === skill.id }"
|
||||
:title="$t('settings.sandbox.skillTranscript')"
|
||||
:class="{ 'is-on': expandedSkillId === skill.id }"
|
||||
:aria-label="$t('settings.sandbox.skillTranscript')"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="chat-bubble-history" size="16px" />
|
||||
</template>
|
||||
</t-button>
|
||||
<t-icon name="chat-bubble-history" size="16px" />
|
||||
</button>
|
||||
<template #content>
|
||||
<div class="skill-transcript-popup__panel">
|
||||
<header class="skill-transcript-popup__head">
|
||||
|
|
@ -243,41 +252,47 @@
|
|||
@confirm="removeSkill(skill)"
|
||||
>
|
||||
<t-tooltip :content="$t('common.delete')" placement="top">
|
||||
<t-button
|
||||
theme="danger"
|
||||
variant="text"
|
||||
shape="square"
|
||||
class="skill-item__icon-btn"
|
||||
:disabled="isBusy(skill)"
|
||||
:loading="deletingId === skill.id"
|
||||
<button
|
||||
type="button"
|
||||
class="skill-item__icon-btn skill-item__icon-btn--danger"
|
||||
:disabled="isBusy(skill) || deletingId === skill.id"
|
||||
:aria-label="$t('common.delete')"
|
||||
>
|
||||
<template #icon><t-icon name="delete" size="16px" /></template>
|
||||
</t-button>
|
||||
<t-icon name="delete" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</t-popconfirm>
|
||||
</div>
|
||||
</div>
|
||||
<p
|
||||
v-if="skill.description"
|
||||
class="skill-item__desc"
|
||||
:class="{ 'skill-item__desc--expanded': isCopyExpanded(skill.id) }"
|
||||
>
|
||||
{{ skill.description }}
|
||||
</p>
|
||||
<button
|
||||
v-if="canToggleCopy(skill)"
|
||||
type="button"
|
||||
class="skill-item__toggle"
|
||||
@click="toggleCopy(skill.id)"
|
||||
>
|
||||
{{ isCopyExpanded(skill.id) ? $t('common.collapse') : $t('common.expand') }}
|
||||
</button>
|
||||
<div v-if="skill.description" class="skill-item__copy">
|
||||
<p
|
||||
class="skill-item__desc"
|
||||
:class="{ 'skill-item__desc--expanded': isCopyExpanded(skill.id) }"
|
||||
>
|
||||
{{ skill.description }}
|
||||
</p>
|
||||
<button
|
||||
v-if="canToggleCopy(skill)"
|
||||
type="button"
|
||||
class="skill-item__toggle"
|
||||
@click="toggleCopy(skill.id)"
|
||||
>
|
||||
{{ isCopyExpanded(skill.id) ? $t('common.collapse') : $t('common.expand') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="failedError(skill)" class="skill-item__error">{{ failedError(skill) }}</p>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</t-loading>
|
||||
|
||||
<SkillFilesDrawer
|
||||
v-model:visible="filesDrawerVisible"
|
||||
:config-id="record?.id || ''"
|
||||
:skill-id="filesSkillId"
|
||||
:skill-name="filesSkillName"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
|
@ -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<Set<string>>(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);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,306 @@
|
|||
<template>
|
||||
<teleport to="body">
|
||||
<div
|
||||
v-if="visible"
|
||||
class="skill-files-drawer-resize-handle"
|
||||
:class="{ 'skill-files-drawer-resize-handle--active': resizing }"
|
||||
:style="{ right: `${drawerWidth}px`, '--skill-files-drawer-travel': `${drawerWidth}px` }"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
@mousedown.prevent="onResizeStart"
|
||||
>
|
||||
<div class="skill-files-drawer-resize-line" />
|
||||
</div>
|
||||
</teleport>
|
||||
<t-drawer
|
||||
:visible="visible"
|
||||
:z-index="2600"
|
||||
:size="`${drawerWidth}px`"
|
||||
attach="body"
|
||||
:close-btn="false"
|
||||
:footer="false"
|
||||
:header="false"
|
||||
:show-overlay="true"
|
||||
:close-on-overlay-click="true"
|
||||
destroy-on-close
|
||||
placement="right"
|
||||
:class="['skill-files-drawer', { 'skill-files-drawer--resizing': resizing }]"
|
||||
@close="onClose"
|
||||
>
|
||||
<div class="skill-files-drawer__shell">
|
||||
<header class="skill-files-drawer__head">
|
||||
<div class="skill-files-drawer__head-icon">
|
||||
<t-icon name="folder" />
|
||||
</div>
|
||||
<div class="skill-files-drawer__head-text">
|
||||
<div class="skill-files-drawer__title">{{ skillName }}</div>
|
||||
<div class="skill-files-drawer__subtitle">{{ $t('settings.sandbox.skillFilesTitle') }}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="skill-files-drawer__close"
|
||||
:title="$t('common.close')"
|
||||
:aria-label="$t('common.close')"
|
||||
@click="onClose"
|
||||
>
|
||||
<t-icon name="close" size="16px" />
|
||||
</button>
|
||||
</header>
|
||||
<SkillFilesPanel
|
||||
v-if="visible && configId && skillId"
|
||||
:config-id="configId"
|
||||
:skill-id="skillId"
|
||||
:drawer-width="drawerWidth"
|
||||
/>
|
||||
</div>
|
||||
</t-drawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import SkillFilesPanel from '@/components/SkillFilesPanel.vue'
|
||||
|
||||
const WIDTH_KEY = 'skill-files-drawer:width'
|
||||
const DEFAULT_WIDTH = 720
|
||||
const MIN_WIDTH = 480
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
configId: string
|
||||
skillId: string
|
||||
skillName: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
}>()
|
||||
|
||||
const drawerWidth = ref(DEFAULT_WIDTH)
|
||||
const resizing = ref(false)
|
||||
|
||||
let resizeStartX = 0
|
||||
let resizeStartWidth = 0
|
||||
|
||||
function maxWidth() {
|
||||
return Math.min(1200, Math.max(MIN_WIDTH, Math.floor(window.innerWidth * 0.92)))
|
||||
}
|
||||
|
||||
function clampWidth(width: number) {
|
||||
return Math.max(MIN_WIDTH, Math.min(maxWidth(), Math.round(width)))
|
||||
}
|
||||
|
||||
function loadWidth() {
|
||||
try {
|
||||
const raw = localStorage.getItem(WIDTH_KEY)
|
||||
const parsed = raw ? parseInt(raw, 10) : NaN
|
||||
if (!Number.isNaN(parsed)) drawerWidth.value = clampWidth(parsed)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function persistWidth() {
|
||||
try {
|
||||
localStorage.setItem(WIDTH_KEY, String(drawerWidth.value))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function onResizeStart(e: MouseEvent) {
|
||||
resizing.value = true
|
||||
resizeStartX = e.clientX
|
||||
resizeStartWidth = drawerWidth.value
|
||||
document.addEventListener('mousemove', onResizeMove)
|
||||
document.addEventListener('mouseup', onResizeEnd)
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
}
|
||||
|
||||
function onResizeMove(e: MouseEvent) {
|
||||
drawerWidth.value = clampWidth(resizeStartWidth + (resizeStartX - e.clientX))
|
||||
}
|
||||
|
||||
function onResizeEnd() {
|
||||
document.removeEventListener('mousemove', onResizeMove)
|
||||
document.removeEventListener('mouseup', onResizeEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
resizing.value = false
|
||||
persistWidth()
|
||||
}
|
||||
|
||||
function cleanupResize() {
|
||||
document.removeEventListener('mousemove', onResizeMove)
|
||||
document.removeEventListener('mouseup', onResizeEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
resizing.value = false
|
||||
}
|
||||
|
||||
function onWindowResize() {
|
||||
drawerWidth.value = clampWidth(drawerWidth.value)
|
||||
}
|
||||
|
||||
function onClose() {
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(open) => {
|
||||
if (open) loadWidth()
|
||||
},
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
loadWidth()
|
||||
window.addEventListener('resize', onWindowResize, { passive: true })
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', onWindowResize)
|
||||
cleanupResize()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.skill-files-drawer__shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.skill-files-drawer__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
.skill-files-drawer__head-icon {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 9px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(7, 192, 95, 0.1);
|
||||
color: var(--td-brand-color);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.skill-files-drawer__head-text {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.skill-files-drawer__title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.skill-files-drawer__subtitle {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.skill-files-drawer__close {
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.t-drawer.skill-files-drawer .t-drawer__content-wrapper,
|
||||
.t-drawer.skill-files-drawer .t-drawer__content {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.t-drawer.skill-files-drawer .t-drawer__body {
|
||||
padding: 0 !important;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.t-drawer.skill-files-drawer--resizing .t-drawer__content,
|
||||
.t-drawer.skill-files-drawer--resizing .t-drawer__content-wrapper {
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.skill-files-drawer-resize-handle {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 12px;
|
||||
margin-left: -6px;
|
||||
cursor: col-resize;
|
||||
z-index: 2601;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: skill-files-drawer-resize-handle-in 0.28s cubic-bezier(0.38, 0, 0.24, 1) both;
|
||||
}
|
||||
|
||||
@keyframes skill-files-drawer-resize-handle-in {
|
||||
from {
|
||||
transform: translateX(var(--skill-files-drawer-travel));
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-drawer-resize-line {
|
||||
width: 2px;
|
||||
height: 48px;
|
||||
border-radius: 1px;
|
||||
background: var(--td-component-border);
|
||||
opacity: 0.55;
|
||||
transition: opacity 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.skill-files-drawer-resize-handle:hover .skill-files-drawer-resize-line,
|
||||
.skill-files-drawer-resize-handle--active .skill-files-drawer-resize-line {
|
||||
opacity: 1;
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,833 @@
|
|||
<template>
|
||||
<div
|
||||
class="skill-files-panel"
|
||||
:class="{ 'skill-files-panel--splitting': splitting }"
|
||||
:style="{ '--skill-files-nav-width': `${navWidth}px` }"
|
||||
>
|
||||
<aside ref="navEl" class="skill-files-panel__nav">
|
||||
<t-loading :loading="listLoading" size="small">
|
||||
<p v-if="listError" class="skill-files-panel__hint">{{ listError }}</p>
|
||||
<p v-else-if="!listLoading && !visibleRows.length" class="skill-files-panel__hint">
|
||||
{{ $t('settings.sandbox.skillFilesEmpty') }}
|
||||
</p>
|
||||
<ul v-else-if="visibleRows.length" class="skill-files-panel__list">
|
||||
<li v-for="row in visibleRows" :key="row.path">
|
||||
<button
|
||||
type="button"
|
||||
class="skill-files-panel__item"
|
||||
:class="{
|
||||
'is-active': selectedPath === row.path,
|
||||
'is-dir': row.isDir,
|
||||
}"
|
||||
:title="row.path"
|
||||
@click="row.isDir ? toggleDir(row.path) : selectFile(row.path)"
|
||||
>
|
||||
<span class="skill-files-panel__indent" :style="{ width: `${row.depth * 12}px` }" />
|
||||
<t-icon
|
||||
class="skill-files-panel__icon"
|
||||
:name="row.isDir ? (expandedDirs.has(row.path) ? 'folder-open' : 'folder') : fileIcon(row.name)"
|
||||
size="16px"
|
||||
/>
|
||||
<span class="skill-files-panel__name">{{ row.name }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</t-loading>
|
||||
</aside>
|
||||
|
||||
<section class="skill-files-panel__main">
|
||||
<div v-if="selectedPath" class="skill-files-panel__bar">
|
||||
<span class="skill-files-panel__path" :title="selectedPath">{{ selectedPath }}</span>
|
||||
<button
|
||||
v-if="canToggleMarkdown"
|
||||
type="button"
|
||||
class="skill-files-panel__link"
|
||||
@click="markdownMode = markdownMode === 'preview' ? 'source' : 'preview'"
|
||||
>
|
||||
{{ markdownMode === 'preview' ? $t('settings.sandbox.skillFilesSource') : $t('settings.sandbox.skillFilesPreview') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="canCopy"
|
||||
type="button"
|
||||
class="skill-files-panel__link"
|
||||
@click="copyContent"
|
||||
>
|
||||
{{ $t('common.copy') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="skill-files-panel__view">
|
||||
<t-loading v-if="fileLoading" size="small" />
|
||||
<p v-else-if="fileError" class="skill-files-panel__hint">{{ fileError }}</p>
|
||||
<p v-else-if="!selectedPath" class="skill-files-panel__hint">
|
||||
{{ $t('settings.sandbox.skillFilesSelectHint') }}
|
||||
</p>
|
||||
<template v-else>
|
||||
<p v-if="file?.truncated" class="skill-files-panel__warn">
|
||||
{{ $t('settings.sandbox.skillFilesTruncated') }}
|
||||
</p>
|
||||
<img
|
||||
v-if="imageSrc"
|
||||
class="skill-files-panel__image"
|
||||
:src="imageSrc"
|
||||
:alt="selectedPath"
|
||||
/>
|
||||
<template v-else-if="showMarkdown">
|
||||
<dl v-if="frontmatterFields.length" class="skill-files-panel__meta">
|
||||
<div
|
||||
v-for="field in frontmatterFields"
|
||||
:key="field.key"
|
||||
class="skill-files-panel__meta-row"
|
||||
>
|
||||
<dt>{{ field.key }}</dt>
|
||||
<dd :class="{ 'is-code': field.code }">{{ field.value }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div
|
||||
v-if="markdownHtml"
|
||||
ref="markdownEl"
|
||||
class="skill-files-panel__markdown markdown-content"
|
||||
v-html="markdownHtml"
|
||||
/>
|
||||
</template>
|
||||
<pre v-else-if="file?.encoding === 'utf-8'" class="skill-files-panel__code"><code class="hljs" v-html="highlightedHtml" /></pre>
|
||||
<p v-else-if="file?.binary" class="skill-files-panel__hint">
|
||||
{{ $t('settings.sandbox.skillFilesBinary') }}
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<teleport to="body">
|
||||
<div
|
||||
v-if="drawerWidth > 0 && splitLeft > 0"
|
||||
class="skill-files-split-handle"
|
||||
:class="{ 'skill-files-split-handle--active': splitting }"
|
||||
:style="{ left: `${splitLeft}px` }"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
@mousedown.prevent="onSplitStart"
|
||||
>
|
||||
<div class="skill-files-split-handle__line" />
|
||||
</div>
|
||||
</teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import hljs from 'highlight.js'
|
||||
import 'katex/dist/katex.min.css'
|
||||
import { copyWithToast } from '@/utils/clipboard'
|
||||
import { getFileIcon } from '@/utils/files'
|
||||
import { sanitizeMarkdownHTML, safeMarkdownToHTML } from '@/utils/security'
|
||||
import {
|
||||
createChatMarkdownRenderer,
|
||||
renderChatMarkdown,
|
||||
} from '@/utils/chatMarkdownRenderer'
|
||||
import {
|
||||
createMermaidCodeRenderer,
|
||||
enhanceMarkdownContainer,
|
||||
} from '@/utils/mermaidShared'
|
||||
import {
|
||||
getConfigSkillFile,
|
||||
listConfigSkillFiles,
|
||||
type ConfigSkillFileContent,
|
||||
type ConfigSkillFileEntry,
|
||||
} from '@/api/system'
|
||||
|
||||
interface FileNode {
|
||||
name: string
|
||||
path: string
|
||||
isDir: boolean
|
||||
children?: FileNode[]
|
||||
}
|
||||
|
||||
interface VisibleRow {
|
||||
name: string
|
||||
path: string
|
||||
isDir: boolean
|
||||
depth: number
|
||||
}
|
||||
|
||||
interface FrontmatterField {
|
||||
key: string
|
||||
value: string
|
||||
code: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
configId: string
|
||||
skillId: string
|
||||
drawerWidth: number
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const NAV_WIDTH_KEY = 'skill-files-panel:nav-width'
|
||||
const DEFAULT_NAV_WIDTH = 208
|
||||
const MIN_NAV_WIDTH = 156
|
||||
const MAX_NAV_WIDTH = 360
|
||||
|
||||
const navWidth = ref(DEFAULT_NAV_WIDTH)
|
||||
const splitting = ref(false)
|
||||
const navEl = ref<HTMLElement | null>(null)
|
||||
const splitLeft = ref(0)
|
||||
let splitStartX = 0
|
||||
let splitStartWidth = 0
|
||||
let splitObserver: ResizeObserver | null = null
|
||||
|
||||
function clampNavWidth(width: number) {
|
||||
return Math.max(MIN_NAV_WIDTH, Math.min(MAX_NAV_WIDTH, Math.round(width)))
|
||||
}
|
||||
|
||||
function syncSplitHandle() {
|
||||
const el = navEl.value
|
||||
if (!el) return
|
||||
splitLeft.value = Math.round(el.getBoundingClientRect().right - 12)
|
||||
}
|
||||
|
||||
function loadNavWidth() {
|
||||
try {
|
||||
const raw = localStorage.getItem(NAV_WIDTH_KEY)
|
||||
const parsed = raw ? parseInt(raw, 10) : NaN
|
||||
if (!Number.isNaN(parsed)) navWidth.value = clampNavWidth(parsed)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function persistNavWidth() {
|
||||
try {
|
||||
localStorage.setItem(NAV_WIDTH_KEY, String(navWidth.value))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function onSplitStart(e: MouseEvent) {
|
||||
splitting.value = true
|
||||
splitStartX = e.clientX
|
||||
splitStartWidth = navWidth.value
|
||||
document.addEventListener('mousemove', onSplitMove)
|
||||
document.addEventListener('mouseup', onSplitEnd)
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
}
|
||||
|
||||
function onSplitMove(e: MouseEvent) {
|
||||
navWidth.value = clampNavWidth(splitStartWidth + (e.clientX - splitStartX))
|
||||
syncSplitHandle()
|
||||
}
|
||||
|
||||
function onSplitEnd() {
|
||||
document.removeEventListener('mousemove', onSplitMove)
|
||||
document.removeEventListener('mouseup', onSplitEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
splitting.value = false
|
||||
persistNavWidth()
|
||||
}
|
||||
|
||||
function cleanupSplit() {
|
||||
document.removeEventListener('mousemove', onSplitMove)
|
||||
document.removeEventListener('mouseup', onSplitEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
splitting.value = false
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadNavWidth()
|
||||
nextTick(() => {
|
||||
syncSplitHandle()
|
||||
if (navEl.value && typeof ResizeObserver !== 'undefined') {
|
||||
splitObserver = new ResizeObserver(() => syncSplitHandle())
|
||||
splitObserver.observe(navEl.value)
|
||||
}
|
||||
})
|
||||
window.addEventListener('resize', syncSplitHandle, { passive: true })
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', syncSplitHandle)
|
||||
splitObserver?.disconnect()
|
||||
splitObserver = null
|
||||
cleanupSplit()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [navWidth.value, props.drawerWidth],
|
||||
() => {
|
||||
nextTick(syncSplitHandle)
|
||||
},
|
||||
)
|
||||
|
||||
const listLoading = ref(false)
|
||||
const fileLoading = ref(false)
|
||||
const listError = ref('')
|
||||
const nodes = ref<FileNode[]>([])
|
||||
const expandedDirs = ref<Set<string>>(new Set())
|
||||
const selectedPath = ref('')
|
||||
const file = ref<ConfigSkillFileContent | null>(null)
|
||||
const fileError = ref('')
|
||||
const markdownHtml = ref('')
|
||||
const highlightedHtml = ref('')
|
||||
const markdownMode = ref<'preview' | 'source'>('preview')
|
||||
const markdownEl = ref<HTMLElement | null>(null)
|
||||
const frontmatterFields = ref<FrontmatterField[]>([])
|
||||
const markdownRenderer = createChatMarkdownRenderer({
|
||||
codeRenderer: createMermaidCodeRenderer('skill-files-md'),
|
||||
})
|
||||
|
||||
const langMap: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
mjs: 'javascript',
|
||||
cjs: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
jsx: 'javascript',
|
||||
py: 'python',
|
||||
rb: 'ruby',
|
||||
sh: 'bash',
|
||||
bash: 'bash',
|
||||
yml: 'yaml',
|
||||
yaml: 'yaml',
|
||||
md: 'markdown',
|
||||
markdown: 'markdown',
|
||||
rs: 'rust',
|
||||
kt: 'kotlin',
|
||||
go: 'go',
|
||||
json: 'json',
|
||||
xml: 'xml',
|
||||
html: 'xml',
|
||||
css: 'css',
|
||||
sql: 'sql',
|
||||
toml: 'ini',
|
||||
ini: 'ini',
|
||||
conf: 'ini',
|
||||
}
|
||||
|
||||
function fileIcon(name: string): string {
|
||||
return getFileIcon(name)
|
||||
}
|
||||
|
||||
function extOf(path: string): string {
|
||||
const base = path.split('/').pop() || path
|
||||
const idx = base.lastIndexOf('.')
|
||||
if (idx < 0) return ''
|
||||
return base.slice(idx + 1).toLowerCase()
|
||||
}
|
||||
|
||||
function isMarkdown(path: string): boolean {
|
||||
const ext = extOf(path)
|
||||
return ext === 'md' || ext === 'markdown'
|
||||
}
|
||||
|
||||
function buildTree(entries: ConfigSkillFileEntry[]): FileNode[] {
|
||||
const root: FileNode = { name: '', path: '', isDir: true, children: [] }
|
||||
for (const entry of entries) {
|
||||
const parts = entry.path.split('/').filter(Boolean)
|
||||
let cur = root
|
||||
parts.forEach((part, i) => {
|
||||
const isLast = i === parts.length - 1
|
||||
const nodePath = parts.slice(0, i + 1).join('/')
|
||||
if (!cur.children) cur.children = []
|
||||
let next = cur.children.find((child) => child.name === part)
|
||||
if (!next) {
|
||||
next = {
|
||||
name: part,
|
||||
path: nodePath,
|
||||
isDir: !isLast,
|
||||
children: isLast ? undefined : [],
|
||||
}
|
||||
cur.children.push(next)
|
||||
} else if (!isLast) {
|
||||
next.isDir = true
|
||||
if (!next.children) next.children = []
|
||||
}
|
||||
cur = next
|
||||
})
|
||||
}
|
||||
const sortNodes = (list: FileNode[]) => {
|
||||
list.sort((a, b) => {
|
||||
if (a.path === 'SKILL.md') return -1
|
||||
if (b.path === 'SKILL.md') return 1
|
||||
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
list.forEach((node) => node.children && sortNodes(node.children))
|
||||
}
|
||||
sortNodes(root.children || [])
|
||||
return root.children || []
|
||||
}
|
||||
|
||||
function collectDirs(list: FileNode[], out: Set<string>) {
|
||||
for (const node of list) {
|
||||
if (!node.isDir) continue
|
||||
out.add(node.path)
|
||||
if (node.children) collectDirs(node.children, out)
|
||||
}
|
||||
}
|
||||
|
||||
function flattenVisible(list: FileNode[], depth: number, expanded: Set<string>, out: VisibleRow[]) {
|
||||
for (const node of list) {
|
||||
out.push({ name: node.name, path: node.path, isDir: node.isDir, depth })
|
||||
if (node.isDir && expanded.has(node.path) && node.children?.length) {
|
||||
flattenVisible(node.children, depth + 1, expanded, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toggleDir(path: string) {
|
||||
const next = new Set(expandedDirs.value)
|
||||
if (next.has(path)) next.delete(path)
|
||||
else next.add(path)
|
||||
expandedDirs.value = next
|
||||
}
|
||||
|
||||
const visibleRows = computed(() => {
|
||||
const out: VisibleRow[] = []
|
||||
flattenVisible(nodes.value, 0, expandedDirs.value, out)
|
||||
return out
|
||||
})
|
||||
const canToggleMarkdown = computed(() =>
|
||||
Boolean(selectedPath.value && isMarkdown(selectedPath.value) && file.value?.encoding === 'utf-8'),
|
||||
)
|
||||
const canCopy = computed(() => Boolean(file.value?.content && file.value.encoding === 'utf-8'))
|
||||
const showMarkdown = computed(() => canToggleMarkdown.value && markdownMode.value === 'preview')
|
||||
const imageSrc = computed(() => {
|
||||
const current = file.value
|
||||
if (!current || current.encoding !== 'base64' || !current.content || !current.media_type) return ''
|
||||
return `data:${current.media_type};base64,${current.content}`
|
||||
})
|
||||
|
||||
function highlightText(text: string, path: string): string {
|
||||
const ext = extOf(path)
|
||||
const lang = langMap[ext] || ext
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(text, { language: lang }).value
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
try {
|
||||
return hljs.highlightAuto(text).value
|
||||
} catch {
|
||||
return text.replace(/[&<>]/g, (ch) => ({ '&': '&', '<': '<', '>': '>' }[ch] || ch))
|
||||
}
|
||||
}
|
||||
|
||||
function formatFrontmatterValue(raw: string): { value: string; code: boolean } {
|
||||
let value = raw.trim()
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
|
||||
(value.startsWith("'") && value.endsWith("'") && value.length >= 2)
|
||||
) {
|
||||
value = value.slice(1, -1)
|
||||
}
|
||||
if (
|
||||
(value.startsWith('{') && value.endsWith('}')) ||
|
||||
(value.startsWith('[') && value.endsWith(']'))
|
||||
) {
|
||||
try {
|
||||
return { value: JSON.stringify(JSON.parse(value), null, 2), code: true }
|
||||
} catch {
|
||||
return { value, code: true }
|
||||
}
|
||||
}
|
||||
return { value, code: false }
|
||||
}
|
||||
|
||||
function parseFrontmatterFields(raw: string): FrontmatterField[] {
|
||||
const fields: FrontmatterField[] = []
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed || trimmed.startsWith('#')) continue
|
||||
const idx = trimmed.indexOf(':')
|
||||
if (idx <= 0) continue
|
||||
const key = trimmed.slice(0, idx).trim()
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(key)) continue
|
||||
const formatted = formatFrontmatterValue(trimmed.slice(idx + 1))
|
||||
fields.push({ key, ...formatted })
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
function splitMarkdownFrontmatter(text: string): { fields: FrontmatterField[]; body: string } {
|
||||
const src = text.replace(/^\uFEFF/, '')
|
||||
const match = src.match(/^(?:[ \t]*\r?\n)*---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/)
|
||||
if (!match) return { fields: [], body: src }
|
||||
return {
|
||||
fields: parseFrontmatterFields(match[1]),
|
||||
body: src.slice(match[0].length),
|
||||
}
|
||||
}
|
||||
|
||||
function renderMarkdown(text: string) {
|
||||
const { fields, body } = splitMarkdownFrontmatter(text)
|
||||
frontmatterFields.value = fields
|
||||
markdownHtml.value = body.trim()
|
||||
? renderChatMarkdown(body, {
|
||||
renderer: markdownRenderer,
|
||||
escapeMarkdown: safeMarkdownToHTML,
|
||||
sanitizeHtml: sanitizeMarkdownHTML,
|
||||
})
|
||||
: ''
|
||||
}
|
||||
|
||||
async function enhancePreview() {
|
||||
if (!showMarkdown.value || fileLoading.value || !markdownHtml.value) return
|
||||
await nextTick()
|
||||
await enhanceMarkdownContainer(markdownEl.value)
|
||||
}
|
||||
|
||||
async function selectFile(path: string) {
|
||||
if (!props.configId || !props.skillId) return
|
||||
selectedPath.value = path
|
||||
fileLoading.value = true
|
||||
fileError.value = ''
|
||||
file.value = null
|
||||
markdownHtml.value = ''
|
||||
highlightedHtml.value = ''
|
||||
frontmatterFields.value = []
|
||||
markdownMode.value = 'preview'
|
||||
try {
|
||||
const res = await getConfigSkillFile(props.configId, props.skillId, path)
|
||||
const data = res?.data
|
||||
file.value = data || null
|
||||
if (!data) {
|
||||
fileError.value = t('settings.sandbox.skillFilesFileLoadFailed')
|
||||
return
|
||||
}
|
||||
if (data.encoding === 'utf-8' && data.content != null) {
|
||||
highlightedHtml.value = highlightText(data.content, path)
|
||||
if (isMarkdown(path)) renderMarkdown(data.content)
|
||||
}
|
||||
} catch (e: any) {
|
||||
fileError.value = e?.message || t('settings.sandbox.skillFilesFileLoadFailed')
|
||||
} finally {
|
||||
fileLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copyContent() {
|
||||
const text = file.value?.content
|
||||
if (!text) return
|
||||
await copyWithToast(text, 'common.copied')
|
||||
}
|
||||
|
||||
async function loadFiles() {
|
||||
if (!props.configId || !props.skillId) return
|
||||
listLoading.value = true
|
||||
listError.value = ''
|
||||
nodes.value = []
|
||||
selectedPath.value = ''
|
||||
file.value = null
|
||||
fileError.value = ''
|
||||
try {
|
||||
const res = await listConfigSkillFiles(props.configId, props.skillId)
|
||||
const list = res?.data || []
|
||||
const tree = buildTree(list)
|
||||
nodes.value = tree
|
||||
const dirs = new Set<string>()
|
||||
collectDirs(tree, dirs)
|
||||
expandedDirs.value = dirs
|
||||
const initial = list.some((item) => item.path === 'SKILL.md') ? 'SKILL.md' : list[0]?.path
|
||||
if (initial) await selectFile(initial)
|
||||
} catch (e: any) {
|
||||
listError.value = e?.message || t('settings.sandbox.skillFilesLoadFailed')
|
||||
} finally {
|
||||
listLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.configId, props.skillId],
|
||||
() => {
|
||||
void loadFiles()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => [markdownHtml.value, markdownMode.value, fileLoading.value],
|
||||
() => {
|
||||
void enhancePreview()
|
||||
},
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@import '@/components/css/chat-markdown.less';
|
||||
|
||||
.skill-files-panel {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.skill-files-panel__nav {
|
||||
width: var(--skill-files-nav-width, 208px);
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
border-right: 1px solid var(--td-component-stroke);
|
||||
overflow: auto;
|
||||
padding: 8px 8px 12px;
|
||||
background: var(--td-bg-color-settings-modal);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--td-bg-color-component-disabled);
|
||||
border-radius: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-panel__list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.skill-files-panel__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
margin-bottom: 2px;
|
||||
padding: 6px 12px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
color: var(--td-text-color-primary);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
user-select: none;
|
||||
transition: background-color 0.2s ease, color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--td-bg-color-container-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
&.is-active {
|
||||
background-color: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-brand-color);
|
||||
font-weight: 500;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-panel__indent {
|
||||
flex-shrink: 0;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.skill-files-panel__icon {
|
||||
flex-shrink: 0;
|
||||
margin-right: 9px;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.skill-files-panel__name {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: inherit;
|
||||
line-height: 1.4;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.skill-files-panel__main {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.skill-files-panel__bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
min-height: 40px;
|
||||
padding: 0 12px 0 16px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
|
||||
.skill-files-panel__path {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.skill-files-panel__link {
|
||||
flex-shrink: 0;
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
font-size: 12px;
|
||||
line-height: 24px;
|
||||
color: var(--td-text-color-secondary);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-panel__view {
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 16px 20px 32px;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: var(--td-bg-color-component-disabled);
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-panel__hint {
|
||||
margin: 24px 8px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.skill-files-panel__warn {
|
||||
margin: 0 0 8px;
|
||||
font-size: 12px;
|
||||
color: var(--td-warning-color);
|
||||
}
|
||||
|
||||
.skill-files-panel__meta {
|
||||
margin: 0 0 20px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 8px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
}
|
||||
|
||||
.skill-files-panel__meta-row {
|
||||
display: grid;
|
||||
grid-template-columns: 108px minmax(0, 1fr);
|
||||
gap: 4px 12px;
|
||||
padding: 6px 0;
|
||||
|
||||
+ .skill-files-panel__meta-row {
|
||||
border-top: 1px solid var(--td-component-stroke);
|
||||
}
|
||||
|
||||
dt {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-primary);
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
|
||||
&.is-code {
|
||||
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.skill-files-panel__image {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.skill-files-panel__code {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
overflow: visible;
|
||||
font-family: var(--td-font-family-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: var(--td-text-color-primary);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.skill-files-panel__markdown {
|
||||
min-width: 0;
|
||||
.chat-markdown-typography();
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
.skill-files-split-handle {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 12px;
|
||||
z-index: 2602;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: col-resize;
|
||||
}
|
||||
|
||||
.skill-files-split-handle__line {
|
||||
width: 2px;
|
||||
height: 48px;
|
||||
border-radius: 1px;
|
||||
background: var(--td-component-border);
|
||||
opacity: 0.55;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
|
||||
.skill-files-split-handle:hover .skill-files-split-handle__line,
|
||||
.skill-files-split-handle--active .skill-files-split-handle__line {
|
||||
opacity: 1;
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -5163,6 +5163,16 @@ export default {
|
|||
skillTranscriptHide: '收起安装过程',
|
||||
skillTranscriptEmpty: '这次安装没有留下记录。',
|
||||
skillTranscriptWaiting: '安装已开始,正在等待过程记录…',
|
||||
skillFiles: '查看文件',
|
||||
skillFilesTitle: '文件',
|
||||
skillFilesEmpty: '该技能还没有可查看的文件。',
|
||||
skillFilesLoadFailed: '加载技能文件失败',
|
||||
skillFilesFileLoadFailed: '无法读取该文件',
|
||||
skillFilesBinary: '该文件是二进制内容,无法在线预览。',
|
||||
skillFilesTruncated: '文件较大,仅显示前一部分。',
|
||||
skillFilesSelectHint: '选择左侧文件以查看内容',
|
||||
skillFilesPreview: '预览',
|
||||
skillFilesSource: '源码',
|
||||
skillLoadFailed: '加载技能列表失败',
|
||||
skillToggleFailed: '更新技能状态失败',
|
||||
skillDeleteAccepted: '已开始删除技能',
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"},
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Reference in New Issue