feat(agent): preview skill artifacts and verify installs without running them (#2823)
* feat(agent): preview skill artifacts and verify installs without running them Generated files open in the chat drawer with overlay/Esc returning to the list, and install verification no longer executes guessed skill entry points. A failed install can be retried from the saved archive. * ui(chat): use a folder icon and corner count for skill artifacts The eye and document glyphs read as preview or copy, and TDesign's loading spinner sat beside the icon. A folder with a top-right count matches the generated-files drawer without covering the toolbar action. * feat(artifact): implement inline artifact references with previews Add support for inline artifact references in Markdown, allowing generated files to be displayed as clickable cards. Implemented a new rendering mechanism for artifacts, enabling previews directly from the chat interface. Updated localization files for new inline preview hints and missing file messages. Introduced tests for artifact reference normalization and rendering logic. * fix(client): document AgentResponseType constants for revive Touching the const block made golangci-lint require comments on every exported value. Match the rest of the SDK and describe artifacts_pending. * fix(agent): wrap artifact-reference prompt lines for lll Pre-push golangci-lint rejected the branch on three lines over 120 characters in the sandbox: reference guidance. * fix(agent): scope HTML scripts and tighten install verification Keep scripted HTML preview on skill artifacts only, recreate sandbox workspace dirs after they are deleted, and treat nested skill files as dependencies rather than first-party imports. * refactor(artifact): enhance artifact reference handling and metadata Updated artifact metadata to include a stable resource handle for better identification. Adjusted artifact reference resolution to support both handle and name forms, ensuring compatibility with existing references. Enhanced tests to validate the new handling logic and ensure proper rendering of artifacts in chat messages. Improved documentation for clarity on artifact reference formats and their usage in the system.main
parent
87d8e8a9b6
commit
270b64f6ec
|
|
@ -222,6 +222,7 @@ err = agentSession.Ask(context.Background(), "什么是深度学习?",
|
|||
| `AgentResponseTypeToolResult` | 工具执行结果 | 工具执行完成后 |
|
||||
| `AgentResponseTypeReferences` | 知识引用 | 检索到相关知识时 |
|
||||
| `AgentResponseTypeAnswer` | 最终答案 | Agent生成回答时(流式) |
|
||||
| `AgentResponseTypeArtifactsPending` | 生成文件上传中 | 回答结束后、文件写入对象存储完成前 |
|
||||
| `AgentResponseTypeReflection` | 自我反思 | Agent评估自己的回答时 |
|
||||
| `AgentResponseTypeError` | 错误 | 发生错误时 |
|
||||
|
||||
|
|
@ -400,6 +401,17 @@ if err != nil {
|
|||
_ = skillID // 用 skillID 订阅 /sandbox-configs/{id}/skills/{skillID}/install-events
|
||||
```
|
||||
|
||||
### 示例:重试失败的安装
|
||||
|
||||
安装失败的原因常与安装包无关(沙箱不可达、依赖源超时)。服务端保留着原始安装包,重试无需再传一次。
|
||||
|
||||
```go
|
||||
skillID, err := apiClient.ReinstallSandboxSkill(context.Background(), sandboxConfigID, skillID)
|
||||
if err != nil {
|
||||
// 处理错误
|
||||
}
|
||||
```
|
||||
|
||||
### 示例:查看已安装技能的文件
|
||||
|
||||
```go
|
||||
|
|
|
|||
|
|
@ -213,6 +213,19 @@ if err != nil {
|
|||
_ = skillID // follow /sandbox-configs/{id}/skills/{skillID}/install-events
|
||||
```
|
||||
|
||||
### Example: Retry a failed install
|
||||
|
||||
Installs usually fail for reasons the bundle cannot fix — an unreachable
|
||||
sandbox, a package index that timed out. The server still holds the archive,
|
||||
so the retry needs nothing from you.
|
||||
|
||||
```go
|
||||
skillID, err := apiClient.ReinstallSandboxSkill(context.Background(), sandboxConfigID, skillID)
|
||||
if err != nil {
|
||||
// Handle error
|
||||
}
|
||||
```
|
||||
|
||||
### Example: Browse files of an installed skill
|
||||
|
||||
```go
|
||||
|
|
|
|||
|
|
@ -43,14 +43,25 @@ type AgentQARequest struct {
|
|||
type AgentResponseType string
|
||||
|
||||
const (
|
||||
AgentResponseTypeThinking AgentResponseType = "thinking"
|
||||
AgentResponseTypeToolCall AgentResponseType = "tool_call"
|
||||
// AgentResponseTypeThinking is emitted while the agent is reasoning.
|
||||
AgentResponseTypeThinking AgentResponseType = "thinking"
|
||||
// AgentResponseTypeToolCall is emitted when the agent invokes a tool.
|
||||
AgentResponseTypeToolCall AgentResponseType = "tool_call"
|
||||
// AgentResponseTypeToolResult is emitted when a tool returns.
|
||||
AgentResponseTypeToolResult AgentResponseType = "tool_result"
|
||||
// AgentResponseTypeReferences is emitted with knowledge references.
|
||||
AgentResponseTypeReferences AgentResponseType = "references"
|
||||
AgentResponseTypeAnswer AgentResponseType = "answer"
|
||||
// AgentResponseTypeAnswer is emitted for answer tokens.
|
||||
AgentResponseTypeAnswer AgentResponseType = "answer"
|
||||
// AgentResponseTypeReflection is emitted for agent reflection.
|
||||
AgentResponseTypeReflection AgentResponseType = "reflection"
|
||||
AgentResponseTypeError AgentResponseType = "error"
|
||||
AgentResponseTypeComplete AgentResponseType = "complete"
|
||||
// AgentResponseTypeError is emitted when the agent fails.
|
||||
AgentResponseTypeError AgentResponseType = "error"
|
||||
// AgentResponseTypeComplete is emitted when the agent run has finished.
|
||||
AgentResponseTypeComplete AgentResponseType = "complete"
|
||||
// AgentResponseTypeArtifactsPending is emitted while skill-generated files
|
||||
// are still being collected after the answer has streamed.
|
||||
AgentResponseTypeArtifactsPending AgentResponseType = "artifacts_pending"
|
||||
)
|
||||
|
||||
// AgentStreamResponse agent streaming response
|
||||
|
|
|
|||
|
|
@ -119,6 +119,33 @@ func (c *Client) UploadSandboxSkill(
|
|||
return response.Data.SkillID, nil
|
||||
}
|
||||
|
||||
// ReinstallSandboxSkill runs the install of one skill again from the archive
|
||||
// the server already stores, so a failure that had nothing to do with the
|
||||
// bundle can be retried without re-uploading it. Like the install it is
|
||||
// accepted asynchronously. A skill already serving the current image is left
|
||||
// alone rather than rebuilt.
|
||||
func (c *Client) ReinstallSandboxSkill(
|
||||
ctx context.Context, configID, skillID string,
|
||||
) (string, error) {
|
||||
if configID == "" {
|
||||
return "", fmt.Errorf("sandbox config ID is required")
|
||||
}
|
||||
if skillID == "" {
|
||||
return "", fmt.Errorf("skill ID is required")
|
||||
}
|
||||
path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) +
|
||||
"/skills/" + url.PathEscape(skillID) + "/reinstall"
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, nil, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response SandboxSkillInstallResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return response.Data.SkillID, nil
|
||||
}
|
||||
|
||||
// SandboxSkillFile is one path in an installed skill's stored archive.
|
||||
type SandboxSkillFile struct {
|
||||
Path string `json:"path"`
|
||||
|
|
|
|||
|
|
@ -541,7 +541,7 @@ Docker 模式提供最强的隔离:
|
|||
|
||||
```bash
|
||||
# 方式一:直接拉取
|
||||
docker pull wechatopenai/weknora-sandbox:latest
|
||||
docker pull wechatopenai/weknora-sandbox:main
|
||||
|
||||
# 方式二:本地构建
|
||||
sh scripts/build_images.sh -s
|
||||
|
|
@ -549,6 +549,8 @@ sh scripts/build_images.sh -s
|
|||
|
||||
> 如果未预拉取,创建第一个沙箱时会先拉取镜像,首次执行需要等待下载完成;也可以在设置页的模板步骤提前触发拉取。
|
||||
|
||||
> 用 `main` 而非 `latest`:`latest` 只在发版时移动,目前仍停在 `/workspace` 及其 `input`/`output` 目录交给沙箱账号之前的版本,用它建出来的沙箱写不了自己的产物目录。发版带上该修复后即可换回 `latest`。
|
||||
|
||||
**镜像内置环境**:
|
||||
- Python 3.11 + pip(requests、pyyaml、pandas、beautifulsoup4)
|
||||
- Node.js 20 + npm
|
||||
|
|
@ -564,7 +566,7 @@ docker run --rm \
|
|||
--network=none \
|
||||
-v /path/to/skill:/skill:ro \
|
||||
-w /skill \
|
||||
wechatopenai/weknora-sandbox:latest \
|
||||
wechatopenai/weknora-sandbox:main \
|
||||
python scripts/analyze.py input.pdf
|
||||
```
|
||||
|
||||
|
|
|
|||
|
|
@ -165,6 +165,7 @@ curl --location 'http://localhost:8080/api/v1/agent-chat/ceb9babb-1e30-41d7-817d
|
|||
| `tool_result` | 工具调用结果 |
|
||||
| `references` | 知识库检索引用 |
|
||||
| `answer` | 最终回答内容 |
|
||||
| `artifacts_pending` | Skill/沙箱产物正在上传;`data.count` 为待保存文件数。回答可能已经 `done`,文件按钮会在此期间显示加载态,直至 `complete` 带上 `artifacts` |
|
||||
| `reflection` | Agent 反思内容 |
|
||||
| `session_title` | 自动生成的会话标题 |
|
||||
| `error` | 错误信息 |
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
| ---- | --------- | ------------------ |
|
||||
| GET | `/skills` | 获取预装 Skills 列表 |
|
||||
| POST | `/sandbox-configs/{id}/skills` | 安装技能(zip 上传或托管平台 source) |
|
||||
| POST | `/sandbox-configs/{id}/skills/{skillId}/reinstall` | 用已保存的安装包重试安装 |
|
||||
| GET | `/sandbox-configs/{id}/skills/{skillId}/files` | 列出已安装技能的文件 |
|
||||
| GET | `/sandbox-configs/{id}/skills/{skillId}/files/content` | 读取已安装技能中的单个文件 |
|
||||
|
||||
|
|
@ -103,6 +104,32 @@ curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \
|
|||
}
|
||||
```
|
||||
|
||||
## POST `/sandbox-configs/{id}/skills/{skillId}/reinstall` - 重试安装
|
||||
|
||||
用服务端已保存的安装包重新跑一遍安装,无需重新上传 zip 或重新提供 source。适用于安装失败的原因与安装包本身无关的情况:沙箱不可达、依赖源超时、安装过程被中断等。
|
||||
|
||||
与安装接口一样只负责受理,进度同样通过
|
||||
`GET /sandbox-configs/{id}/skills/{skillId}/install-events` 跟随。技能会复用同一个 `skill_id`,不会产生新记录。
|
||||
|
||||
已经在当前镜像中正常服务、且安装包未变的技能会被跳过,不会重复构建快照。若该技能的安装包已不在存储中,返回 400,此时只能重新上传。
|
||||
|
||||
```curl
|
||||
curl --location --request POST \
|
||||
'http://localhost:8080/api/v1/sandbox-configs/{id}/skills/{skillId}/reinstall' \
|
||||
--header 'X-API-Key: sk-xxxxx'
|
||||
```
|
||||
|
||||
**响应**(202):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"skill_id": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## GET `/sandbox-configs/{id}/skills/{skillId}/files` - 列出技能文件
|
||||
|
||||
返回该技能存档里的文件路径与大小。路径相对技能根目录(`SKILL.md` 所在目录),不启动沙箱。
|
||||
|
|
|
|||
64
docs/docs.go
64
docs/docs.go
|
|
@ -12093,6 +12093,70 @@ const docTemplate = `{
|
|||
}
|
||||
}
|
||||
},
|
||||
"/sandbox-configs/{id}/skills/{skillId}/reinstall": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
},
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Retry a failed install from the stored archive; does not re-upload.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"SandboxConfig"
|
||||
],
|
||||
"summary": "Retry a skill install",
|
||||
"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": {
|
||||
"202": {
|
||||
"description": "Reinstall accepted",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "The stored archive is gone",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Skill not found",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/sandbox-configs/{id}/skills/{skillId}/transcript": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ Cube 变体只发布 linux/amd64——envd 的来源镜像 `cubesandbox-base`
|
|||
|
||||
1. 按 [CubeSandbox Quick Start](https://github.com/TencentCloud/CubeSandbox/blob/master/docs/zh/guide/quickstart.md) 完成控制面、计算节点、CubeProxy 与域名解析。生产环境还需按官方文档完成鉴权、TLS、网络策略与多节点部署。
|
||||
2. 在 WeKnora 的空间设置中填写 CubeAPI、CubeProxy、sandbox domain 和可选 API Key。需要自定义 guest DNS 时填写「DNS 服务器」(须为 IP);留空则使用集群默认。若这些端点位于 RFC1918/loopback 网络,显式打开“允许访问私网集群地址”。
|
||||
3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并列出集群模板。**不会自动创建**。没有 WeKnora 标准模板时在占位卡片上点「创建」,会从 `wechatopenai/weknora-sandbox:latest-cube` 发起构建。改 DNS 或需要换镜像时在 weknora 卡片上点「重建」:优先对现有标准模板做 in-place rebuild(模板 ID 不变);只有 redo 被拒绝时才先建新模板、成功后再删旧的。已安装 Skill 的配置(以及同一集群上其它已装 Skill 的配置)不能重建。失败模板同样用「重建」(CubeMaster 拒绝 redo、错误码 130400 时尤其需要)。
|
||||
3. 点击“连接并继续”。WeKnora 先验证控制面地址与凭据,通过后才进入模板步骤并列出集群模板。**不会自动创建**。没有 WeKnora 标准模板时在占位卡片上点「创建」,会从 `wechatopenai/weknora-sandbox:main-cube` 发起构建。改 DNS 或需要换镜像时在 weknora 卡片上点「重建」:优先对现有标准模板做 in-place rebuild(模板 ID 不变);只有 redo 被拒绝时才先建新模板、成功后再删旧的。已安装 Skill 的配置(以及同一集群上其它已装 Skill 的配置)不能重建。失败模板同样用「重建」(CubeMaster 拒绝 redo、错误码 130400 时尤其需要)。
|
||||
4. 模板构建状态会自动刷新。状态变为 `READY` 后才可选择并进入运行配置;界面显示模板名称、状态和版本,配置内部才保存该集群自己的 `template_id`。
|
||||
|
||||
模板镜像必须提供 uid 1000 的 `user` 账号:WeKnora 以该账号执行脚本与文件操作。写权限只保证在 `/workspace/output` 与 `/workspace/input` 下。
|
||||
|
|
|
|||
|
|
@ -12086,6 +12086,70 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/sandbox-configs/{id}/skills/{skillId}/reinstall": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"Bearer": []
|
||||
},
|
||||
{
|
||||
"ApiKeyAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Retry a failed install from the stored archive; does not re-upload.",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"SandboxConfig"
|
||||
],
|
||||
"summary": "Retry a skill install",
|
||||
"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": {
|
||||
"202": {
|
||||
"description": "Reinstall accepted",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "The stored archive is gone",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Unauthorized",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Skill not found",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/sandbox-configs/{id}/skills/{skillId}/transcript": {
|
||||
"get": {
|
||||
"security": [
|
||||
|
|
|
|||
|
|
@ -698,7 +698,8 @@ definitions:
|
|||
cube_sandbox_ttl_seconds:
|
||||
type: integer
|
||||
dns_servers:
|
||||
description: DNSServers are Cube template nameserver IPs. Empty uses Cubelet's default.
|
||||
description: DNSServers are Cube template nameserver IPs. Empty uses Cubelet's
|
||||
default.
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
|
|
@ -3828,7 +3829,8 @@ definitions:
|
|||
place secrets here that scripts must not access."
|
||||
type: object
|
||||
sandbox_type:
|
||||
description: SandboxType is cube, e2b, or docker; disabled is the hidden policy row.
|
||||
description: SandboxType is cube, e2b, or docker; disabled is the hidden policy
|
||||
row.
|
||||
type: string
|
||||
skill_image:
|
||||
allOf:
|
||||
|
|
@ -13997,6 +13999,47 @@ paths:
|
|||
summary: Follow an install or removal
|
||||
tags:
|
||||
- SandboxConfig
|
||||
/sandbox-configs/{id}/skills/{skillId}/reinstall:
|
||||
post:
|
||||
description: Retry a failed install from the stored archive; does not re-upload.
|
||||
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:
|
||||
"202":
|
||||
description: Reinstall accepted
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"400":
|
||||
description: The stored archive is gone
|
||||
schema:
|
||||
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
|
||||
"401":
|
||||
description: Unauthorized
|
||||
schema:
|
||||
additionalProperties: true
|
||||
type: object
|
||||
"404":
|
||||
description: Skill not found
|
||||
schema:
|
||||
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
|
||||
security:
|
||||
- Bearer: []
|
||||
- ApiKeyAuth: []
|
||||
summary: Retry a skill install
|
||||
tags:
|
||||
- SandboxConfig
|
||||
/sandbox-configs/{id}/skills/{skillId}/transcript:
|
||||
get:
|
||||
description: |-
|
||||
|
|
|
|||
|
|
@ -84,14 +84,20 @@ export async function clearSessionMessages(session_id: string) {
|
|||
// ---------------------------------------------------------------------------
|
||||
// Skill artifacts (files generated by skill scripts during agent turns)
|
||||
//
|
||||
// The backend keeps the storage URL private and indexes each file by its
|
||||
// position (:index) in the owning assistant message. The list endpoints
|
||||
// The backend keeps the physical storage path private and indexes each file by
|
||||
// its position (:index) in the owning assistant message. The list endpoints
|
||||
// return metadata only — clients must go through downloadArtifact to fetch
|
||||
// the actual bytes so ownership checks always run server-side.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ArtifactMeta {
|
||||
index: number;
|
||||
/**
|
||||
* `resource://<handle>` — the artifact's stable identity, and the destination
|
||||
* the answer body references. Empty when the deployment runs without a
|
||||
* resource catalog, in which case the body references files by name.
|
||||
*/
|
||||
handle?: string;
|
||||
file_name: string;
|
||||
file_type: string;
|
||||
file_size: number;
|
||||
|
|
|
|||
|
|
@ -1056,6 +1056,19 @@ export function installConfigSkillFromSource(
|
|||
}) as unknown as Promise<{ data: { skill_id: string } }>
|
||||
}
|
||||
|
||||
// Retries an install from the archive the server already stores, so a failure
|
||||
// that had nothing to do with the bundle does not send the operator looking
|
||||
// for the original zip or registry URL.
|
||||
export function reinstallConfigSkill(
|
||||
configId: string,
|
||||
skillId: string,
|
||||
): Promise<{ data: { skill_id: string } }> {
|
||||
return post(
|
||||
`/api/v1/sandbox-configs/${configId}/skills/${skillId}/reinstall`,
|
||||
{},
|
||||
) as unknown as Promise<{ data: { skill_id: string } }>
|
||||
}
|
||||
|
||||
export function patchConfigSkill(
|
||||
configId: string,
|
||||
skillId: string,
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@
|
|||
</div>
|
||||
<t-form-item :label="requiredLabel('dockerImage')" :status="fieldStatus('image')"
|
||||
:tips="fieldTip('image')">
|
||||
<t-input v-model="docker.image" placeholder="wechatopenai/weknora-sandbox:latest"
|
||||
<t-input v-model="docker.image" :placeholder="defaultDockerImage"
|
||||
:disabled="retargetFrozen" @input="onFieldInput('image')" />
|
||||
<p v-if="retargetFrozen" class="section-help section-help--field">
|
||||
{{ hasSkillSnapshot
|
||||
|
|
@ -532,6 +532,11 @@ const { t } = useI18n()
|
|||
const secretPlaceholder = '***'
|
||||
const isMaskedSecret = (value?: string) => value === secretPlaceholder
|
||||
|
||||
// Mirrors DefaultDockerImage on the server, including why it tracks main
|
||||
// instead of latest: the latest tag still carries an image whose /workspace
|
||||
// the sandbox account cannot write.
|
||||
const defaultDockerImage = 'wechatopenai/weknora-sandbox:main'
|
||||
|
||||
const clusterGuideUrl = 'https://github.com/Tencent/WeKnora/blob/main/docs/sandbox-cluster.md'
|
||||
const e2bApiKeysUrl = 'https://e2b.dev/dashboard?tab=keys'
|
||||
|
||||
|
|
@ -771,7 +776,7 @@ function reset() {
|
|||
Object.assign(docker, cfg.docker || {})
|
||||
if (!Array.isArray(cube.dns_servers)) cube.dns_servers = []
|
||||
if (backend.value === 'docker' && !docker.image) {
|
||||
docker.image = 'wechatopenai/weknora-sandbox:latest'
|
||||
docker.image = defaultDockerImage
|
||||
}
|
||||
storedSecrets.cube = isMaskedSecret(cube.api_key)
|
||||
storedSecrets.e2b = isMaskedSecret(e2b.api_key)
|
||||
|
|
@ -802,7 +807,7 @@ function selectBackend(value: string) {
|
|||
if (backend.value === value) return
|
||||
backend.value = value
|
||||
if (value === 'docker' && !docker.image) {
|
||||
docker.image = 'wechatopenai/weknora-sandbox:latest'
|
||||
docker.image = defaultDockerImage
|
||||
}
|
||||
onBackendChange()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -133,11 +133,17 @@
|
|||
:class="{ 'skill-item--focused': focusedSkillId === skill.id }"
|
||||
>
|
||||
<div class="skill-status-ring" :title="statusLabel(skill)">
|
||||
<!-- The percentage is spelled out in the meta line below, so the
|
||||
ring only has to show proportion: its own label is two digits
|
||||
crammed into 16px. The default 6px stroke is most of the
|
||||
radius at this size, which reads as a blob rather than a ring. -->
|
||||
<t-progress
|
||||
v-if="isBusy(skill)"
|
||||
theme="circle"
|
||||
:percentage="progressOf(skill)"
|
||||
:size="16"
|
||||
:stroke-width="2"
|
||||
:label="false"
|
||||
/>
|
||||
<t-icon
|
||||
v-else-if="skill.status === 'failed'"
|
||||
|
|
@ -271,6 +277,21 @@
|
|||
</span>
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-tooltip
|
||||
v-if="skill.status === 'failed'"
|
||||
:content="$t('settings.sandbox.skillRetryHint')"
|
||||
placement="top"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="skill-item__icon-btn"
|
||||
:disabled="retryingId === skill.id"
|
||||
:aria-label="$t('settings.sandbox.skillRetry')"
|
||||
@click="retrySkill(skill)"
|
||||
>
|
||||
<t-icon name="refresh" size="16px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
<t-popconfirm
|
||||
theme="warning"
|
||||
:content="deleteHint"
|
||||
|
|
@ -308,7 +329,9 @@
|
|||
{{ isCopyExpanded(skill.id) ? $t('common.collapse') : $t('common.expand') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="failedError(skill)" class="skill-item__error">{{ failedError(skill) }}</p>
|
||||
<ul v-if="failedErrorLines(skill).length" class="skill-item__error">
|
||||
<li v-for="(line, i) in failedErrorLines(skill)" :key="i">{{ line }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
|
@ -344,6 +367,7 @@ import {
|
|||
updateSandboxConfigById,
|
||||
listConfigSkills,
|
||||
patchConfigSkill,
|
||||
reinstallConfigSkill,
|
||||
uploadConfigSkill,
|
||||
installConfigSkillFromSource,
|
||||
type ConfigSkill,
|
||||
|
|
@ -378,6 +402,7 @@ const skills = ref<ConfigSkill[]>([])
|
|||
const skillImage = ref<SandboxSkillImage | null>(null)
|
||||
const togglingId = ref('')
|
||||
const deletingId = ref('')
|
||||
const retryingId = 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('')
|
||||
|
|
@ -535,11 +560,33 @@ function progressLog(skill: ConfigSkill): string {
|
|||
return progressById.value[skill.id]?.log || ''
|
||||
}
|
||||
|
||||
// A re-run reuses the skill id, so the previous run's last event is still the
|
||||
// one cached here. Left in place it renders as this run's state: a retry would
|
||||
// open at 100% showing the failure it was started to fix, until the first new
|
||||
// event lands.
|
||||
function forgetProgress(skillId: string) {
|
||||
if (!(skillId in progressById.value)) return
|
||||
const next = { ...progressById.value }
|
||||
delete next[skillId]
|
||||
progressById.value = next
|
||||
}
|
||||
|
||||
function failedError(skill: ConfigSkill): string {
|
||||
if (skill.status !== 'failed') return ''
|
||||
return skill.error || progressLog(skill)
|
||||
}
|
||||
|
||||
// Script verification reports every problem it found rather than stopping at
|
||||
// the first, so one failure is often several lines. Run together they are
|
||||
// unreadable, and the list is what tells the operator whether this is one
|
||||
// missing package or a bundle that needs rebuilding.
|
||||
function failedErrorLines(skill: ConfigSkill): string[] {
|
||||
return failedError(skill)
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
function isCopyExpanded(skillId: string): boolean {
|
||||
return expandedCopyIds.value.has(skillId)
|
||||
}
|
||||
|
|
@ -783,6 +830,9 @@ async function uploadFile(file: File) {
|
|||
})
|
||||
MessagePlugin.success(t('settings.sandbox.skillUploadAccepted'))
|
||||
const skillId = res?.data?.skill_id
|
||||
// Re-uploading a skill by the same name reuses its row, so this may be a
|
||||
// second run of a skill already on screen.
|
||||
if (skillId) forgetProgress(skillId)
|
||||
await loadSkills()
|
||||
await refreshImage()
|
||||
if (skillId) {
|
||||
|
|
@ -813,6 +863,7 @@ async function installFromSource() {
|
|||
MessagePlugin.success(t('settings.sandbox.skillUploadAccepted'))
|
||||
sourceInput.value = ''
|
||||
const skillId = res?.data?.skill_id
|
||||
if (skillId) forgetProgress(skillId)
|
||||
await loadSkills()
|
||||
await refreshImage()
|
||||
if (skillId) {
|
||||
|
|
@ -855,6 +906,25 @@ async function toggleEnabled(skill: ConfigSkill, enabled: boolean) {
|
|||
}
|
||||
}
|
||||
|
||||
// The server still holds the archive, so a retry needs nothing from the
|
||||
// operator. It reuses the same row, which is why the progress follow can be
|
||||
// re-attached under the id already on screen.
|
||||
async function retrySkill(skill: ConfigSkill) {
|
||||
if (!props.record) return
|
||||
retryingId.value = skill.id
|
||||
forgetProgress(skill.id)
|
||||
try {
|
||||
await reinstallConfigSkill(props.record.id, skill.id)
|
||||
MessagePlugin.success(t('settings.sandbox.skillRetryAccepted'))
|
||||
await loadSkills()
|
||||
followProgress(skill.id)
|
||||
} catch (e: any) {
|
||||
MessagePlugin.error(e?.message || t('settings.sandbox.skillRetryFailed'))
|
||||
} finally {
|
||||
retryingId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function removeSkill(skill: ConfigSkill) {
|
||||
if (!props.record) return
|
||||
deletingId.value = skill.id
|
||||
|
|
@ -1116,12 +1186,18 @@ onUnmounted(() => {
|
|||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
:deep(.t-progress),
|
||||
:deep(.t-icon) {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
/* The ring is already sized to 16px by the component. The svg is inline by
|
||||
default, so without this it sits on a text baseline and pushes the ring
|
||||
a few pixels below the icon the other two states draw. */
|
||||
:deep(.t-progress--circle svg) {
|
||||
display: block;
|
||||
}
|
||||
|
||||
&__ready {
|
||||
color: var(--td-success-color);
|
||||
}
|
||||
|
|
@ -1166,9 +1242,27 @@ onUnmounted(() => {
|
|||
.skill-item__desc,
|
||||
.skill-item__error {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* Verification reports every problem it found, so a failure is often several
|
||||
lines. They are bulleted only when there is more than one: a lone problem
|
||||
reads as a sentence, not as a one-item list. */
|
||||
.skill-item__error li:not(:only-child) {
|
||||
padding-left: 10px;
|
||||
text-indent: -10px;
|
||||
}
|
||||
|
||||
.skill-item__error li:not(:only-child)::before {
|
||||
content: '· ';
|
||||
}
|
||||
|
||||
.skill-item__error li + li {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.skill-item__copy {
|
||||
|
|
|
|||
|
|
@ -635,5 +635,86 @@
|
|||
margin: 0;
|
||||
}
|
||||
|
||||
// A sandbox-generated file that is not an image (HTML chart, CSV, document)
|
||||
// is referenced inline as a card instead of being embedded: the artifacts are
|
||||
// self-contained pages up to a megabyte, and an iframe per reference would be
|
||||
// both slow and an active-content risk. Clicking opens the artifact drawer's
|
||||
// sandboxed preview. It must stay inline — Markdown wraps the reference in a
|
||||
// paragraph, and a block element would be hoisted out of it by the parser.
|
||||
:deep(.artifact-ref-card) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
max-width: min(420px, 100%);
|
||||
margin: 0.75em 0;
|
||||
padding: 8px 14px 8px 10px;
|
||||
border: 1px solid var(--td-component-stroke);
|
||||
border-radius: 10px;
|
||||
background: var(--td-bg-color-container);
|
||||
cursor: pointer;
|
||||
vertical-align: middle;
|
||||
text-align: left;
|
||||
transition: border-color 0.15s ease, background 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--td-brand-color);
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--td-brand-color);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card--pending) {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--td-component-stroke);
|
||||
background: var(--td-bg-color-container);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card__icon) {
|
||||
flex-shrink: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card__glyph) {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card__text) {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card__name) {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
color: var(--td-text-color-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
:deep(.artifact-ref-card__hint) {
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.chat-markdown-hljs();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,18 +89,35 @@
|
|||
}
|
||||
}
|
||||
|
||||
/* Count sits on the download glyph like the settings list badges: muted
|
||||
surface + secondary type, not TDesign's brand-pink t-badge. */
|
||||
.answer-toolbar__artifact {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.answer-toolbar__artifact.is-collecting .t-button {
|
||||
color: var(--td-text-color-placeholder);
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.answer-toolbar__artifact-spinner {
|
||||
animation: answer-toolbar-artifact-spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes answer-toolbar-artifact-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.answer-toolbar__artifact-count {
|
||||
position: absolute;
|
||||
top: 1px;
|
||||
right: 1px;
|
||||
top: -2px;
|
||||
right: -2px;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
|
@ -115,6 +132,7 @@
|
|||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { useAuthStore } from '@/stores/auth';
|
|||
import DocumentPreview from '@/components/document-preview.vue';
|
||||
import KnowledgeProcessingTimeline from '@/components/knowledge-processing-timeline.vue';
|
||||
import { resolveKnowledgeDownloadFileName } from '@/views/knowledge/knowledgeDownloadFileName';
|
||||
import { isKnownPreviewableExt, resolveFilePreviewExt } from '@/utils/filePreview';
|
||||
|
||||
const { t } = useI18n();
|
||||
const authStore = useAuthStore();
|
||||
|
|
@ -739,22 +740,12 @@ const processedChunks = computed(() => {
|
|||
});
|
||||
});
|
||||
|
||||
const previewSupportedTypes = new Set([
|
||||
'pdf', 'docx', 'pptx', 'ppt', 'xlsx', 'xls', 'csv',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'svg',
|
||||
'txt', 'md', 'markdown', 'json', 'xml', 'html', 'css', 'js', 'ts',
|
||||
'py', 'java', 'go', 'cpp', 'c', 'h', 'sh', 'yaml', 'yml',
|
||||
'ini', 'conf', 'log', 'sql', 'rs', 'rb', 'php', 'swift', 'kt',
|
||||
'scala', 'r', 'lua', 'pl', 'toml',
|
||||
'mp3', 'wav', 'm4a', 'flac', 'ogg',
|
||||
]);
|
||||
|
||||
const canPreview = (): boolean => {
|
||||
if (props.details?.type !== 'file') return false;
|
||||
const ft = props.details?.file_type?.toLowerCase();
|
||||
const ft = resolveFilePreviewExt(props.details?.title, props.details?.file_type);
|
||||
if (!ft) return false;
|
||||
if (audioExtensions.has(ft)) return false; // 音频不走预览tab,播放器已内嵌
|
||||
return previewSupportedTypes.has(ft);
|
||||
return isKnownPreviewableExt(ft);
|
||||
};
|
||||
|
||||
// 当文档详情加载完成时,file 类型自动切换到「预览」;音频类型使用 merged + 播放器
|
||||
|
|
|
|||
|
|
@ -3,13 +3,27 @@
|
|||
import { ref, shallowRef, watch, onUnmounted, nextTick, defineAsyncComponent } from 'vue';
|
||||
import { previewKnowledgeFile } from '@/api/knowledge-base/index';
|
||||
import { previewTemporaryAttachment } from '@/api/chat/temporary-attachments';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import { downloadArtifact } from '@/api/chat';
|
||||
import hljs from 'highlight.js';
|
||||
import 'highlight.js/styles/github.css';
|
||||
import markedKatex from 'marked-katex-extension';
|
||||
import 'katex/dist/katex.min.css';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { sanitizeHTML, safeMarkdownToHTML } from '@/utils/security';
|
||||
import { sanitizeHTML, sanitizeMarkdownHTML, safeMarkdownToHTML } from '@/utils/security';
|
||||
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
|
||||
import { renderMermaidToSvg } from '@/utils/mermaidShared';
|
||||
import {
|
||||
FILE_PREVIEW_SNIFF_BYTES,
|
||||
getHighlightLang as resolveHighlightLang,
|
||||
getPreviewMimeType,
|
||||
prettyPrintJson,
|
||||
resolveFilePreviewExt,
|
||||
resolvePreviewKind,
|
||||
shouldPrettyPrintJson,
|
||||
sniffPreview,
|
||||
isValidUTF8,
|
||||
type FilePreviewKind,
|
||||
} from '@/utils/filePreview';
|
||||
|
||||
|
||||
const VueOfficePptx = defineAsyncComponent(() => import('@vue-office/pptx'));
|
||||
|
|
@ -20,6 +34,8 @@ const props = defineProps<{
|
|||
knowledgeId?: string;
|
||||
sessionId?: string;
|
||||
attachmentId?: string;
|
||||
messageId?: string;
|
||||
artifactIndex?: number;
|
||||
fileType: string;
|
||||
fileName: string;
|
||||
active: boolean;
|
||||
|
|
@ -28,12 +44,14 @@ const props = defineProps<{
|
|||
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const previewType = ref<'pdf' | 'docx' | 'image' | 'excel' | 'text' | 'markdown' | 'pptx' | 'audio' | 'unsupported'>('unsupported');
|
||||
const previewType = ref<FilePreviewKind>('unsupported');
|
||||
const blobUrl = ref('');
|
||||
const textContent = ref('');
|
||||
const highlightedCode = ref('');
|
||||
const markdownHtml = ref('');
|
||||
const excelHtml = ref('');
|
||||
const mermaidSvg = ref('');
|
||||
const htmlViewMode = ref<'render' | 'source'>('render');
|
||||
const pptxData = shallowRef<ArrayBuffer | null>(null);
|
||||
const docxContainer = ref<HTMLElement | null>(null);
|
||||
const imageNaturalWidth = ref(0);
|
||||
|
|
@ -52,62 +70,14 @@ function toggleFullscreen() {
|
|||
}
|
||||
|
||||
|
||||
const fileTypeMap: Record<string, typeof previewType.value> = {};
|
||||
['pdf'].forEach(t => fileTypeMap[t] = 'pdf');
|
||||
['docx'].forEach(t => fileTypeMap[t] = 'docx');
|
||||
['pptx', 'ppt'].forEach(t => fileTypeMap[t] = 'pptx');
|
||||
['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'svg'].forEach(t => fileTypeMap[t] = 'image');
|
||||
['xlsx', 'xls', 'csv'].forEach(t => fileTypeMap[t] = 'excel');
|
||||
['md', 'markdown'].forEach(t => fileTypeMap[t] = 'markdown');
|
||||
['txt', 'json', 'xml', 'html', 'css', 'js', 'ts', 'py', 'java', 'go',
|
||||
'cpp', 'c', 'h', 'sh', 'yaml', 'yml', 'ini', 'conf', 'log', 'sql', 'rs', 'rb', 'php',
|
||||
'swift', 'kt', 'scala', 'r', 'lua', 'pl', 'toml'].forEach(t => fileTypeMap[t] = 'text');
|
||||
['mp3', 'wav', 'm4a', 'flac', 'ogg'].forEach(t => fileTypeMap[t] = 'audio');
|
||||
|
||||
const mimeTypeMap: Record<string, string> = {
|
||||
pdf: 'application/pdf',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
doc: 'application/msword',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
csv: 'text/csv',
|
||||
jpg: 'image/jpeg', jpeg: 'image/jpeg',
|
||||
png: 'image/png', gif: 'image/gif', bmp: 'image/bmp',
|
||||
webp: 'image/webp', tiff: 'image/tiff', svg: 'image/svg+xml',
|
||||
txt: 'text/plain', md: 'text/markdown', markdown: 'text/markdown',
|
||||
json: 'application/json', xml: 'application/xml',
|
||||
html: 'text/html', css: 'text/css',
|
||||
js: 'text/javascript', ts: 'text/typescript',
|
||||
py: 'text/x-python', java: 'text/x-java', go: 'text/x-go',
|
||||
mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4',
|
||||
flac: 'audio/flac', ogg: 'audio/ogg',
|
||||
};
|
||||
|
||||
function getMimeType(ft: string): string {
|
||||
return mimeTypeMap[ft?.toLowerCase()] || 'application/octet-stream';
|
||||
}
|
||||
|
||||
function ensureBlobType(blob: Blob, ft: string): Blob {
|
||||
const expected = getMimeType(ft);
|
||||
const expected = getPreviewMimeType(ft);
|
||||
if (blob.type === expected) return blob;
|
||||
return new Blob([blob], { type: expected });
|
||||
}
|
||||
|
||||
const langMap: Record<string, string> = {
|
||||
js: 'javascript', ts: 'typescript', py: 'python', rb: 'ruby',
|
||||
sh: 'bash', yml: 'yaml', md: 'markdown', rs: 'rust',
|
||||
kt: 'kotlin', pl: 'perl', conf: 'ini', log: 'plaintext',
|
||||
};
|
||||
|
||||
function resolvePreviewType(ft: string): typeof previewType.value {
|
||||
return fileTypeMap[ft?.toLowerCase()] || 'unsupported';
|
||||
}
|
||||
|
||||
function getHighlightLang(ft: string): string {
|
||||
const lower = ft?.toLowerCase() || '';
|
||||
return langMap[lower] || lower;
|
||||
return resolveHighlightLang(ft);
|
||||
}
|
||||
|
||||
const preprocessMathDelimiters = (rawText: string): string => {
|
||||
|
|
@ -138,24 +108,6 @@ async function renderDocx(blob: Blob) {
|
|||
}
|
||||
}
|
||||
|
||||
function isValidUTF8(bytes: Uint8Array): boolean {
|
||||
for (let i = 0; i < bytes.length;) {
|
||||
const b = bytes[i];
|
||||
let remaining = 0;
|
||||
if (b <= 0x7F) { remaining = 0; }
|
||||
else if ((b & 0xE0) === 0xC0) { remaining = 1; }
|
||||
else if ((b & 0xF0) === 0xE0) { remaining = 2; }
|
||||
else if ((b & 0xF8) === 0xF0) { remaining = 3; }
|
||||
else { return false; }
|
||||
if (i + remaining >= bytes.length) return false;
|
||||
for (let j = 1; j <= remaining; j++) {
|
||||
if ((bytes[i + j] & 0xC0) !== 0x80) return false;
|
||||
}
|
||||
i += 1 + remaining;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function decodeCSVBlob(arrayBuffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
if (bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) {
|
||||
|
|
@ -172,9 +124,13 @@ async function renderExcel(blob: Blob, fileType?: string) {
|
|||
const arrayBuffer = await blob.arrayBuffer();
|
||||
|
||||
let workbook;
|
||||
if (fileType?.toLowerCase() === 'csv') {
|
||||
const lowerType = fileType?.toLowerCase();
|
||||
if (lowerType === 'csv') {
|
||||
const csvText = decodeCSVBlob(arrayBuffer);
|
||||
workbook = XLSX.read(csvText, { type: 'string' });
|
||||
} else if (lowerType === 'tsv' || lowerType === 'tab') {
|
||||
const tsvText = decodeCSVBlob(arrayBuffer);
|
||||
workbook = XLSX.read(tsvText, { type: 'string', FS: '\t' });
|
||||
} else {
|
||||
workbook = XLSX.read(arrayBuffer, { type: 'array' });
|
||||
}
|
||||
|
|
@ -194,7 +150,10 @@ async function renderExcel(blob: Blob, fileType?: string) {
|
|||
}
|
||||
|
||||
async function renderText(blob: Blob, fileType: string) {
|
||||
const text = await blob.text();
|
||||
let text = await blob.text();
|
||||
if (shouldPrettyPrintJson(fileType)) {
|
||||
text = prettyPrintJson(text);
|
||||
}
|
||||
textContent.value = text;
|
||||
|
||||
const lang = getHighlightLang(fileType);
|
||||
|
|
@ -256,9 +215,24 @@ function onImageLoad(e: Event) {
|
|||
function getPreviewSourceKey(): string {
|
||||
if (props.knowledgeId) return `knowledge:${props.knowledgeId}`;
|
||||
if (props.sessionId && props.attachmentId) return `attachment:${props.sessionId}:${props.attachmentId}`;
|
||||
if (
|
||||
props.sessionId &&
|
||||
props.messageId &&
|
||||
Number.isInteger(props.artifactIndex) &&
|
||||
(props.artifactIndex as number) >= 0
|
||||
) {
|
||||
return `artifact:${props.sessionId}:${props.messageId}:${props.artifactIndex}`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// Skill-generated HTML is often a self-contained chart that needs its own
|
||||
// scripts. Knowledge-base files and chat attachments are untrusted uploads:
|
||||
// they stay as source, matching the previous text preview.
|
||||
function allowsHtmlScriptPreview(): boolean {
|
||||
return getPreviewSourceKey().startsWith('artifact:');
|
||||
}
|
||||
|
||||
async function fetchPreviewBlob(): Promise<Blob> {
|
||||
if (props.knowledgeId) {
|
||||
return previewKnowledgeFile(props.knowledgeId);
|
||||
|
|
@ -266,40 +240,80 @@ async function fetchPreviewBlob(): Promise<Blob> {
|
|||
if (props.sessionId && props.attachmentId) {
|
||||
return previewTemporaryAttachment(props.sessionId, props.attachmentId);
|
||||
}
|
||||
if (
|
||||
props.sessionId &&
|
||||
props.messageId &&
|
||||
Number.isInteger(props.artifactIndex) &&
|
||||
(props.artifactIndex as number) >= 0
|
||||
) {
|
||||
return downloadArtifact(props.sessionId, props.messageId, props.artifactIndex as number);
|
||||
}
|
||||
throw new Error('Missing preview source');
|
||||
}
|
||||
|
||||
async function renderMermaid(blob: Blob) {
|
||||
const text = await blob.text();
|
||||
const svg = await renderMermaidToSvg(text, `file-preview-mermaid-${Date.now()}`);
|
||||
if (svg) {
|
||||
mermaidSvg.value = sanitizeMarkdownHTML(svg);
|
||||
return;
|
||||
}
|
||||
previewType.value = 'text';
|
||||
await renderText(new Blob([text], { type: 'text/plain' }), 'mmd');
|
||||
}
|
||||
|
||||
function openMermaid() {
|
||||
if (mermaidSvg.value) openMermaidFullscreen(mermaidSvg.value);
|
||||
}
|
||||
|
||||
async function loadPreview() {
|
||||
const sourceKey = getPreviewSourceKey();
|
||||
const ft = props.fileType;
|
||||
if (!sourceKey || !ft) return;
|
||||
if (!sourceKey) return;
|
||||
if (loadedForId === sourceKey) return;
|
||||
|
||||
cleanup();
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
previewType.value = resolvePreviewType(ft);
|
||||
htmlViewMode.value = allowsHtmlScriptPreview() ? 'render' : 'source';
|
||||
|
||||
if (previewType.value === 'unsupported') {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
let ft = resolveFilePreviewExt(props.fileName, props.fileType);
|
||||
previewType.value = resolvePreviewKind(ft);
|
||||
|
||||
try {
|
||||
const rawBlob = await fetchPreviewBlob();
|
||||
let kind = resolvePreviewKind(ft);
|
||||
if (kind === 'unsupported') {
|
||||
const sample = new Uint8Array(await rawBlob.slice(0, FILE_PREVIEW_SNIFF_BYTES).arrayBuffer());
|
||||
const sniffed = sniffPreview(sample);
|
||||
kind = sniffed.kind;
|
||||
if (sniffed.ext) ft = sniffed.ext;
|
||||
}
|
||||
previewType.value = kind;
|
||||
|
||||
if (kind === 'unsupported') {
|
||||
loading.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = ensureBlobType(rawBlob, ft);
|
||||
loadedForId = sourceKey;
|
||||
|
||||
loading.value = false;
|
||||
await nextTick();
|
||||
|
||||
switch (previewType.value) {
|
||||
case 'pdf': {
|
||||
switch (kind) {
|
||||
case 'pdf':
|
||||
case 'image':
|
||||
case 'audio':
|
||||
case 'video': {
|
||||
blobUrl.value = URL.createObjectURL(blob);
|
||||
break;
|
||||
}
|
||||
case 'image': {
|
||||
blobUrl.value = URL.createObjectURL(blob);
|
||||
case 'html': {
|
||||
if (allowsHtmlScriptPreview()) {
|
||||
blobUrl.value = URL.createObjectURL(blob);
|
||||
}
|
||||
await renderText(blob, ft || 'html');
|
||||
break;
|
||||
}
|
||||
case 'docx': {
|
||||
|
|
@ -322,8 +336,8 @@ async function loadPreview() {
|
|||
pptxData.value = await blob.arrayBuffer();
|
||||
break;
|
||||
}
|
||||
case 'audio': {
|
||||
blobUrl.value = URL.createObjectURL(blob);
|
||||
case 'mermaid': {
|
||||
await renderMermaid(blob);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -344,6 +358,8 @@ function cleanup() {
|
|||
highlightedCode.value = '';
|
||||
markdownHtml.value = '';
|
||||
excelHtml.value = '';
|
||||
mermaidSvg.value = '';
|
||||
htmlViewMode.value = 'render';
|
||||
pptxData.value = null;
|
||||
imageNaturalWidth.value = 0;
|
||||
imageNaturalHeight.value = 0;
|
||||
|
|
@ -354,7 +370,7 @@ function cleanup() {
|
|||
}
|
||||
|
||||
watch(
|
||||
() => [props.active, props.knowledgeId, props.sessionId, props.attachmentId],
|
||||
() => [props.active, props.knowledgeId, props.sessionId, props.attachmentId, props.messageId, props.artifactIndex],
|
||||
([active]) => {
|
||||
if (active && getPreviewSourceKey()) {
|
||||
loadPreview();
|
||||
|
|
@ -374,6 +390,15 @@ onUnmounted(() => {
|
|||
<!-- Toolbar -->
|
||||
<div class="preview-toolbar" v-if="!loading && !error && previewType !== 'unsupported'">
|
||||
<t-space size="small">
|
||||
<t-tooltip
|
||||
v-if="previewType === 'html' && allowsHtmlScriptPreview()"
|
||||
:content="htmlViewMode === 'render' ? $t('preview.htmlSource') : $t('preview.htmlRendered')"
|
||||
placement="bottom"
|
||||
>
|
||||
<t-button theme="default" variant="text" shape="square" @click="htmlViewMode = htmlViewMode === 'render' ? 'source' : 'render'">
|
||||
<template #icon><t-icon :name="htmlViewMode === 'render' ? 'code' : 'browse'" /></template>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
<t-tooltip :content="isFullscreen ? $t('preview.exitFullscreen') : $t('preview.fullscreen')" placement="bottom">
|
||||
<t-button theme="default" variant="text" shape="square" @click="toggleFullscreen">
|
||||
<template #icon><t-icon :name="isFullscreen ? 'fullscreen-exit' : 'fullscreen'" /></template>
|
||||
|
|
@ -409,6 +434,18 @@ onUnmounted(() => {
|
|||
<iframe :src="blobUrl" class="pdf-iframe" />
|
||||
</div>
|
||||
|
||||
<!-- HTML: artifacts render in a unique-origin iframe; other sources stay as source. -->
|
||||
<div v-else-if="previewType === 'html'" class="preview-html">
|
||||
<iframe
|
||||
v-if="allowsHtmlScriptPreview() && htmlViewMode === 'render' && blobUrl"
|
||||
:src="blobUrl"
|
||||
class="html-iframe"
|
||||
sandbox="allow-scripts"
|
||||
referrerpolicy="no-referrer"
|
||||
/>
|
||||
<pre v-show="!allowsHtmlScriptPreview() || htmlViewMode === 'source'" class="code-preview"><code class="hljs" v-html="highlightedCode"></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Image -->
|
||||
<div v-else-if="previewType === 'image' && blobUrl" class="preview-image">
|
||||
<div class="image-wrapper">
|
||||
|
|
@ -444,6 +481,11 @@ onUnmounted(() => {
|
|||
<pre class="code-preview"><code class="hljs" v-html="highlightedCode"></code></pre>
|
||||
</div>
|
||||
|
||||
<!-- Mermaid -->
|
||||
<div v-else-if="previewType === 'mermaid' && mermaidSvg" class="preview-mermaid" @click="openMermaid">
|
||||
<div class="mermaid-body" v-html="mermaidSvg" />
|
||||
</div>
|
||||
|
||||
<!-- Audio -->
|
||||
<div v-else-if="previewType === 'audio' && blobUrl" class="preview-audio">
|
||||
<div class="audio-wrapper">
|
||||
|
|
@ -454,6 +496,13 @@ onUnmounted(() => {
|
|||
</audio>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Video -->
|
||||
<div v-else-if="previewType === 'video' && blobUrl" class="preview-video">
|
||||
<video controls playsinline :src="blobUrl" class="video-element">
|
||||
{{ $t('preview.videoNotSupported') }}
|
||||
</video>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
|
@ -509,7 +558,10 @@ onUnmounted(() => {
|
|||
.preview-excel,
|
||||
.preview-markdown,
|
||||
.preview-text,
|
||||
.preview-html,
|
||||
.preview-mermaid,
|
||||
.preview-audio,
|
||||
.preview-video,
|
||||
.preview-loading,
|
||||
.preview-error,
|
||||
.preview-unsupported {
|
||||
|
|
@ -545,9 +597,19 @@ onUnmounted(() => {
|
|||
|
||||
.preview-excel .excel-container,
|
||||
.preview-markdown,
|
||||
.preview-text .code-preview {
|
||||
.preview-text .code-preview,
|
||||
.preview-html .code-preview {
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
.preview-html .html-iframe {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.preview-html {
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -613,9 +675,16 @@ onUnmounted(() => {
|
|||
|
||||
.preview-excel .excel-container,
|
||||
.preview-markdown,
|
||||
.preview-text .code-preview {
|
||||
.preview-text .code-preview,
|
||||
.preview-html .code-preview {
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.preview-html,
|
||||
.preview-video,
|
||||
.preview-mermaid {
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.preview-toolbar {
|
||||
|
|
@ -683,6 +752,55 @@ onUnmounted(() => {
|
|||
}
|
||||
}
|
||||
|
||||
// ── HTML ──
|
||||
.preview-html {
|
||||
width: 100%;
|
||||
height: @preview-max-h;
|
||||
min-height: 420px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
.html-iframe {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
border: 1px solid @border-color;
|
||||
border-radius: @border-radius;
|
||||
background: @bg-white;
|
||||
}
|
||||
.code-preview {
|
||||
.preview-container();
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
background: @bg-subtle;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
code {
|
||||
white-space: pre;
|
||||
word-wrap: normal;
|
||||
display: block;
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mermaid ──
|
||||
.preview-mermaid {
|
||||
.preview-container();
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 24px 16px;
|
||||
cursor: zoom-in;
|
||||
.mermaid-body {
|
||||
max-width: 100%;
|
||||
:deep(svg) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Image ──
|
||||
.preview-image {
|
||||
display: flex;
|
||||
|
|
@ -769,6 +887,21 @@ onUnmounted(() => {
|
|||
}
|
||||
}
|
||||
|
||||
// ── Video ──
|
||||
.preview-video {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 16px;
|
||||
min-height: 280px;
|
||||
.video-element {
|
||||
width: 100%;
|
||||
max-height: calc(100vh - 240px);
|
||||
border-radius: @border-radius;
|
||||
background: #000;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Deep styles (v-html / third-party components) ──
|
||||
|
||||
// Shared table mixin for v-html content
|
||||
|
|
|
|||
|
|
@ -836,6 +836,14 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
}
|
||||
break
|
||||
}
|
||||
case 'artifacts_pending': {
|
||||
const pendingCount = Number((dataPayload as any)?.count)
|
||||
message.artifactsCollecting = true
|
||||
if (Number.isFinite(pendingCount) && pendingCount > 0) {
|
||||
message.artifactsPendingCount = pendingCount
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'complete': {
|
||||
log('[Agent] Complete event received')
|
||||
loading.value = false
|
||||
|
|
@ -855,6 +863,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
if (Array.isArray(streamedArtifacts) && streamedArtifacts.length) {
|
||||
message.artifacts = streamedArtifacts
|
||||
}
|
||||
message.artifactsCollecting = false
|
||||
if (message.agentEventStream) {
|
||||
;(message.agentEventStream as ChatMessage[]).push({
|
||||
type: 'agent_complete',
|
||||
|
|
@ -877,6 +886,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
isReplying.value = false
|
||||
fullContent.value = ''
|
||||
currentAssistantMessageId.value = ''
|
||||
message.artifactsCollecting = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
|
@ -958,7 +968,8 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
data.response_type === 'thinking' ||
|
||||
data.response_type === 'tool_call' ||
|
||||
data.response_type === 'tool_result' ||
|
||||
data.response_type === 'reflection'
|
||||
data.response_type === 'reflection' ||
|
||||
data.response_type === 'artifacts_pending'
|
||||
|
||||
const lastMessage = messagesList[messagesList.length - 1]
|
||||
const isCurrentlyAgentMode = lastMessage?.isAgentMode === true
|
||||
|
|
|
|||
|
|
@ -804,11 +804,16 @@ export default {
|
|||
copy: 'Copy',
|
||||
addToKnowledgeBase: 'Add to Knowledge Base',
|
||||
artifactDrawer: {
|
||||
buttonTitle: 'Download files generated in this reply',
|
||||
buttonTitle: 'View files generated in this reply',
|
||||
title: 'Generated files',
|
||||
empty: 'No downloadable files were generated this turn.',
|
||||
preview: 'Preview',
|
||||
previewBack: 'Back to list',
|
||||
collecting: 'Saving generated files…',
|
||||
download: 'Download',
|
||||
downloadFailed: 'Download failed, please retry.',
|
||||
inlinePreviewHint: 'Click to preview',
|
||||
inlineMissing: 'File unavailable',
|
||||
},
|
||||
updatePlan: 'Update Plan',
|
||||
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
|
||||
|
|
@ -1346,6 +1351,10 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillRetry: 'Reinstall',
|
||||
skillRetryHint: 'Retry with the stored bundle; no re-upload needed',
|
||||
skillRetryAccepted: 'Reinstall started',
|
||||
skillRetryFailed: 'Failed to start the reinstall',
|
||||
skillEmpty: 'No skills installed yet. Paste a registry URL, or upload a zip.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
|
|
@ -4981,8 +4990,11 @@ export default {
|
|||
unsupportedHint: 'Please download and open with a local application',
|
||||
fullscreen: 'Fullscreen',
|
||||
exitFullscreen: 'Exit Fullscreen',
|
||||
htmlRendered: 'Rendered preview',
|
||||
htmlSource: 'View source',
|
||||
audioLoading: 'Loading audio…',
|
||||
audioNotSupported: 'Your browser does not support audio playback'
|
||||
audioNotSupported: 'Your browser does not support audio playback',
|
||||
videoNotSupported: 'Your browser does not support video playback'
|
||||
},
|
||||
commandPalette: {
|
||||
placeholder: 'Search knowledge bases, files, conversations…',
|
||||
|
|
|
|||
|
|
@ -1519,8 +1519,11 @@ export default {
|
|||
unsupportedHint: '파일을 다운로드하여 로컬 앱으로 열어주세요',
|
||||
fullscreen: '전체 화면',
|
||||
exitFullscreen: '전체 화면 종료',
|
||||
htmlRendered: '렌더링 미리보기',
|
||||
htmlSource: '원본 보기',
|
||||
audioLoading: '오디오 로딩 중…',
|
||||
audioNotSupported: '브라우저가 오디오 재생을 지원하지 않습니다'
|
||||
audioNotSupported: '브라우저가 오디오 재생을 지원하지 않습니다',
|
||||
videoNotSupported: '브라우저가 동영상 재생을 지원하지 않습니다'
|
||||
},
|
||||
organization: {
|
||||
title: '공유 공간',
|
||||
|
|
@ -5200,6 +5203,10 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillRetry: '다시 설치',
|
||||
skillRetryHint: '저장된 번들로 재시도합니다. 다시 업로드할 필요가 없습니다',
|
||||
skillRetryAccepted: '재설치를 시작했습니다',
|
||||
skillRetryFailed: '재설치를 시작하지 못했습니다',
|
||||
skillEmpty: '아직 설치된 스킬이 없습니다. 레지스트리 URL을 붙여넣거나 zip을 업로드하세요.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
|
|
@ -5453,11 +5460,16 @@ export default {
|
|||
copy: '복사',
|
||||
addToKnowledgeBase: '지식베이스에 추가',
|
||||
artifactDrawer: {
|
||||
buttonTitle: '이 응답에서 생성된 파일 다운로드',
|
||||
buttonTitle: '이 응답에서 생성된 파일 보기',
|
||||
title: '생성된 파일',
|
||||
empty: '이번 회차에서 다운로드 가능한 파일이 없습니다.',
|
||||
preview: '미리보기',
|
||||
previewBack: '목록으로',
|
||||
collecting: '생성된 파일을 저장하는 중…',
|
||||
download: '다운로드',
|
||||
downloadFailed: '다운로드에 실패했습니다. 다시 시도해 주세요.',
|
||||
inlinePreviewHint: '클릭하여 미리보기',
|
||||
inlineMissing: '파일을 사용할 수 없습니다',
|
||||
},
|
||||
updatePlan: '계획 업데이트',
|
||||
webSearchFound: '<strong>{count}</strong>개의 웹 검색 결과 발견',
|
||||
|
|
|
|||
|
|
@ -1519,8 +1519,11 @@ export default {
|
|||
unsupportedHint: 'Скачайте файл и откройте локально',
|
||||
fullscreen: 'Полноэкранный режим',
|
||||
exitFullscreen: 'Выйти из полноэкранного режима',
|
||||
htmlRendered: 'Отображение',
|
||||
htmlSource: 'Исходный код',
|
||||
audioLoading: 'Загрузка аудио…',
|
||||
audioNotSupported: 'Ваш браузер не поддерживает воспроизведение аудио'
|
||||
audioNotSupported: 'Ваш браузер не поддерживает воспроизведение аудио',
|
||||
videoNotSupported: 'Ваш браузер не поддерживает воспроизведение видео'
|
||||
},
|
||||
organization: {
|
||||
title: 'Shared Spaces',
|
||||
|
|
@ -5200,6 +5203,10 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillRetry: 'Переустановить',
|
||||
skillRetryHint: 'Повторить с сохранённым пакетом — загружать заново не нужно',
|
||||
skillRetryAccepted: 'Переустановка запущена',
|
||||
skillRetryFailed: 'Не удалось запустить переустановку',
|
||||
skillEmpty: 'Навыки ещё не установлены. Вставьте URL реестра или загрузите zip.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
|
|
@ -5453,11 +5460,16 @@ export default {
|
|||
copy: 'Копировать',
|
||||
addToKnowledgeBase: 'Добавить в базу знаний',
|
||||
artifactDrawer: {
|
||||
buttonTitle: 'Скачать файлы, сгенерированные в этом ответе',
|
||||
buttonTitle: 'Просмотреть файлы, сгенерированные в этом ответе',
|
||||
title: 'Сгенерированные файлы',
|
||||
empty: 'В этом раунде не создано файлов для скачивания.',
|
||||
preview: 'Предпросмотр',
|
||||
previewBack: 'Назад к списку',
|
||||
collecting: 'Сохранение сгенерированных файлов…',
|
||||
download: 'Скачать',
|
||||
downloadFailed: 'Не удалось скачать, повторите попытку.',
|
||||
inlinePreviewHint: 'Нажмите для просмотра',
|
||||
inlineMissing: 'Файл недоступен',
|
||||
},
|
||||
updatePlan: 'Обновить план',
|
||||
webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',
|
||||
|
|
|
|||
|
|
@ -1521,8 +1521,11 @@ export default {
|
|||
unsupportedHint: '请下载文件后使用本地应用查看',
|
||||
fullscreen: '全屏预览',
|
||||
exitFullscreen: '退出全屏',
|
||||
htmlRendered: '渲染预览',
|
||||
htmlSource: '查看源码',
|
||||
audioLoading: '加载音频中…',
|
||||
audioNotSupported: '您的浏览器不支持音频播放'
|
||||
audioNotSupported: '您的浏览器不支持音频播放',
|
||||
videoNotSupported: '您的浏览器不支持视频播放'
|
||||
},
|
||||
organization: {
|
||||
title: '共享空间',
|
||||
|
|
@ -5202,6 +5205,10 @@ export default {
|
|||
skillLoadFailed: '加载技能列表失败',
|
||||
skillToggleFailed: '更新技能状态失败',
|
||||
skillDeleteAccepted: '已开始删除技能',
|
||||
skillRetry: '重新安装',
|
||||
skillRetryHint: '用已保存的安装包重试,无需重新上传',
|
||||
skillRetryAccepted: '已开始重新安装',
|
||||
skillRetryFailed: '重新安装失败',
|
||||
skillEmpty: '尚未安装技能。粘贴托管平台链接,或上传 zip。',
|
||||
skillVersion: '版本',
|
||||
skillVersionEmpty: '未填写',
|
||||
|
|
@ -5455,11 +5462,16 @@ export default {
|
|||
copy: '复制',
|
||||
addToKnowledgeBase: '添加到知识库',
|
||||
artifactDrawer: {
|
||||
buttonTitle: '下载本次生成的文件',
|
||||
buttonTitle: '查看本次生成的文件',
|
||||
title: '生成的文件',
|
||||
empty: '本次未生成可下载的文件',
|
||||
preview: '预览',
|
||||
previewBack: '返回列表',
|
||||
collecting: '正在保存生成的文件…',
|
||||
download: '下载',
|
||||
downloadFailed: '下载失败,请稍后重试',
|
||||
inlinePreviewHint: '点击预览',
|
||||
inlineMissing: '文件不可用',
|
||||
},
|
||||
updatePlan: '更新计划',
|
||||
webSearchFound: '找到 <strong>{count}</strong> 个网络搜索结果',
|
||||
|
|
|
|||
|
|
@ -1,36 +1,16 @@
|
|||
const previewSupportedExtensions = new Set([
|
||||
'pdf',
|
||||
'docx', 'doc',
|
||||
'pptx', 'ppt',
|
||||
'xlsx', 'xls', 'csv',
|
||||
'md', 'markdown',
|
||||
'txt', 'json', 'xml', 'html', 'css', 'js', 'ts', 'py', 'java', 'go',
|
||||
'cpp', 'c', 'h', 'sh', 'yaml', 'yml', 'ini', 'conf', 'log', 'sql', 'rs', 'rb', 'php',
|
||||
'swift', 'kt', 'scala', 'r', 'lua', 'pl', 'toml',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'svg',
|
||||
'mp3', 'wav', 'm4a', 'flac', 'ogg',
|
||||
]);
|
||||
import { resolveFilePreviewExt, isKnownPreviewableFile } from './filePreview'
|
||||
|
||||
export type ChatAttachmentLike = {
|
||||
id?: string;
|
||||
file_name?: string;
|
||||
file_type?: string;
|
||||
};
|
||||
id?: string
|
||||
file_name?: string
|
||||
file_type?: string
|
||||
}
|
||||
|
||||
export function resolveAttachmentFileType(fileName?: string, fileType?: string): string {
|
||||
const normalizedType = String(fileType || '')
|
||||
.trim()
|
||||
.replace(/^\./, '')
|
||||
.toLowerCase();
|
||||
if (normalizedType) return normalizedType;
|
||||
return String(fileName || '')
|
||||
.split('.')
|
||||
.pop()
|
||||
?.toLowerCase() || '';
|
||||
return resolveFilePreviewExt(fileName, fileType)
|
||||
}
|
||||
|
||||
export function isPreviewableAttachment(attachment: ChatAttachmentLike | null | undefined): boolean {
|
||||
if (!attachment?.id) return false;
|
||||
const fileType = resolveAttachmentFileType(attachment.file_name, attachment.file_type);
|
||||
return previewSupportedExtensions.has(fileType);
|
||||
if (!attachment?.id) return false
|
||||
return isKnownPreviewableFile(attachment.file_name, attachment.file_type)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { marked, type Renderer } from 'marked'
|
|||
import markedKatex from 'marked-katex-extension'
|
||||
import type { Tokens } from 'marked'
|
||||
|
||||
import { normalizeSandboxArtifactRefs } from './sandboxArtifactRefs.ts'
|
||||
import {
|
||||
collapseStandaloneCitationParagraphs,
|
||||
extractCitationHtmlPlaceholders,
|
||||
|
|
@ -465,7 +466,11 @@ export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMark
|
|||
const citationSafeText = stripIncompleteCitationTag(imageContextSafeText)
|
||||
const { text: tagSafe, tags } = preserveCitationTags(citationSafeText)
|
||||
const normalizedImageMarkdown = normalizeFullwidthMarkdownImageParentheses(tagSafe)
|
||||
const imageSafe = replaceIncompleteImageWithPlaceholder(normalizedImageMarkdown)
|
||||
// Skill-generated file names routinely contain spaces and parentheses, which
|
||||
// marked would split the destination on. Collapse each reference into a
|
||||
// single token before parsing.
|
||||
const artifactSafe = normalizeSandboxArtifactRefs(normalizedImageMarkdown)
|
||||
const imageSafe = replaceIncompleteImageWithPlaceholder(artifactSafe)
|
||||
const mathSafe = preprocessMathDelimiters(imageSafe)
|
||||
const restoredTags = restoreCitationTags(mathSafe, tags)
|
||||
const inlineTags = joinCitationTagsToPreviousLine(restoredTags)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,73 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
getHighlightLang,
|
||||
getPreviewMimeType,
|
||||
isKnownPreviewableExt,
|
||||
prettyPrintJson,
|
||||
resolveFilePreviewExt,
|
||||
resolvePreviewKind,
|
||||
shouldPrettyPrintJson,
|
||||
sniffPreview,
|
||||
} from './filePreview.ts'
|
||||
|
||||
test('resolveFilePreviewExt prefers explicit type and strips a leading dot', () => {
|
||||
assert.equal(resolveFilePreviewExt('chart.html', '.HTML'), 'html')
|
||||
assert.equal(resolveFilePreviewExt('kb_stats.csv', ''), 'csv')
|
||||
assert.equal(resolveFilePreviewExt('noext', ''), '')
|
||||
})
|
||||
|
||||
test('resolvePreviewKind covers office, tables, html, media, and code', () => {
|
||||
assert.equal(resolvePreviewKind('html'), 'html')
|
||||
assert.equal(resolvePreviewKind('htm'), 'html')
|
||||
assert.equal(resolvePreviewKind('csv'), 'excel')
|
||||
assert.equal(resolvePreviewKind('tsv'), 'excel')
|
||||
assert.equal(resolvePreviewKind('xlsx'), 'excel')
|
||||
assert.equal(resolvePreviewKind('pdf'), 'pdf')
|
||||
assert.equal(resolvePreviewKind('docx'), 'docx')
|
||||
assert.equal(resolvePreviewKind('pptx'), 'pptx')
|
||||
assert.equal(resolvePreviewKind('png'), 'image')
|
||||
assert.equal(resolvePreviewKind('svg'), 'image')
|
||||
assert.equal(resolvePreviewKind('md'), 'markdown')
|
||||
assert.equal(resolvePreviewKind('mp4'), 'video')
|
||||
assert.equal(resolvePreviewKind('mp3'), 'audio')
|
||||
assert.equal(resolvePreviewKind('mmd'), 'mermaid')
|
||||
assert.equal(resolvePreviewKind('vue'), 'text')
|
||||
assert.equal(resolvePreviewKind('ipynb'), 'text')
|
||||
assert.equal(resolvePreviewKind('exe'), 'unsupported')
|
||||
assert.equal(isKnownPreviewableExt('html'), true)
|
||||
assert.equal(isKnownPreviewableExt('bin'), false)
|
||||
})
|
||||
|
||||
test('sniffPreview detects html, svg, pdf, png, and mermaid from bytes', () => {
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<!DOCTYPE html><html><body>ok</body></html>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<div id="chart"></div>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<table><tr><td>1</td></tr></table>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>')).kind, 'image')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('%PDF-1.7\n')).kind, 'pdf')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('flowchart TD\n A-->B')).kind, 'mermaid')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('{"ok": true}')).kind, 'text')
|
||||
|
||||
const png = Uint8Array.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0])
|
||||
assert.equal(sniffPreview(png).kind, 'image')
|
||||
assert.equal(sniffPreview(png).ext, 'png')
|
||||
})
|
||||
|
||||
test('sniffPreview rejects NUL-containing binaries', () => {
|
||||
assert.equal(sniffPreview(Uint8Array.from([0x00, 0x01, 0x02, 0x03])).kind, 'unsupported')
|
||||
})
|
||||
|
||||
test('pretty-print helpers only rewrite canonical JSON documents', () => {
|
||||
assert.equal(shouldPrettyPrintJson('json'), true)
|
||||
assert.equal(shouldPrettyPrintJson('jsonl'), false)
|
||||
assert.equal(prettyPrintJson('{"a":1}'), '{\n "a": 1\n}')
|
||||
assert.equal(prettyPrintJson('not json'), 'not json')
|
||||
})
|
||||
|
||||
test('mime and highlight maps cover skill-generated html/csv', () => {
|
||||
assert.equal(getPreviewMimeType('html'), 'text/html')
|
||||
assert.equal(getPreviewMimeType('csv'), 'text/csv')
|
||||
assert.equal(getHighlightLang('html'), 'xml')
|
||||
assert.equal(getHighlightLang('ts'), 'typescript')
|
||||
})
|
||||
|
|
@ -0,0 +1,406 @@
|
|||
/**
|
||||
* Shared file-preview type resolution used by DocumentPreview, chat
|
||||
* attachments, and skill-generated artifacts.
|
||||
*
|
||||
* Unknown extensions are not immediately rejected: callers can fetch a
|
||||
* short byte prefix and run sniffPreview() so skill outputs without a
|
||||
* conventional suffix (or with a misleading one) still open when the
|
||||
* content is HTML, SVG, JSON-like text, PDF, images, audio, or video.
|
||||
*/
|
||||
|
||||
export type FilePreviewKind =
|
||||
| 'pdf'
|
||||
| 'docx'
|
||||
| 'pptx'
|
||||
| 'image'
|
||||
| 'excel'
|
||||
| 'text'
|
||||
| 'markdown'
|
||||
| 'html'
|
||||
| 'audio'
|
||||
| 'video'
|
||||
| 'mermaid'
|
||||
| 'unsupported'
|
||||
|
||||
export type FilePreviewSniff = {
|
||||
kind: FilePreviewKind
|
||||
ext: string
|
||||
}
|
||||
|
||||
const KIND_BY_EXT: Record<string, FilePreviewKind> = {}
|
||||
|
||||
function register(kind: FilePreviewKind, exts: string[]) {
|
||||
for (const ext of exts) {
|
||||
KIND_BY_EXT[ext] = kind
|
||||
}
|
||||
}
|
||||
|
||||
register('pdf', ['pdf'])
|
||||
register('docx', ['docx', 'doc'])
|
||||
register('pptx', ['pptx', 'ppt'])
|
||||
register('image', [
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif', 'svg', 'svgz',
|
||||
'ico', 'avif', 'apng', 'jfif', 'pjpeg', 'pjp', 'heic', 'heif',
|
||||
])
|
||||
register('excel', ['xlsx', 'xls', 'csv', 'tsv', 'tab'])
|
||||
register('markdown', ['md', 'markdown', 'mdown', 'mkd', 'mdx'])
|
||||
register('html', ['html', 'htm', 'xhtml'])
|
||||
register('audio', ['mp3', 'wav', 'm4a', 'flac', 'ogg', 'oga', 'aac', 'opus', 'weba'])
|
||||
register('video', ['mp4', 'webm', 'ogv', 'm4v', 'mov'])
|
||||
register('mermaid', ['mmd', 'mermaid'])
|
||||
register('text', [
|
||||
'txt', 'text', 'log', 'out', 'err',
|
||||
'json', 'jsonc', 'json5', 'geojson', 'ipynb', 'jsonl', 'ndjson', 'har',
|
||||
'xml', 'xsl', 'xsd', 'dtd',
|
||||
'css', 'scss', 'less', 'sass', 'styl',
|
||||
'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'mts', 'cts',
|
||||
'vue', 'svelte', 'astro',
|
||||
'py', 'pyi', 'pyw', 'java', 'kt', 'kts', 'scala', 'groovy', 'gradle',
|
||||
'go', 'rs', 'rb', 'php', 'cs', 'fs', 'fsx',
|
||||
'c', 'h', 'cc', 'cpp', 'cxx', 'hpp', 'hxx', 'hh',
|
||||
'swift', 'mm',
|
||||
'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
|
||||
'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf', 'config', 'env', 'properties',
|
||||
'editorconfig', 'gitignore', 'dockerignore', 'npmignore', 'gitattributes',
|
||||
'sql', 'graphql', 'gql', 'proto', 'prisma',
|
||||
'r', 'lua', 'pl', 'pm', 'tcl',
|
||||
'dart', 'ex', 'exs', 'erl', 'hrl', 'hs', 'lhs', 'ml', 'mli',
|
||||
'clj', 'cljs', 'cljc', 'lisp', 'el', 'scm', 'rkt',
|
||||
'vim', 'diff', 'patch',
|
||||
'makefile', 'mk', 'cmake', 'dockerfile',
|
||||
'tf', 'hcl', 'nix', 'zig', 'nim',
|
||||
'asm', 's',
|
||||
'rst', 'adoc', 'asciidoc', 'org', 'tex', 'latex',
|
||||
'lock', 'sum', 'mod',
|
||||
])
|
||||
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
pdf: 'application/pdf',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
doc: 'application/msword',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
csv: 'text/csv',
|
||||
tsv: 'text/tab-separated-values',
|
||||
tab: 'text/tab-separated-values',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
gif: 'image/gif',
|
||||
bmp: 'image/bmp',
|
||||
webp: 'image/webp',
|
||||
tiff: 'image/tiff',
|
||||
tif: 'image/tiff',
|
||||
svg: 'image/svg+xml',
|
||||
svgz: 'image/svg+xml',
|
||||
ico: 'image/x-icon',
|
||||
avif: 'image/avif',
|
||||
apng: 'image/apng',
|
||||
heic: 'image/heic',
|
||||
heif: 'image/heif',
|
||||
txt: 'text/plain',
|
||||
md: 'text/markdown',
|
||||
markdown: 'text/markdown',
|
||||
json: 'application/json',
|
||||
geojson: 'application/geo+json',
|
||||
xml: 'application/xml',
|
||||
html: 'text/html',
|
||||
htm: 'text/html',
|
||||
xhtml: 'application/xhtml+xml',
|
||||
css: 'text/css',
|
||||
js: 'text/javascript',
|
||||
mjs: 'text/javascript',
|
||||
ts: 'text/typescript',
|
||||
py: 'text/x-python',
|
||||
java: 'text/x-java',
|
||||
go: 'text/x-go',
|
||||
mp3: 'audio/mpeg',
|
||||
wav: 'audio/wav',
|
||||
m4a: 'audio/mp4',
|
||||
flac: 'audio/flac',
|
||||
ogg: 'audio/ogg',
|
||||
oga: 'audio/ogg',
|
||||
aac: 'audio/aac',
|
||||
opus: 'audio/opus',
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
ogv: 'video/ogg',
|
||||
m4v: 'video/mp4',
|
||||
mov: 'video/quicktime',
|
||||
mmd: 'text/plain',
|
||||
mermaid: 'text/plain',
|
||||
}
|
||||
|
||||
const HIGHLIGHT_LANG_BY_EXT: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
mjs: 'javascript',
|
||||
cjs: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
mts: 'typescript',
|
||||
cts: 'typescript',
|
||||
py: 'python',
|
||||
pyi: 'python',
|
||||
rb: 'ruby',
|
||||
sh: 'bash',
|
||||
bash: 'bash',
|
||||
zsh: 'bash',
|
||||
fish: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
mdx: 'markdown',
|
||||
rs: 'rust',
|
||||
kt: 'kotlin',
|
||||
kts: 'kotlin',
|
||||
pl: 'perl',
|
||||
pm: 'perl',
|
||||
conf: 'ini',
|
||||
cfg: 'ini',
|
||||
env: 'ini',
|
||||
properties: 'ini',
|
||||
editorconfig: 'ini',
|
||||
log: 'plaintext',
|
||||
vue: 'xml',
|
||||
svelte: 'xml',
|
||||
astro: 'xml',
|
||||
html: 'xml',
|
||||
htm: 'xml',
|
||||
xhtml: 'xml',
|
||||
svg: 'xml',
|
||||
less: 'css',
|
||||
scss: 'scss',
|
||||
sass: 'scss',
|
||||
ipynb: 'json',
|
||||
geojson: 'json',
|
||||
jsonc: 'json',
|
||||
json5: 'json',
|
||||
jsonl: 'json',
|
||||
ndjson: 'json',
|
||||
har: 'json',
|
||||
proto: 'protobuf',
|
||||
gql: 'graphql',
|
||||
ps1: 'powershell',
|
||||
bat: 'dos',
|
||||
cmd: 'dos',
|
||||
dockerfile: 'dockerfile',
|
||||
makefile: 'makefile',
|
||||
cmake: 'cmake',
|
||||
tf: 'hcl',
|
||||
hcl: 'hcl',
|
||||
dart: 'dart',
|
||||
ex: 'elixir',
|
||||
exs: 'elixir',
|
||||
erl: 'erlang',
|
||||
hs: 'haskell',
|
||||
fs: 'fsharp',
|
||||
clj: 'clojure',
|
||||
lisp: 'lisp',
|
||||
vim: 'vim',
|
||||
diff: 'diff',
|
||||
patch: 'diff',
|
||||
tex: 'latex',
|
||||
prisma: 'javascript',
|
||||
mmd: 'plaintext',
|
||||
mermaid: 'plaintext',
|
||||
}
|
||||
|
||||
const JSON_PRETTY_EXTS = new Set(['json', 'jsonc', 'geojson', 'ipynb', 'har'])
|
||||
|
||||
const DEFAULT_EXT_BY_KIND: Record<FilePreviewKind, string> = {
|
||||
pdf: 'pdf',
|
||||
docx: 'docx',
|
||||
pptx: 'pptx',
|
||||
image: 'png',
|
||||
excel: 'csv',
|
||||
text: 'txt',
|
||||
markdown: 'md',
|
||||
html: 'html',
|
||||
audio: 'mp3',
|
||||
video: 'mp4',
|
||||
mermaid: 'mmd',
|
||||
unsupported: '',
|
||||
}
|
||||
|
||||
const SNIFF_BYTES = 16384
|
||||
|
||||
/** Strip a leading dot and lowercase. Prefers an explicit type over the filename suffix. */
|
||||
export function resolveFilePreviewExt(fileName?: string, fileType?: string): string {
|
||||
const normalizedType = String(fileType || '')
|
||||
.trim()
|
||||
.replace(/^\./, '')
|
||||
.toLowerCase()
|
||||
if (normalizedType) return normalizedType
|
||||
const name = String(fileName || '')
|
||||
const dot = name.lastIndexOf('.')
|
||||
if (dot < 0 || dot === name.length - 1) return ''
|
||||
return name.slice(dot + 1).toLowerCase()
|
||||
}
|
||||
|
||||
export function resolvePreviewKind(ext: string): FilePreviewKind {
|
||||
if (!ext) return 'unsupported'
|
||||
return KIND_BY_EXT[ext.toLowerCase()] || 'unsupported'
|
||||
}
|
||||
|
||||
export function isKnownPreviewableExt(ext: string): boolean {
|
||||
return resolvePreviewKind(ext) !== 'unsupported'
|
||||
}
|
||||
|
||||
export function isKnownPreviewableFile(fileName?: string, fileType?: string): boolean {
|
||||
return isKnownPreviewableExt(resolveFilePreviewExt(fileName, fileType))
|
||||
}
|
||||
|
||||
export function getPreviewMimeType(ext: string): string {
|
||||
return MIME_BY_EXT[ext?.toLowerCase()] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
export function getHighlightLang(ext: string): string {
|
||||
const lower = ext?.toLowerCase() || ''
|
||||
return HIGHLIGHT_LANG_BY_EXT[lower] || lower
|
||||
}
|
||||
|
||||
export function shouldPrettyPrintJson(ext: string): boolean {
|
||||
return JSON_PRETTY_EXTS.has(ext?.toLowerCase())
|
||||
}
|
||||
|
||||
export function prettyPrintJson(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return text
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(trimmed), null, 2)
|
||||
} catch {
|
||||
return text
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `bytes` is well-formed UTF-8. A truncated trailing sequence at
|
||||
* the end of a prefix sample is tolerated so sniffing a slice does not
|
||||
* reject valid text files.
|
||||
*/
|
||||
export function isValidUTF8(bytes: Uint8Array, allowTruncatedEnd = false): boolean {
|
||||
for (let i = 0; i < bytes.length;) {
|
||||
const b = bytes[i]
|
||||
let remaining = 0
|
||||
if (b <= 0x7F) {
|
||||
remaining = 0
|
||||
} else if ((b & 0xE0) === 0xC0) {
|
||||
remaining = 1
|
||||
} else if ((b & 0xF0) === 0xE0) {
|
||||
remaining = 2
|
||||
} else if ((b & 0xF8) === 0xF0) {
|
||||
remaining = 3
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
if (i + remaining >= bytes.length) {
|
||||
return allowTruncatedEnd
|
||||
}
|
||||
for (let j = 1; j <= remaining; j++) {
|
||||
if ((bytes[i + j] & 0xC0) !== 0x80) return false
|
||||
}
|
||||
i += 1 + remaining
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function asciiTag(bytes: Uint8Array, offset: number, length: number): string {
|
||||
if (offset + length > bytes.length) return ''
|
||||
let out = ''
|
||||
for (let i = 0; i < length; i++) {
|
||||
out += String.fromCharCode(bytes[offset + i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function looksLikeMermaid(head: string): boolean {
|
||||
const line = head.split(/\r?\n/, 1)[0]?.trim() || ''
|
||||
if (/^(graph|flowchart)\s+[A-Za-z-]+\b/i.test(line)) return true
|
||||
return /^(sequenceDiagram|classDiagram|erDiagram|gantt|pie\b|mindmap|gitGraph|stateDiagram|journey|C4Context|requirementDiagram|quadrantChart|sankey-beta|xychart-beta|block-beta|timeline)\b/i.test(line)
|
||||
}
|
||||
|
||||
function sniffFromMagic(bytes: Uint8Array): FilePreviewSniff | null {
|
||||
if (bytes.length >= 4 && asciiTag(bytes, 0, 4) === '%PDF') {
|
||||
return { kind: 'pdf', ext: 'pdf' }
|
||||
}
|
||||
if (bytes.length >= 8 && bytes[0] === 0x89 && asciiTag(bytes, 1, 3) === 'PNG') {
|
||||
return { kind: 'image', ext: 'png' }
|
||||
}
|
||||
if (bytes.length >= 3 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) {
|
||||
return { kind: 'image', ext: 'jpg' }
|
||||
}
|
||||
if (bytes.length >= 6 && asciiTag(bytes, 0, 3) === 'GIF') {
|
||||
return { kind: 'image', ext: 'gif' }
|
||||
}
|
||||
if (bytes.length >= 12 && asciiTag(bytes, 0, 4) === 'RIFF') {
|
||||
const tag = asciiTag(bytes, 8, 4)
|
||||
if (tag === 'WEBP') return { kind: 'image', ext: 'webp' }
|
||||
if (tag === 'WAVE') return { kind: 'audio', ext: 'wav' }
|
||||
if (tag === 'AVI ') return { kind: 'video', ext: 'avi' }
|
||||
}
|
||||
if (bytes.length >= 8 && asciiTag(bytes, 4, 4) === 'ftyp') {
|
||||
return { kind: 'video', ext: 'mp4' }
|
||||
}
|
||||
if (bytes.length >= 4 && bytes[0] === 0x1A && bytes[1] === 0x45 && bytes[2] === 0xDF && bytes[3] === 0xA3) {
|
||||
return { kind: 'video', ext: 'webm' }
|
||||
}
|
||||
if (bytes.length >= 3 && asciiTag(bytes, 0, 3) === 'ID3') {
|
||||
return { kind: 'audio', ext: 'mp3' }
|
||||
}
|
||||
if (bytes.length >= 4 && bytes[0] === 0x66 && bytes[1] === 0x4C && bytes[2] === 0x61 && bytes[3] === 0x43) {
|
||||
return { kind: 'audio', ext: 'flac' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer a preview kind from a byte prefix. Used when the filename has no
|
||||
* known extension, or when callers want a second opinion on unlabeled
|
||||
* skill output.
|
||||
*/
|
||||
export function sniffPreview(bytes: Uint8Array): FilePreviewSniff {
|
||||
if (!bytes || bytes.length === 0) {
|
||||
return { kind: 'text', ext: 'txt' }
|
||||
}
|
||||
const magic = sniffFromMagic(bytes)
|
||||
if (magic) return magic
|
||||
|
||||
const sample = bytes.subarray(0, Math.min(bytes.length, SNIFF_BYTES))
|
||||
if (sample.includes(0)) {
|
||||
return { kind: 'unsupported', ext: '' }
|
||||
}
|
||||
if (!isValidUTF8(sample, true)) {
|
||||
return { kind: 'unsupported', ext: '' }
|
||||
}
|
||||
|
||||
const head = new TextDecoder('utf-8').decode(sample).replace(/^\uFEFF/, '').trimStart()
|
||||
const headLower = head.slice(0, 512).toLowerCase()
|
||||
if (
|
||||
headLower.startsWith('<!doctype html') ||
|
||||
headLower.startsWith('<html') ||
|
||||
/^<(?:head|body|div|table|section|article|main|header|footer|nav|script|style|meta|link|span|p|h[1-6]|canvas|form|ul|ol|pre|template)[\s>]/i.test(head)
|
||||
) {
|
||||
return { kind: 'html', ext: 'html' }
|
||||
}
|
||||
if (/^<\?xml\b/i.test(head) && /<svg[\s>]/i.test(head.slice(0, 2048))) {
|
||||
return { kind: 'image', ext: 'svg' }
|
||||
}
|
||||
if (/^<svg[\s>]/i.test(head)) {
|
||||
return { kind: 'image', ext: 'svg' }
|
||||
}
|
||||
if (looksLikeMermaid(head)) {
|
||||
return { kind: 'mermaid', ext: 'mmd' }
|
||||
}
|
||||
if (
|
||||
(head.startsWith('{') || head.startsWith('[')) &&
|
||||
/"cells"\s*:/.test(head) &&
|
||||
/"nbformat"\s*:/.test(head)
|
||||
) {
|
||||
return { kind: 'text', ext: 'ipynb' }
|
||||
}
|
||||
return { kind: 'text', ext: DEFAULT_EXT_BY_KIND.text }
|
||||
}
|
||||
|
||||
export { SNIFF_BYTES as FILE_PREVIEW_SNIFF_BYTES }
|
||||
|
|
@ -79,6 +79,7 @@ export const markdownDomPurifyConfig = {
|
|||
ALLOWED_ATTR: [
|
||||
'href', 'title', 'target', 'rel', 'data-tooltip', 'data-url', 'data-kb-id',
|
||||
'data-chunk-id', 'data-doc', 'data-slug', 'class', 'role', 'tabindex', 'src', 'alt', 'data-protected-src', 'data-img-loading',
|
||||
'data-artifact-index',
|
||||
'width', 'height', 'style', 'id', 'type', 'aria-label', 'data-mermaid', 'disabled',
|
||||
'd', 'fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
|
||||
'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'stroke-opacity',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,191 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
isArtifactRefHref,
|
||||
normalizeSandboxArtifactRefs,
|
||||
renderArtifactReference,
|
||||
resolveArtifactRef,
|
||||
type ArtifactRefMeta,
|
||||
} from './sandboxArtifactRefs.ts'
|
||||
|
||||
const labels = { previewHint: '点击预览', missingHint: '文件不可用' }
|
||||
|
||||
// 22 位句柄,与后端 types.ResourceHandleLength 一致。
|
||||
const handleFor = (i: number) => `art${i}`.padEnd(22, 'x')
|
||||
const refFor = (i: number) => `resource://${handleFor(i)}`
|
||||
|
||||
const artifacts: ArtifactRefMeta[] = [
|
||||
{ index: 0, handle: refFor(0), file_name: '市场画像评分_e7edba.html', file_type: 'text/html' },
|
||||
{ index: 1, handle: refFor(1), file_name: 'trend.png', file_type: 'image/png' },
|
||||
{ index: 2, handle: refFor(2), file_name: 'diagram.svg', file_type: 'image/svg+xml' },
|
||||
{ index: 3, handle: refFor(3), file_name: '腾讯控股(00700) 成交量_838ccc.html', file_type: 'text/html' },
|
||||
]
|
||||
|
||||
// 知识库检索图:形式与产物完全相同,但不属于这条消息。
|
||||
const foreignRef = `resource://${'z'.repeat(22)}`
|
||||
|
||||
test('isArtifactRefHref matches handle and sandbox forms only', () => {
|
||||
assert.equal(isArtifactRefHref(refFor(0)), true)
|
||||
assert.equal(isArtifactRefHref('sandbox:trend.png'), true)
|
||||
assert.equal(isArtifactRefHref('sandbox://trend.png'), true)
|
||||
assert.equal(isArtifactRefHref('https://example.com/trend.png'), false)
|
||||
// 长度不对的不是句柄。
|
||||
assert.equal(isArtifactRefHref('resource://tenant/1/trend.png'), false)
|
||||
assert.equal(isArtifactRefHref('trend.png'), false)
|
||||
assert.equal(isArtifactRefHref(''), false)
|
||||
})
|
||||
|
||||
test('resolveArtifactRef resolves both the handle and the name form', () => {
|
||||
assert.equal(resolveArtifactRef(refFor(1), artifacts)?.file_name, 'trend.png')
|
||||
assert.equal(resolveArtifactRef('sandbox:trend.png', artifacts)?.index, 1)
|
||||
assert.equal(
|
||||
resolveArtifactRef('sandbox:/workspace/output/trend.png', artifacts)?.index,
|
||||
1,
|
||||
)
|
||||
assert.equal(
|
||||
resolveArtifactRef('sandbox:%E5%B8%82%E5%9C%BA%E7%94%BB%E5%83%8F%E8%AF%84%E5%88%86_e7edba.html', artifacts)?.index,
|
||||
0,
|
||||
)
|
||||
assert.equal(resolveArtifactRef(foreignRef, artifacts), null)
|
||||
assert.equal(resolveArtifactRef('sandbox:missing.csv', artifacts), null)
|
||||
})
|
||||
|
||||
test('resolveArtifactRef accepts the url field carried by persisted messages', () => {
|
||||
const persisted: ArtifactRefMeta[] = [{ index: 0, url: refFor(7), file_name: 'a.csv' }]
|
||||
assert.equal(resolveArtifactRef(refFor(7), persisted)?.file_name, 'a.csv')
|
||||
})
|
||||
|
||||
test('renderArtifactReference leaves ordinary images to the default renderer', () => {
|
||||
assert.equal(
|
||||
renderArtifactReference({ href: 'https://example.com/a.png', artifacts, labels }),
|
||||
null,
|
||||
)
|
||||
assert.equal(
|
||||
renderArtifactReference({ href: 'resource://tenant/1/a.png', artifacts, labels }),
|
||||
null,
|
||||
)
|
||||
})
|
||||
|
||||
test('a handle from outside this message falls back to protected-image rendering', () => {
|
||||
// 知识库检索图与产物同形。此时必须交回默认渲染,而不是显示「文件不可用」。
|
||||
assert.equal(
|
||||
renderArtifactReference({ href: foreignRef, artifacts, labels }),
|
||||
null,
|
||||
)
|
||||
assert.equal(
|
||||
renderArtifactReference({ href: foreignRef, artifacts: [], labels, streaming: true }),
|
||||
null,
|
||||
)
|
||||
})
|
||||
|
||||
test('renderArtifactReference renders image artifacts inline', () => {
|
||||
const html = renderArtifactReference({
|
||||
href: refFor(1),
|
||||
alt: '走势',
|
||||
artifacts,
|
||||
labels,
|
||||
})
|
||||
assert.ok(html?.includes('class="markdown-image artifact-ref-image"'))
|
||||
assert.ok(html?.includes('data-artifact-index="1"'))
|
||||
assert.ok(html?.includes('data-img-loading="1"'))
|
||||
assert.ok(html?.includes('alt="走势"'))
|
||||
})
|
||||
|
||||
test('renderArtifactReference renders non-image artifacts as a clickable card', () => {
|
||||
const html = renderArtifactReference({
|
||||
href: refFor(0),
|
||||
alt: '市场画像评分',
|
||||
artifacts,
|
||||
labels,
|
||||
})
|
||||
assert.ok(html?.includes('class="artifact-ref-card"'))
|
||||
assert.ok(html?.includes('data-artifact-index="0"'))
|
||||
assert.ok(html?.includes('role="button"'))
|
||||
assert.ok(html?.includes('市场画像评分_e7edba.html'))
|
||||
assert.ok(html?.includes('点击预览'))
|
||||
assert.ok(!html?.includes('<img'))
|
||||
})
|
||||
|
||||
test('svg artifacts go through the sandboxed preview rather than inline rendering', () => {
|
||||
const html = renderArtifactReference({ href: refFor(2), artifacts, labels })
|
||||
assert.ok(html?.includes('artifact-ref-card'))
|
||||
assert.ok(!html?.includes('artifact-ref-image'))
|
||||
})
|
||||
|
||||
test('while streaming an unresolved reference shows the image skeleton', () => {
|
||||
// Artifacts are only collected once the turn ends, so mid-stream every
|
||||
// reference is unresolved; a card there would flash a half-written name.
|
||||
const html = renderArtifactReference({
|
||||
href: 'sandbox:市场画像评分_e7edba.html',
|
||||
artifacts: [],
|
||||
labels,
|
||||
streaming: true,
|
||||
})
|
||||
assert.ok(html?.includes('streaming-image-loading'))
|
||||
assert.ok(!html?.includes('artifact-ref-card'))
|
||||
})
|
||||
|
||||
test('after the turn ends an unresolved reference says so instead of hanging', () => {
|
||||
const html = renderArtifactReference({
|
||||
href: 'sandbox:市场画像评分_e7edba.html',
|
||||
alt: '市场画像评分',
|
||||
artifacts: [],
|
||||
labels,
|
||||
})
|
||||
assert.ok(html?.includes('artifact-ref-card--pending'))
|
||||
assert.ok(html?.includes('文件不可用'))
|
||||
assert.ok(!html?.includes('data-artifact-index'))
|
||||
assert.ok(!html?.includes('role="button"'))
|
||||
})
|
||||
|
||||
test('file names with spaces and parentheses resolve end to end', () => {
|
||||
const raw = ' 成交量_838ccc.html)'
|
||||
const normalized = normalizeSandboxArtifactRefs(raw)
|
||||
|
||||
// marked would split the raw destination at the first space; after
|
||||
// normalization it is a single token.
|
||||
const href = normalized.slice(normalized.indexOf('](') + 2, normalized.lastIndexOf(')'))
|
||||
assert.ok(!href.includes(' '))
|
||||
assert.equal(resolveArtifactRef(href, artifacts)?.index, 3)
|
||||
|
||||
const html = renderArtifactReference({ href, alt: '成交量', artifacts, labels })
|
||||
assert.ok(html?.includes('腾讯控股(00700) 成交量_838ccc.html'))
|
||||
assert.ok(html?.includes('data-artifact-index="3"'))
|
||||
})
|
||||
|
||||
test('normalizeSandboxArtifactRefs leaves everything else alone', () => {
|
||||
const untouched = [
|
||||
'.png)',
|
||||
'',
|
||||
'腾讯控股(00700) 的成交量见下图。',
|
||||
'写成 `` 即可',
|
||||
'```\n\n```',
|
||||
]
|
||||
for (const markdown of untouched) {
|
||||
assert.equal(normalizeSandboxArtifactRefs(markdown), markdown)
|
||||
}
|
||||
})
|
||||
|
||||
test('normalizeSandboxArtifactRefs preserves a title and an unterminated tail', () => {
|
||||
assert.equal(
|
||||
normalizeSandboxArtifactRefs(''),
|
||||
'',
|
||||
)
|
||||
// Mid-stream the closing paren has not arrived yet; leave the tail for the
|
||||
// streaming placeholder guard rather than guessing where it ends.
|
||||
assert.equal(
|
||||
normalizeSandboxArtifactRefs(',
|
||||
'
|
||||
})
|
||||
|
||||
test('artifact names are HTML-escaped', () => {
|
||||
const html = renderArtifactReference({
|
||||
href: refFor(0),
|
||||
artifacts: [{ index: 0, handle: refFor(0), file_name: '<img src=x onerror=alert(1)>.csv' }],
|
||||
labels,
|
||||
})
|
||||
assert.ok(!html?.includes('<img src=x'))
|
||||
assert.ok(html?.includes('<img'))
|
||||
})
|
||||
|
|
@ -0,0 +1,395 @@
|
|||
/**
|
||||
* 把回答正文里对「沙盒生成文件」的引用,接到 artifact 下载链路上。
|
||||
*
|
||||
* 模型会用 Markdown 图片语法引用它在沙盒里生成的文件(提示词规定写成
|
||||
* ``),服务端在落库前把它改写成该文件的稳定句柄
|
||||
* `resource://<handle>` —— 与知识库图片、聊天附件同一种引用形式。两种写法
|
||||
* 都指向同一份 `Message.Artifacts`:
|
||||
*
|
||||
* - `resource://<handle>` —— 落库后的权威形式,历史会话读到的就是它;
|
||||
* - `sandbox:<文件名>` —— 模型原始写法,本轮流式输出尚未改写时用到。
|
||||
*
|
||||
* 由于句柄形式与知识库图片完全一致,一条回答里同时出现「检索到的知识库图」
|
||||
* 和「技能生成的图」是常态。所以句柄对不上本消息产物列表时必须返回 null,
|
||||
* 交回默认的受保护图片渲染,而不是显示「文件不可用」。
|
||||
*
|
||||
* 图片类产物内联显示(带鉴权拉取后换成 blob),其余类型(HTML 图表、CSV、
|
||||
* 文档等)渲染成一张卡片,点击后交给 ChatArtifactsDrawer 预览——正文里塞一个
|
||||
* 1MB 的自包含 HTML iframe 既慢又不安全。
|
||||
*/
|
||||
|
||||
import { escapeHTML } from './security.ts';
|
||||
|
||||
/** 与后端 artifactListItem / SSE publicArtifactViews 对齐的最小字段集。 */
|
||||
export interface ArtifactRefMeta {
|
||||
index: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
/** `resource://<handle>`。后端未启用资源目录时为空,此时只能按文件名解析。 */
|
||||
handle?: string;
|
||||
/**
|
||||
* 历史消息直接携带 `Message.Artifacts`,其中的存储引用叫 `url`。与 handle
|
||||
* 同义,取其一即可。
|
||||
*/
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface ArtifactRefContext {
|
||||
sessionId: string;
|
||||
messageId: string;
|
||||
}
|
||||
|
||||
export interface ArtifactRefLabels {
|
||||
/** 卡片副标题,如「点击预览」。 */
|
||||
previewHint: string;
|
||||
/** 本轮已结束但引用对不上任何产物时的副标题,如「文件不可用」。 */
|
||||
missingHint: string;
|
||||
}
|
||||
|
||||
const RESOURCE_HANDLE_RE = /^resource:\/\/([A-Za-z0-9_-]{22})$/;
|
||||
const SANDBOX_NAME_RE = /^sandbox:(?:\/\/)?(.+)$/i;
|
||||
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif']);
|
||||
const TRANSPARENT_PIXEL =
|
||||
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
|
||||
|
||||
type ArtifactRef = { kind: 'handle'; handle: string } | { kind: 'name'; name: string };
|
||||
|
||||
function parseArtifactRef(href: string): ArtifactRef | null {
|
||||
const trimmed = (href || '').trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
const handleMatch = trimmed.match(RESOURCE_HANDLE_RE);
|
||||
if (handleMatch) {
|
||||
return { kind: 'handle', handle: handleMatch[1] };
|
||||
}
|
||||
|
||||
const nameMatch = trimmed.match(SANDBOX_NAME_RE);
|
||||
if (!nameMatch) return null;
|
||||
let name = nameMatch[1].trim();
|
||||
try {
|
||||
name = decodeURIComponent(name);
|
||||
} catch {
|
||||
// 保留原样:文件名里出现裸 % 时 decodeURIComponent 会抛错。
|
||||
}
|
||||
// 目录前缀不带信息量,产物是按文件名索引的。
|
||||
name = name.split('/').pop() || '';
|
||||
return name ? { kind: 'name', name } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 该链接目标是否可能是沙盒产物引用。
|
||||
*
|
||||
* 句柄形式与知识库图片同形,因此这里为真只说明「值得交给产物解析试一次」,
|
||||
* 不代表本消息真有这个文件。
|
||||
*/
|
||||
export function isArtifactRefHref(href: string): boolean {
|
||||
return parseArtifactRef(href) !== null;
|
||||
}
|
||||
|
||||
function artifactHandle(artifact: ArtifactRefMeta): string {
|
||||
const raw = (artifact.handle || artifact.url || '').trim();
|
||||
return raw.match(RESOURCE_HANDLE_RE)?.[1] || '';
|
||||
}
|
||||
|
||||
const CODE_SPAN_OR_FENCE_RE = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/g;
|
||||
|
||||
/**
|
||||
* 扫描一个 Markdown 链接目标,返回括号内的原文与右括号位置。
|
||||
*
|
||||
* 用括号配对而不是正则,是因为技能生成的文件名经常带括号和空格
|
||||
* (`腾讯控股(00700) 成交量_838ccc.html`)。marked 会在第一个空格处把目标截断,
|
||||
* 于是引用永远匹配不上产物;而按深度扫描能准确找到真正闭合链接的那个右括号。
|
||||
*/
|
||||
function scanLinkDestination(text: string, openIndex: number): { inner: string; end: number } | null {
|
||||
let depth = 1;
|
||||
for (let i = openIndex + 1; i < text.length; i += 1) {
|
||||
const ch = text[i];
|
||||
if (ch === '\n') return null;
|
||||
if (ch === '(') depth += 1;
|
||||
else if (ch === ')') {
|
||||
depth -= 1;
|
||||
if (depth === 0) return { inner: text.slice(openIndex + 1, i), end: i };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 把目标里可选的标题部分(`dest "title"`)拆出来。 */
|
||||
function splitDestinationTitle(inner: string): { destination: string; title: string } {
|
||||
const match = inner.match(/^([\s\S]*?)(\s+(?:"[^"]*"|'[^']*'))$/);
|
||||
if (!match) return { destination: inner.trim(), title: '' };
|
||||
return { destination: match[1].trim(), title: match[2] };
|
||||
}
|
||||
|
||||
/** `](` 之前必须是同一行上闭合的 `[...]`,否则这不是一个链接。 */
|
||||
function hasLinkLabelBefore(text: string, closeBracketIndex: number): boolean {
|
||||
for (let i = closeBracketIndex - 1; i >= 0; i -= 1) {
|
||||
const ch = text[i];
|
||||
if (ch === '\n') return false;
|
||||
if (ch === '[') return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeSegment(segment: string): string {
|
||||
if (!segment.includes('](')) return segment;
|
||||
|
||||
let out = '';
|
||||
let cursor = 0;
|
||||
while (cursor < segment.length) {
|
||||
const relative = segment.slice(cursor).indexOf('](');
|
||||
if (relative < 0) break;
|
||||
const closeBracket = cursor + relative;
|
||||
const open = closeBracket + 1;
|
||||
|
||||
if (!hasLinkLabelBefore(segment, closeBracket)) {
|
||||
out += segment.slice(cursor, open + 1);
|
||||
cursor = open + 1;
|
||||
continue;
|
||||
}
|
||||
const scanned = scanLinkDestination(segment, open);
|
||||
if (!scanned) {
|
||||
out += segment.slice(cursor, open + 1);
|
||||
cursor = open + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const { destination, title } = splitDestinationTitle(scanned.inner);
|
||||
const ref = parseArtifactRef(destination);
|
||||
if (!ref || ref.kind !== 'name') {
|
||||
out += segment.slice(cursor, scanned.end + 1);
|
||||
cursor = scanned.end + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Percent-encode so marked sees a single whitespace-free token;
|
||||
// parseArtifactRef decodes it again on the way out.
|
||||
out += `${segment.slice(cursor, open + 1)}sandbox:${encodeURIComponent(ref.name)}${title})`;
|
||||
cursor = scanned.end + 1;
|
||||
}
|
||||
return out + segment.slice(cursor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 marked 解析前,把 `sandbox:` 引用的目标规整成不含空格的单个 token。
|
||||
*
|
||||
* 不做这一步的话,带空格的文件名会被 marked 从空格处切开,目标只剩前半截,
|
||||
* 后半截漏成正文——正是「卡片名字被截断 + 尾巴变成裸文本」那个现象。
|
||||
* 代码块内的示例原样保留。
|
||||
*/
|
||||
export function normalizeSandboxArtifactRefs(markdown: string): string {
|
||||
if (!markdown || !markdown.includes('](')) return markdown;
|
||||
if (!/\]\(\s*sandbox:/i.test(markdown)) return markdown;
|
||||
|
||||
const parts = markdown.split(CODE_SPAN_OR_FENCE_RE);
|
||||
for (let i = 0; i < parts.length; i += 2) {
|
||||
parts[i] = normalizeSegment(parts[i]);
|
||||
}
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/** 把引用解析成具体产物;解析不到(尚未收集完/文件名对不上)返回 null。 */
|
||||
export function resolveArtifactRef(
|
||||
href: string,
|
||||
artifacts: ArtifactRefMeta[] | undefined | null,
|
||||
): ArtifactRefMeta | null {
|
||||
const ref = parseArtifactRef(href);
|
||||
if (!ref || !artifacts?.length) return null;
|
||||
|
||||
if (ref.kind === 'handle') {
|
||||
return artifacts.find((item) => artifactHandle(item) === ref.handle) || null;
|
||||
}
|
||||
return artifacts.find((item) => (item.file_name || '').trim() === ref.name) || null;
|
||||
}
|
||||
|
||||
function fileExtension(fileName: string): string {
|
||||
const base = (fileName || '').trim().toLowerCase();
|
||||
const dot = base.lastIndexOf('.');
|
||||
return dot > 0 ? base.slice(dot + 1) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否按图片内联渲染。SVG 刻意排除:它是可执行内容,走卡片 + 预览的沙箱路径。
|
||||
*/
|
||||
function rendersAsImage(artifact: ArtifactRefMeta): boolean {
|
||||
const ext = fileExtension(artifact.file_name);
|
||||
if (ext) return IMAGE_EXTENSIONS.has(ext);
|
||||
const type = (artifact.file_type || '').toLowerCase();
|
||||
return type.startsWith('image/') && !type.includes('svg');
|
||||
}
|
||||
|
||||
// blob URL 按 (会话, 消息, 下标) 缓存,并挂在 window 上:Vite 热更新会替换模块
|
||||
// 但不会重建文档,模块级 Map 会让已加载的图片退回占位图。
|
||||
type ArtifactBlobState = { blobByKey: Map<string, string>; inflight: Map<string, Promise<string | null>> };
|
||||
|
||||
const artifactBlobState: ArtifactBlobState = (() => {
|
||||
const fresh = (): ArtifactBlobState => ({ blobByKey: new Map(), inflight: new Map() });
|
||||
if (typeof window === 'undefined') return fresh();
|
||||
const scope = window as typeof window & { __weknoraArtifactBlobCacheV1__?: ArtifactBlobState };
|
||||
scope.__weknoraArtifactBlobCacheV1__ ||= fresh();
|
||||
return scope.__weknoraArtifactBlobCacheV1__;
|
||||
})();
|
||||
|
||||
function blobCacheKey(ctx: ArtifactRefContext, index: number): string {
|
||||
return `${ctx.sessionId}\u0000${ctx.messageId}\u0000${index}`;
|
||||
}
|
||||
|
||||
function fileIconSvg(): string {
|
||||
return (
|
||||
'<svg class="artifact-ref-card__glyph" viewBox="0 0 24 24" aria-hidden="true">'
|
||||
+ '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" '
|
||||
+ 'fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>'
|
||||
+ '<path d="M14 2v6h6" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>'
|
||||
+ '</svg>'
|
||||
);
|
||||
}
|
||||
|
||||
// 与 chatMarkdownRenderer 的流式图片骨架同一个类名,样式复用。
|
||||
const STREAMING_PLACEHOLDER =
|
||||
'<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>';
|
||||
|
||||
function renderCard(fileName: string, hint: string, index: number | null): string {
|
||||
const safeName = escapeHTML(fileName);
|
||||
const safeHint = escapeHTML(hint);
|
||||
// 卡片必须是内联元素:marked 会把图片包在 <p> 里,块级元素会被 HTML 解析器
|
||||
// 提到段落外面,破坏正文结构。
|
||||
const interactive = index === null
|
||||
? ''
|
||||
: ` data-artifact-index="${index}" role="button" tabindex="0"`;
|
||||
const state = index === null ? ' artifact-ref-card--pending' : '';
|
||||
return (
|
||||
`<span class="artifact-ref-card${state}"${interactive} title="${safeName}">`
|
||||
+ `<span class="artifact-ref-card__icon" aria-hidden="true">${fileIconSvg()}</span>`
|
||||
+ '<span class="artifact-ref-card__text">'
|
||||
+ `<span class="artifact-ref-card__name">${safeName}</span>`
|
||||
+ `<span class="artifact-ref-card__hint">${safeHint}</span>`
|
||||
+ '</span></span>'
|
||||
);
|
||||
}
|
||||
|
||||
function renderImage(
|
||||
artifact: ArtifactRefMeta,
|
||||
alt: string,
|
||||
ctx: ArtifactRefContext | null,
|
||||
): string {
|
||||
const safeAlt = escapeHTML(alt || artifact.file_name || '');
|
||||
// 已经拉取过就直接给 blob:流式重渲染会重建 <img>,否则每帧都会闪回占位图。
|
||||
const cached = ctx ? artifactBlobState.blobByKey.get(blobCacheKey(ctx, artifact.index)) : undefined;
|
||||
const src = cached || TRANSPARENT_PIXEL;
|
||||
const loading = cached ? '' : ' data-img-loading="1"';
|
||||
return (
|
||||
`<img class="markdown-image artifact-ref-image" src="${src}" alt="${safeAlt}"`
|
||||
+ ` data-artifact-index="${artifact.index}"${loading}>`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染一个 Markdown 图片/链接目标。
|
||||
*
|
||||
* 返回 null 表示这不是沙盒产物引用,调用方应回落到默认渲染(普通图片、
|
||||
* `resource://` 受保护图片、外链等一律不受影响)。
|
||||
*/
|
||||
export function renderArtifactReference(args: {
|
||||
href: string;
|
||||
alt?: string;
|
||||
artifacts?: ArtifactRefMeta[] | null;
|
||||
labels: ArtifactRefLabels;
|
||||
context?: ArtifactRefContext | null;
|
||||
/** 本轮回答还在生成中。产物要到本轮结束才会收集,此时解析不到是正常的。 */
|
||||
streaming?: boolean;
|
||||
}): string | null {
|
||||
const ref = parseArtifactRef(args.href);
|
||||
if (!ref) return null;
|
||||
|
||||
const artifact = resolveArtifactRef(args.href, args.artifacts);
|
||||
if (!artifact) {
|
||||
// 句柄对不上本消息的产物,说明这是别的受保护文件(知识库检索图、
|
||||
// 附件图……)。交回默认渲染,由 hydrateProtectedFileImages 带鉴权拉取。
|
||||
if (ref.kind === 'handle') return null;
|
||||
// 产物列表要到本轮结束才随 complete 事件到达,流式期间必然解析不到。
|
||||
// 这时给骨架屏而不是卡片:既避免半截文件名闪一下,也不会把「生成中」
|
||||
// 这种状态留在一个其实已经结束的回答里。
|
||||
if (args.streaming) return STREAMING_PLACEHOLDER;
|
||||
// 本轮已结束仍对不上,说明模型引用了并不存在的文件。如实说明,不要
|
||||
// 继续显示「生成中」。
|
||||
const fallbackName = ref.name || (args.alt || '').trim();
|
||||
if (!fallbackName) return '';
|
||||
return renderCard(fallbackName, args.labels.missingHint, null);
|
||||
}
|
||||
|
||||
if (rendersAsImage(artifact)) {
|
||||
return renderImage(artifact, args.alt || '', args.context ?? null);
|
||||
}
|
||||
return renderCard(artifact.file_name, args.labels.previewHint, artifact.index);
|
||||
}
|
||||
|
||||
async function loadArtifactBlobURL(ctx: ArtifactRefContext, index: number): Promise<string | null> {
|
||||
const key = blobCacheKey(ctx, index);
|
||||
const cached = artifactBlobState.blobByKey.get(key);
|
||||
if (cached) return cached;
|
||||
|
||||
let task = artifactBlobState.inflight.get(key);
|
||||
if (!task) {
|
||||
task = (async () => {
|
||||
try {
|
||||
// Imported lazily so parsing/rendering stays free of the axios
|
||||
// transport — those parts run in plain Node during unit tests.
|
||||
const { downloadArtifact } = await import('@/api/chat');
|
||||
const blob = await downloadArtifact(ctx.sessionId, ctx.messageId, index);
|
||||
const blobURL = URL.createObjectURL(blob);
|
||||
artifactBlobState.blobByKey.set(key, blobURL);
|
||||
return blobURL;
|
||||
} catch (error) {
|
||||
console.warn('[sandboxArtifactRefs] artifact image load failed:', error);
|
||||
return null;
|
||||
} finally {
|
||||
artifactBlobState.inflight.delete(key);
|
||||
}
|
||||
})();
|
||||
artifactBlobState.inflight.set(key, task);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把正文里的产物图片换成带鉴权拉取的 blob。
|
||||
*
|
||||
* 与 hydrateProtectedFileImages 同样是幂等的:已换过的元素带 authHydrated 标记,
|
||||
* 相同文件的并发请求共享同一个 Promise。
|
||||
*/
|
||||
export async function hydrateArtifactImages(
|
||||
root: ParentNode | null | undefined,
|
||||
ctx: ArtifactRefContext | null | undefined,
|
||||
): Promise<void> {
|
||||
if (!root || !ctx?.sessionId || !ctx?.messageId) return;
|
||||
|
||||
const images = Array.from(
|
||||
root.querySelectorAll<HTMLImageElement>('img.artifact-ref-image[data-artifact-index]'),
|
||||
).filter((img) => img.dataset.authHydrated !== '1');
|
||||
if (!images.length) return;
|
||||
|
||||
await Promise.all(images.map(async (img) => {
|
||||
const index = Number(img.getAttribute('data-artifact-index'));
|
||||
if (!Number.isInteger(index) || index < 0) return;
|
||||
img.dataset.authHydrated = '1';
|
||||
|
||||
const blobURL = await loadArtifactBlobURL(ctx, index);
|
||||
if (!blobURL) {
|
||||
img.dataset.authHydrated = '0';
|
||||
return;
|
||||
}
|
||||
img.src = blobURL;
|
||||
img.removeAttribute('data-img-loading');
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从点击/键盘事件里取出被激活的产物卡片下标;返回 null 表示事件与卡片无关。
|
||||
*/
|
||||
export function artifactIndexFromEventTarget(target: EventTarget | null): number | null {
|
||||
if (!(target instanceof Element)) return null;
|
||||
const card = target.closest('.artifact-ref-card[data-artifact-index]');
|
||||
if (!card) return null;
|
||||
const index = Number(card.getAttribute('data-artifact-index'));
|
||||
return Number.isInteger(index) && index >= 0 ? index : null;
|
||||
}
|
||||
|
|
@ -69,6 +69,7 @@ const DOMPurifyConfig = {
|
|||
// 允许的属性
|
||||
ALLOWED_ATTR: [
|
||||
'href', 'title', 'alt', 'src', 'class', 'id', 'style', 'data-protected-src', 'data-img-loading',
|
||||
'data-artifact-index',
|
||||
'target', 'rel', 'width', 'height', 'open',
|
||||
'type', 'aria-label', 'disabled', 'role', 'tabindex',
|
||||
// Mermaid SVG 支持的属性
|
||||
|
|
|
|||
|
|
@ -0,0 +1,28 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { agentTurnUsedSkillScript, isCollectingSkillArtifacts } from './skillArtifacts.ts'
|
||||
|
||||
test('agentTurnUsedSkillScript detects execute_skill_script in the stream', () => {
|
||||
assert.equal(agentTurnUsedSkillScript(undefined), false)
|
||||
assert.equal(agentTurnUsedSkillScript([]), false)
|
||||
assert.equal(agentTurnUsedSkillScript([{ tool_name: 'web_search' }]), false)
|
||||
assert.equal(agentTurnUsedSkillScript([{ tool_name: 'execute_skill_script' }]), true)
|
||||
})
|
||||
|
||||
test('isCollectingSkillArtifacts covers the post-answer upload gap', () => {
|
||||
const stream = [{ tool_name: 'execute_skill_script' }]
|
||||
assert.equal(isCollectingSkillArtifacts({ agentEventStream: stream }), true)
|
||||
assert.equal(isCollectingSkillArtifacts({ artifactsCollecting: true }), true)
|
||||
assert.equal(
|
||||
isCollectingSkillArtifacts({ agentEventStream: stream, is_completed: true }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
isCollectingSkillArtifacts({
|
||||
agentEventStream: stream,
|
||||
artifacts: [{ file_name: 'chart.html' }],
|
||||
}),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
/** Tool that writes skill output into the session artifact directory. */
|
||||
export const EXECUTE_SKILL_SCRIPT_TOOL = 'execute_skill_script'
|
||||
|
||||
export type SkillArtifactStreamEvent = {
|
||||
tool_name?: string
|
||||
}
|
||||
|
||||
export type SkillArtifactSessionLike = {
|
||||
artifacts?: unknown[]
|
||||
is_completed?: boolean
|
||||
artifactsCollecting?: boolean
|
||||
agentEventStream?: SkillArtifactStreamEvent[]
|
||||
}
|
||||
|
||||
export function agentTurnUsedSkillScript(
|
||||
stream: SkillArtifactStreamEvent[] | null | undefined,
|
||||
): boolean {
|
||||
if (!Array.isArray(stream)) return false
|
||||
return stream.some((event) => event?.tool_name === EXECUTE_SKILL_SCRIPT_TOOL)
|
||||
}
|
||||
|
||||
/**
|
||||
* True while the assistant answer is already on screen but generated files
|
||||
* have not been persisted yet. The server uploads sandbox output after the
|
||||
* answer `done` event, so the toolbar would otherwise sit empty for seconds.
|
||||
*/
|
||||
export function isCollectingSkillArtifacts(
|
||||
session: SkillArtifactSessionLike | null | undefined,
|
||||
): boolean {
|
||||
if (!session) return false
|
||||
if (Array.isArray(session.artifacts) && session.artifacts.length > 0) return false
|
||||
if (session.is_completed) return false
|
||||
if (session.artifactsCollecting) return true
|
||||
return agentTurnUsedSkillScript(session.agentEventStream)
|
||||
}
|
||||
|
|
@ -340,13 +340,16 @@
|
|||
assistant message recorded any generated files. Agent
|
||||
mode is the primary path for skills, so this is where
|
||||
the button is most likely to appear. -->
|
||||
<span v-if="hasArtifacts" class="answer-toolbar__artifact">
|
||||
<span v-if="hasArtifacts || artifactsCollecting" class="answer-toolbar__artifact"
|
||||
:class="{ 'is-collecting': artifactButtonCollecting }">
|
||||
<t-button size="small" variant="outline" shape="round"
|
||||
@click.stop="openArtifactDrawer"
|
||||
:title="$t('agent.artifactDrawer.buttonTitle')">
|
||||
<t-icon name="download" />
|
||||
:disabled="artifactButtonCollecting"
|
||||
:title="hasArtifacts ? $t('agent.artifactDrawer.buttonTitle') : $t('agent.artifactDrawer.collecting')"
|
||||
@click.stop="openArtifactDrawer()">
|
||||
<t-icon v-if="artifactButtonCollecting" name="loading" class="answer-toolbar__artifact-spinner" />
|
||||
<t-icon v-else name="folder" />
|
||||
</t-button>
|
||||
<span class="answer-toolbar__artifact-count" aria-hidden="true">{{ artifactCount }}</span>
|
||||
<span v-if="hasArtifacts" class="answer-toolbar__artifact-count" aria-hidden="true">{{ artifactCount }}</span>
|
||||
</span>
|
||||
<t-tooltip v-if="event.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
|
||||
<t-button size="small" variant="outline" shape="round" class="fallback-icon-btn">
|
||||
|
|
@ -518,6 +521,7 @@
|
|||
:session-id="sessionIdForArtifacts"
|
||||
:message-id="messageIdForArtifacts"
|
||||
:artifacts="artifactList"
|
||||
:preview-index="artifactPreviewIndex"
|
||||
/>
|
||||
</template>
|
||||
|
||||
|
|
@ -533,6 +537,7 @@ import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
|
|||
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
|
||||
import picturePreview from '@/components/picture-preview.vue';
|
||||
import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
|
||||
import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';
|
||||
import ChatMemoryStep from './ChatMemoryStep.vue';
|
||||
import { useChatMemoryRow, type UsedMemory } from '@/composables/useChatMemoryRow';
|
||||
import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';
|
||||
|
|
@ -550,6 +555,11 @@ import { useAuthStore } from '@/stores/auth';
|
|||
import { useI18n } from 'vue-i18n';
|
||||
import i18n from '@/i18n';
|
||||
import { hydrateProtectedFileImages, clearProtectedFileFailureCache, sanitizeMarkdownHTML } from '@/utils/security';
|
||||
import {
|
||||
artifactIndexFromEventTarget,
|
||||
hydrateArtifactImages,
|
||||
renderArtifactReference,
|
||||
} from '@/utils/sandboxArtifactRefs';
|
||||
import type { ProtectedFileAccessContext } from '@/utils/protectedFileAccess';
|
||||
import { unwrapFinalAnswerWrappers, thinkingEqualsAnswer } from '@/utils/finalAnswer';
|
||||
import { getAgentToolIconName } from '@/utils/agent-tool-icons';
|
||||
|
|
@ -926,15 +936,33 @@ const artifactList = computed(() => {
|
|||
});
|
||||
const hasArtifacts = computed(() => artifactList.value.length > 0);
|
||||
const artifactCount = computed(() => artifactList.value.length);
|
||||
const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session as any));
|
||||
const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value);
|
||||
const sessionIdForArtifacts = computed(() => props.sessionId ?? '');
|
||||
const messageIdForArtifacts = computed(() =>
|
||||
String(props.session?.id || props.session?.request_id || ''),
|
||||
);
|
||||
function openArtifactDrawer() {
|
||||
// Set when the drawer is opened from an inline artifact card in the answer, so
|
||||
// it lands on that file's preview instead of the list.
|
||||
const artifactPreviewIndex = ref<number | null>(null);
|
||||
function openArtifactDrawer(previewIndex: number | null = null) {
|
||||
if (!hasArtifacts.value) return;
|
||||
artifactPreviewIndex.value = previewIndex;
|
||||
showArtifactDrawer.value = true;
|
||||
}
|
||||
|
||||
const artifactRefContext = computed(() => {
|
||||
const sessionId = sessionIdForArtifacts.value;
|
||||
const messageId = messageIdForArtifacts.value;
|
||||
if (!sessionId || !messageId) return null;
|
||||
return { sessionId, messageId };
|
||||
});
|
||||
|
||||
const artifactRefLabels = computed(() => ({
|
||||
previewHint: t('agent.artifactDrawer.inlinePreviewHint'),
|
||||
missingHint: t('agent.artifactDrawer.inlineMissing'),
|
||||
}));
|
||||
|
||||
const {
|
||||
float: citationFloat,
|
||||
rebind: rebindCitations,
|
||||
|
|
@ -2170,6 +2198,15 @@ const onRootClick = (e: Event) => {
|
|||
const target = e.target as HTMLElement;
|
||||
if (!target) return;
|
||||
|
||||
// Inline artifact card -> open the drawer straight on that file's preview.
|
||||
const artifactIndex = artifactIndexFromEventTarget(target);
|
||||
if (artifactIndex !== null) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openArtifactDrawer(artifactIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle image clicks -> open preview (only for images inside markdown/answer content, not icons)
|
||||
if (target.tagName === 'IMG') {
|
||||
const imgEl = target as HTMLImageElement;
|
||||
|
|
@ -2258,6 +2295,15 @@ const onRootKeydown = (e: KeyboardEvent) => {
|
|||
const target = e.target as HTMLElement;
|
||||
if (!target) return;
|
||||
|
||||
const artifactIndex = artifactIndexFromEventTarget(target);
|
||||
if (artifactIndex !== null) {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
openArtifactDrawer(artifactIndex);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle web citation keyboard
|
||||
const webEl = target.closest?.('.citation-web') as HTMLElement | null;
|
||||
if (webEl) {
|
||||
|
|
@ -2329,6 +2375,7 @@ onMounted(() => {
|
|||
root.addEventListener('keydown', keydownListener, true);
|
||||
rebindCitations();
|
||||
await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value);
|
||||
await hydrateArtifactImages(rootElement.value, artifactRefContext.value);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -2353,6 +2400,7 @@ onUpdated(() => {
|
|||
// de-duped, and failures back off for a cooldown — so a not-yet-ready file
|
||||
// simply retries later (and the answerFullyRendered pass is the backstop).
|
||||
await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value);
|
||||
await hydrateArtifactImages(rootElement.value, artifactRefContext.value);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -2360,6 +2408,25 @@ onUpdated(() => {
|
|||
const agentRenderer = new marked.Renderer();
|
||||
agentRenderer.code = createMermaidCodeRenderer('mermaid-agent');
|
||||
|
||||
// Files the agent generated in its sandbox carry the same `resource://` handle
|
||||
// as any other stored file, so they are matched against this reply's artifacts
|
||||
// before marked's default <img>. Everything else — including a handle that
|
||||
// belongs to a knowledge-base image rather than to this reply — keeps the
|
||||
// default output, which protectProviderImageSrcInHTML still rewrites.
|
||||
const defaultImageRenderer = new marked.Renderer().image;
|
||||
agentRenderer.image = function agentImageRenderer(token) {
|
||||
const artifactHtml = renderArtifactReference({
|
||||
href: token.href || '',
|
||||
alt: token.text || '',
|
||||
artifacts: artifactList.value,
|
||||
labels: artifactRefLabels.value,
|
||||
context: artifactRefContext.value,
|
||||
streaming: !isConversationDone.value,
|
||||
});
|
||||
if (artifactHtml !== null) return artifactHtml;
|
||||
return defaultImageRenderer.call(this, token);
|
||||
};
|
||||
|
||||
const prepareAgentMarkdown = (markdown: string, cachedSvgHtml?: string | null): string => {
|
||||
const mermaidSafe = !isConversationDone.value
|
||||
? prepareStreamingMermaidMarkdown(markdown, cachedSvgHtml ?? streamingMermaidSvgCache.value)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
<template>
|
||||
<!--
|
||||
ChatArtifactsDrawer — right-side drawer that lists every skill-generated
|
||||
file attached to the surrounding assistant message.
|
||||
file attached to the surrounding assistant message, and opens an inline
|
||||
preview that reuses DocumentPreview (same renderer as knowledge files
|
||||
and chat attachments).
|
||||
|
||||
Usage (from botmsg.vue / AgentStreamDisplay.vue):
|
||||
<ChatArtifactsDrawer
|
||||
|
|
@ -10,32 +12,92 @@
|
|||
:message-id="messageId"
|
||||
:artifacts="artifacts"
|
||||
/>
|
||||
|
||||
The list is driven by whatever the parent has already resolved from
|
||||
the streamed message payload. When the parent has no local copy
|
||||
(e.g. after a page refresh) it can pass an empty array and the
|
||||
drawer will pull the metadata itself via /artifacts.
|
||||
-->
|
||||
<teleport to="body">
|
||||
<div
|
||||
v-if="previewResizing"
|
||||
class="artifact-preview-resize-overlay"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
v-if="internalVisible && previewItem"
|
||||
class="artifact-preview-resize-handle"
|
||||
:class="{ 'artifact-preview-resize-handle--active': previewResizing }"
|
||||
:style="{ right: `${previewWidth}px` }"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
@mousedown.prevent="onPreviewResizeStart"
|
||||
>
|
||||
<div class="artifact-preview-resize-line" />
|
||||
</div>
|
||||
</teleport>
|
||||
|
||||
<t-drawer
|
||||
v-model:visible="internalVisible"
|
||||
class="chat-artifacts-drawer"
|
||||
:class="{ 'chat-artifacts-drawer--preview': !!previewItem, 'chat-artifacts-drawer--resizing': previewResizing }"
|
||||
placement="right"
|
||||
size="440px"
|
||||
:size="drawerSize"
|
||||
:z-index="previewItem ? 2000 : 1500"
|
||||
attach="body"
|
||||
:footer="false"
|
||||
:close-on-overlay-click="true"
|
||||
:close-on-esc-keydown="true"
|
||||
:destroy-on-close="false"
|
||||
@close="handleClose"
|
||||
>
|
||||
<template #header>
|
||||
<div class="artifact-drawer-header">
|
||||
<div v-if="previewItem" class="artifact-drawer-header artifact-drawer-header--preview">
|
||||
<t-button
|
||||
class="artifact-back"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('agent.artifactDrawer.previewBack')"
|
||||
:aria-label="$t('agent.artifactDrawer.previewBack')"
|
||||
@click="closePreview"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="chevron-left" size="18px" />
|
||||
</template>
|
||||
</t-button>
|
||||
<div class="artifact-drawer-header-icon">
|
||||
<t-icon name="file" />
|
||||
<t-icon :name="getFileIcon(previewItem.file_name)" />
|
||||
</div>
|
||||
<div class="artifact-drawer-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>
|
||||
<t-button
|
||||
class="artifact-download"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('agent.artifactDrawer.download')"
|
||||
:loading="!!downloading[previewItem.index]"
|
||||
@click="handleDownload(previewItem)"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="download" size="16px" />
|
||||
</template>
|
||||
</t-button>
|
||||
</div>
|
||||
<div v-else class="artifact-drawer-header">
|
||||
<div class="artifact-drawer-header-icon">
|
||||
<t-icon name="folder" />
|
||||
</div>
|
||||
<div class="artifact-drawer-header-title">{{ $t('agent.artifactDrawer.title') }}</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="loading" class="artifact-drawer-empty">
|
||||
<div v-if="previewItem" class="artifact-preview-body">
|
||||
<DocumentPreview
|
||||
:session-id="sessionId"
|
||||
:message-id="messageId"
|
||||
:artifact-index="previewItem.index"
|
||||
:file-type="previewFileType"
|
||||
:file-name="previewItem.file_name"
|
||||
:active="internalVisible"
|
||||
fill-height
|
||||
/>
|
||||
</div>
|
||||
<div v-else-if="loading" class="artifact-drawer-empty">
|
||||
<t-loading size="small" />
|
||||
<span>{{ $t('common.loading') }}</span>
|
||||
</div>
|
||||
|
|
@ -44,7 +106,12 @@
|
|||
<span>{{ $t('agent.artifactDrawer.empty') }}</span>
|
||||
</div>
|
||||
<ul v-else class="artifact-list">
|
||||
<li v-for="item in items" :key="`${item.index}-${item.file_name}`" class="artifact-item">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="`${item.index}-${item.file_name}`"
|
||||
class="artifact-item is-previewable"
|
||||
@click="openPreview(item)"
|
||||
>
|
||||
<span class="artifact-icon">
|
||||
<t-icon :name="getFileIcon(item.file_name)" />
|
||||
</span>
|
||||
|
|
@ -56,6 +123,18 @@
|
|||
<span>{{ formatDateTime(item.created_at) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<t-button
|
||||
class="artifact-preview-btn"
|
||||
variant="text"
|
||||
shape="square"
|
||||
size="small"
|
||||
:title="$t('agent.artifactDrawer.preview')"
|
||||
@click.stop="openPreview(item)"
|
||||
>
|
||||
<template #icon>
|
||||
<t-icon name="browse" size="16px" />
|
||||
</template>
|
||||
</t-button>
|
||||
<t-button
|
||||
class="artifact-download"
|
||||
variant="text"
|
||||
|
|
@ -81,24 +160,43 @@
|
|||
* the chat API's downloadArtifact() helper which uses the axios blob
|
||||
* transport (getDown) so the Bearer token stays attached — plain
|
||||
* <a href> would drop it and hit 401.
|
||||
* - Preview reuses DocumentPreview so HTML charts, CSV tables, PDFs,
|
||||
* images, office docs, audio/video, mermaid, and unlabeled text all
|
||||
* go through the same renderer as knowledge-file / attachment preview.
|
||||
* - `items` prefers the props-provided list (already in memory from the
|
||||
* stream payload). When empty, we pull from /artifacts on open so a
|
||||
* refreshed page still shows something without waiting for the parent
|
||||
* to re-hydrate.
|
||||
* - Errors during download are surfaced via MessagePlugin.error but do
|
||||
* NOT close the drawer, matching spec §7: "抽屉保持打开以便重试其他文件".
|
||||
* - Overlay / Esc while a file is previewed pop back to the list (same as
|
||||
* the header chevron). TDesign still emits update:visible=false after
|
||||
* @close, so we swallow that one emit; the header X still closes all.
|
||||
*/
|
||||
import { computed, ref, watch, reactive } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch, reactive } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { downloadArtifact, listMessageArtifacts, type ArtifactMeta } from '@/api/chat'
|
||||
import { getFileIcon } from '@/utils/files'
|
||||
import { resolveFilePreviewExt } from '@/utils/filePreview'
|
||||
import DocumentPreview from '@/components/document-preview.vue'
|
||||
|
||||
const LIST_WIDTH = 440
|
||||
const PREVIEW_WIDTH_KEY = 'weknora-chat-artifact-preview-width'
|
||||
const PREVIEW_DEFAULT_WIDTH = 760
|
||||
const PREVIEW_MIN_WIDTH = 520
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
sessionId: string
|
||||
messageId: string
|
||||
artifacts?: ArtifactMeta[]
|
||||
/**
|
||||
* Open straight into this artifact's preview instead of the list. Set when
|
||||
* the drawer is opened by clicking an inline artifact card in the answer,
|
||||
* where the user already picked the file.
|
||||
*/
|
||||
previewIndex?: number | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
|
|
@ -107,32 +205,121 @@ const emit = defineEmits<{
|
|||
|
||||
const { t } = useI18n()
|
||||
|
||||
// Two-way binding shim so `v-model:visible` works while the parent still
|
||||
// owns the source of truth.
|
||||
/** TDesign always follows @close with update:visible=false; swallow that when popping preview. */
|
||||
let suppressDrawerClose = false
|
||||
|
||||
const internalVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: (v: boolean) => emit('update:visible', v),
|
||||
set: (v: boolean) => {
|
||||
if (!v && suppressDrawerClose) {
|
||||
suppressDrawerClose = false
|
||||
return
|
||||
}
|
||||
emit('update:visible', v)
|
||||
},
|
||||
})
|
||||
|
||||
const loading = ref(false)
|
||||
const fetched = ref<ArtifactMeta[]>([])
|
||||
const downloading = reactive<Record<number, boolean>>({})
|
||||
const previewItem = ref<ArtifactMeta | null>(null)
|
||||
// Opening the drawer from an inline artifact card jumps straight to the
|
||||
// preview, so there is no list behind it to pop back to — overlay/Esc should
|
||||
// dismiss the whole drawer. Coming from the list, they pop back to it.
|
||||
const previewOpenedDirectly = ref(false)
|
||||
const previewWidth = ref(PREVIEW_DEFAULT_WIDTH)
|
||||
const previewResizing = ref(false)
|
||||
|
||||
let previewResizeStartX = 0
|
||||
let previewResizeStartWidth = 0
|
||||
|
||||
const items = computed<ArtifactMeta[]>(() => {
|
||||
if (props.artifacts && props.artifacts.length) return props.artifacts
|
||||
return fetched.value
|
||||
})
|
||||
|
||||
// Refresh /artifacts when the drawer opens without a caller-provided list.
|
||||
// Cheap when the caller already passed artifacts; a real request only when
|
||||
// the parent's copy is empty (e.g. right after page refresh, before message
|
||||
// hydration finishes).
|
||||
const previewFileType = computed(() => {
|
||||
const item = previewItem.value
|
||||
if (!item) return ''
|
||||
return resolveFilePreviewExt(item.file_name, item.file_type)
|
||||
})
|
||||
|
||||
const drawerSize = computed(() => (
|
||||
previewItem.value ? `${previewWidth.value}px` : `${LIST_WIDTH}px`
|
||||
))
|
||||
|
||||
function previewMaxWidth() {
|
||||
return Math.min(1600, Math.max(PREVIEW_MIN_WIDTH, Math.floor(window.innerWidth * 0.95)))
|
||||
}
|
||||
|
||||
function clampPreviewWidth(width: number) {
|
||||
return Math.max(PREVIEW_MIN_WIDTH, Math.min(previewMaxWidth(), width))
|
||||
}
|
||||
|
||||
function loadPreviewWidth() {
|
||||
try {
|
||||
const raw = localStorage.getItem(PREVIEW_WIDTH_KEY)
|
||||
const parsed = raw ? parseInt(raw, 10) : NaN
|
||||
if (!Number.isNaN(parsed)) {
|
||||
previewWidth.value = clampPreviewWidth(parsed)
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function onPreviewResizeStart(e: MouseEvent) {
|
||||
previewResizing.value = true
|
||||
previewResizeStartX = e.clientX
|
||||
previewResizeStartWidth = previewWidth.value
|
||||
document.addEventListener('mousemove', onPreviewResizeMove)
|
||||
document.addEventListener('mouseup', onPreviewResizeEnd)
|
||||
document.body.style.cursor = 'col-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
}
|
||||
|
||||
function onPreviewResizeMove(e: MouseEvent) {
|
||||
const delta = previewResizeStartX - e.clientX
|
||||
previewWidth.value = clampPreviewWidth(previewResizeStartWidth + delta)
|
||||
}
|
||||
|
||||
function onPreviewResizeEnd() {
|
||||
document.removeEventListener('mousemove', onPreviewResizeMove)
|
||||
document.removeEventListener('mouseup', onPreviewResizeEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
previewResizing.value = false
|
||||
try {
|
||||
localStorage.setItem(PREVIEW_WIDTH_KEY, String(previewWidth.value))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupPreviewResize() {
|
||||
document.removeEventListener('mousemove', onPreviewResizeMove)
|
||||
document.removeEventListener('mouseup', onPreviewResizeEnd)
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
previewResizing.value = false
|
||||
}
|
||||
|
||||
function onWindowResize() {
|
||||
previewWidth.value = clampPreviewWidth(previewWidth.value)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
async (open) => {
|
||||
if (!open) return
|
||||
if (!open) {
|
||||
suppressDrawerClose = false
|
||||
previewItem.value = null
|
||||
previewOpenedDirectly.value = false
|
||||
return
|
||||
}
|
||||
if (props.artifacts && props.artifacts.length) {
|
||||
fetched.value = []
|
||||
applyRequestedPreview()
|
||||
return
|
||||
}
|
||||
if (!props.sessionId || !props.messageId) return
|
||||
|
|
@ -141,6 +328,7 @@ watch(
|
|||
const res: any = await listMessageArtifacts(props.sessionId, props.messageId)
|
||||
const data = (res && (res.data || res)) as ArtifactMeta[] | undefined
|
||||
fetched.value = Array.isArray(data) ? data : []
|
||||
applyRequestedPreview()
|
||||
} catch (err) {
|
||||
console.error('[ChatArtifactsDrawer] load failed:', err)
|
||||
fetched.value = []
|
||||
|
|
@ -150,10 +338,43 @@ watch(
|
|||
},
|
||||
)
|
||||
|
||||
function handleClose() {
|
||||
// Clicking a second inline card while the drawer is already open should swap
|
||||
// the preview rather than leave the previous file on screen.
|
||||
watch(() => props.previewIndex, () => {
|
||||
if (props.visible) applyRequestedPreview()
|
||||
})
|
||||
|
||||
function applyRequestedPreview() {
|
||||
if (!Number.isInteger(props.previewIndex as number)) return
|
||||
const target = items.value.find((item) => item.index === props.previewIndex)
|
||||
if (!target) return
|
||||
previewItem.value = target
|
||||
previewOpenedDirectly.value = true
|
||||
}
|
||||
|
||||
function handleClose(context?: { trigger?: string }) {
|
||||
const dismissedFromOutside = context?.trigger === 'overlay' || context?.trigger === 'esc'
|
||||
const popPreview = !!previewItem.value && !previewOpenedDirectly.value && dismissedFromOutside
|
||||
if (popPreview) {
|
||||
closePreview()
|
||||
suppressDrawerClose = true
|
||||
return
|
||||
}
|
||||
previewItem.value = null
|
||||
previewOpenedDirectly.value = false
|
||||
emit('update:visible', false)
|
||||
}
|
||||
|
||||
function openPreview(item: ArtifactMeta) {
|
||||
previewItem.value = item
|
||||
previewOpenedDirectly.value = false
|
||||
}
|
||||
|
||||
function closePreview() {
|
||||
previewItem.value = null
|
||||
previewOpenedDirectly.value = false
|
||||
}
|
||||
|
||||
function formatFileSize(size: number): string {
|
||||
if (!size || size < 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB']
|
||||
|
|
@ -182,9 +403,6 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
downloading[item.index] = true
|
||||
try {
|
||||
const blob = await downloadArtifact(props.sessionId, props.messageId, item.index)
|
||||
// Trigger browser save via an object URL so the file name comes
|
||||
// through even when the server's Content-Disposition is stripped
|
||||
// by an intermediate proxy.
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
|
|
@ -192,7 +410,6 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
// Give the browser a tick to start the download before revoking.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (err) {
|
||||
console.error('[ChatArtifactsDrawer] download failed:', err)
|
||||
|
|
@ -201,6 +418,16 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
downloading[item.index] = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadPreviewWidth()
|
||||
window.addEventListener('resize', onWindowResize)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('resize', onWindowResize)
|
||||
cleanupPreviewResize()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
|
|
@ -213,6 +440,19 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
padding-right: 32px;
|
||||
}
|
||||
|
||||
.artifact-drawer-header--preview {
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
.artifact-back {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
||||
:deep(.t-button__icon) {
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.artifact-drawer-header-icon {
|
||||
flex-shrink: 0;
|
||||
width: 32px;
|
||||
|
|
@ -228,6 +468,7 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
|
||||
.artifact-drawer-header-title {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
|
|
@ -237,6 +478,14 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.artifact-preview-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.artifact-drawer-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
|
@ -260,11 +509,20 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
gap: 10px;
|
||||
padding: 10px 4px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
border-radius: 8px;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&.is-previewable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--td-bg-color-container-hover);
|
||||
}
|
||||
|
||||
&:hover .artifact-icon {
|
||||
color: var(--td-brand-color);
|
||||
}
|
||||
|
|
@ -314,6 +572,7 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.artifact-preview-btn,
|
||||
.artifact-download {
|
||||
flex-shrink: 0;
|
||||
color: var(--td-text-color-secondary);
|
||||
|
|
@ -322,6 +581,41 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.artifact-preview-resize-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2001;
|
||||
cursor: col-resize;
|
||||
}
|
||||
|
||||
.artifact-preview-resize-handle {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 12px;
|
||||
margin-left: -6px;
|
||||
z-index: 2002;
|
||||
cursor: col-resize;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.artifact-preview-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;
|
||||
}
|
||||
|
||||
.artifact-preview-resize-handle:hover .artifact-preview-resize-line,
|
||||
.artifact-preview-resize-handle--active .artifact-preview-resize-line {
|
||||
opacity: 1;
|
||||
background: var(--td-brand-color);
|
||||
}
|
||||
</style>
|
||||
|
||||
<style lang="less">
|
||||
|
|
@ -335,4 +629,41 @@ async function handleDownload(item: ArtifactMeta) {
|
|||
padding: 4px 20px 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.t-drawer.chat-artifacts-drawer--preview {
|
||||
.t-drawer__content-wrapper,
|
||||
.t-drawer__content {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.t-drawer__header {
|
||||
padding: 14px 18px;
|
||||
border-bottom: 1px solid var(--td-component-stroke);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.t-drawer__body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
padding: 12px 16px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.t-drawer.chat-artifacts-drawer--resizing .t-drawer__content {
|
||||
transition: none !important;
|
||||
}
|
||||
|
||||
.t-drawer.chat-artifacts-drawer--resizing {
|
||||
.artifact-preview-body,
|
||||
.document-preview,
|
||||
iframe,
|
||||
.pdf-iframe,
|
||||
.html-iframe {
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -23,17 +23,28 @@ test('agent actions reuse the fully-rendered answer state', () => {
|
|||
assert.match(agentStream, /v-if="answerFullyRendered && event\.done/)
|
||||
})
|
||||
|
||||
test('artifact download uses a muted count overlay instead of t-badge', () => {
|
||||
test('artifact count is a top-right overlay instead of t-badge', () => {
|
||||
assert.match(botMessage, /class="answer-toolbar__artifact"/)
|
||||
assert.match(agentStream, /class="answer-toolbar__artifact"/)
|
||||
assert.match(botMessage, /class="answer-toolbar__artifact-count"/)
|
||||
assert.match(agentStream, /class="answer-toolbar__artifact-count"/)
|
||||
assert.match(sharedStyles, /answer-toolbar__artifact-count/)
|
||||
assert.match(sharedStyles, /position: absolute/)
|
||||
assert.match(sharedStyles, /td-bg-color-secondarycontainer/)
|
||||
assert.doesNotMatch(botMessage, /<t-badge/)
|
||||
assert.doesNotMatch(agentStream, /<t-badge/)
|
||||
})
|
||||
|
||||
test('artifact toolbar uses a folder icon and replaces it while collecting', () => {
|
||||
assert.match(botMessage, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/)
|
||||
assert.match(agentStream, /answer-toolbar__artifact[\s\S]{0,800}name="folder"/)
|
||||
assert.match(botMessage, /class="answer-toolbar__artifact-spinner"/)
|
||||
assert.match(agentStream, /class="answer-toolbar__artifact-spinner"/)
|
||||
assert.match(sharedStyles, /answer-toolbar-artifact-spin/)
|
||||
assert.doesNotMatch(botMessage, /answer-toolbar__artifact[\s\S]{0,800}:loading=/)
|
||||
assert.doesNotMatch(agentStream, /answer-toolbar__artifact[\s\S]{0,800}:loading=/)
|
||||
})
|
||||
|
||||
test('follow-up loading is shown compactly inside both answer toolbars', () => {
|
||||
assert.match(chatView, /:follow-up-loading="Boolean\(session\.suggestionLoading/)
|
||||
assert.match(botMessage, /class="answer-toolbar__follow-up-loading"/)
|
||||
|
|
|
|||
|
|
@ -56,13 +56,16 @@
|
|||
assistant message actually recorded any generated files.
|
||||
Emptiness is the default: the button stays hidden for
|
||||
conversational messages that never touched a skill. -->
|
||||
<span v-if="hasArtifacts" class="answer-toolbar__artifact">
|
||||
<span v-if="hasArtifacts || artifactsCollecting" class="answer-toolbar__artifact"
|
||||
:class="{ 'is-collecting': artifactButtonCollecting }">
|
||||
<t-button size="small" variant="outline" shape="round"
|
||||
@click.stop="openArtifactDrawer"
|
||||
:title="$t('agent.artifactDrawer.buttonTitle')">
|
||||
<t-icon name="download" />
|
||||
:disabled="artifactButtonCollecting"
|
||||
:title="hasArtifacts ? $t('agent.artifactDrawer.buttonTitle') : $t('agent.artifactDrawer.collecting')"
|
||||
@click.stop="openArtifactDrawer()">
|
||||
<t-icon v-if="artifactButtonCollecting" name="loading" class="answer-toolbar__artifact-spinner" />
|
||||
<t-icon v-else name="folder" />
|
||||
</t-button>
|
||||
<span class="answer-toolbar__artifact-count" aria-hidden="true">{{ artifactCount }}</span>
|
||||
<span v-if="hasArtifacts" class="answer-toolbar__artifact-count" aria-hidden="true">{{ artifactCount }}</span>
|
||||
</span>
|
||||
<!-- Fallback 提示图标 -->
|
||||
<t-tooltip v-if="session.is_fallback" :content="$t('chat.fallbackHint')" placement="top">
|
||||
|
|
@ -93,6 +96,7 @@
|
|||
:session-id="sessionId"
|
||||
:message-id="messageIdForArtifacts"
|
||||
:artifacts="artifactList"
|
||||
:preview-index="artifactPreviewIndex"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -107,7 +111,14 @@ import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
|
|||
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
|
||||
import picturePreview from '@/components/picture-preview.vue';
|
||||
import ChatArtifactsDrawer from './ChatArtifactsDrawer.vue';
|
||||
import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';
|
||||
import { sanitizeMarkdownHTML, safeMarkdownToHTML, createSafeImage, isValidImageURL, hydrateProtectedFileImages } from '@/utils/security';
|
||||
import {
|
||||
artifactIndexFromEventTarget,
|
||||
hydrateArtifactImages,
|
||||
isArtifactRefHref,
|
||||
renderArtifactReference,
|
||||
} from '@/utils/sandboxArtifactRefs';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import { useUIStore } from '@/stores/ui';
|
||||
|
|
@ -216,16 +227,33 @@ const artifactList = computed(() => {
|
|||
});
|
||||
const hasArtifacts = computed(() => artifactList.value.length > 0);
|
||||
const artifactCount = computed(() => artifactList.value.length);
|
||||
const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session));
|
||||
const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value);
|
||||
const messageIdForArtifacts = computed(() => {
|
||||
// Prefer the persistent message ID; fall back to request_id for the
|
||||
// in-flight path where the SSE stream still identifies rows by request.
|
||||
return String((props.session && (props.session.id || props.session.request_id)) || '');
|
||||
});
|
||||
function openArtifactDrawer() {
|
||||
// Set when the drawer is opened by clicking an inline artifact card, so it
|
||||
// lands directly on that file's preview instead of the list.
|
||||
const artifactPreviewIndex = ref(null);
|
||||
function openArtifactDrawer(previewIndex = null) {
|
||||
if (!hasArtifacts.value) return;
|
||||
artifactPreviewIndex.value = previewIndex;
|
||||
showArtifactDrawer.value = true;
|
||||
}
|
||||
|
||||
const artifactRefContext = computed(() => {
|
||||
const messageId = messageIdForArtifacts.value;
|
||||
if (!props.sessionId || !messageId) return null;
|
||||
return { sessionId: props.sessionId, messageId };
|
||||
});
|
||||
|
||||
const artifactRefLabels = computed(() => ({
|
||||
previewHint: t('agent.artifactDrawer.inlinePreviewHint'),
|
||||
missingHint: t('agent.artifactDrawer.inlineMissing'),
|
||||
}));
|
||||
|
||||
const preview = (url) => {
|
||||
nextTick(() => {
|
||||
reviewUrl.value = url;
|
||||
|
|
@ -240,9 +268,24 @@ const closePreImg = () => {
|
|||
|
||||
const markdownRenderer = createChatMarkdownRenderer({
|
||||
codeRenderer: createMermaidCodeRenderer('mermaid-botmsg'),
|
||||
imageRenderer: ({ href, title, text }) => createSafeImage(href, text || '', title || ''),
|
||||
imageRenderer: ({ href, title, text }) => {
|
||||
// A sandbox-generated file shares the resource:// form with every other
|
||||
// protected image, so it is matched against this message's artifacts
|
||||
// first. Anything that does not belong to this reply falls through to
|
||||
// the ordinary protected-image path.
|
||||
const artifactHtml = renderArtifactReference({
|
||||
href,
|
||||
alt: text || '',
|
||||
artifacts: artifactList.value,
|
||||
labels: artifactRefLabels.value,
|
||||
context: artifactRefContext.value,
|
||||
streaming: !props.session?.is_completed,
|
||||
});
|
||||
if (artifactHtml !== null) return artifactHtml;
|
||||
return createSafeImage(href, text || '', title || '');
|
||||
},
|
||||
invalidImageHtml: () => `<p>${t('error.invalidImageLink')}</p>`,
|
||||
isValidImageUrl: isValidImageURL,
|
||||
isValidImageUrl: (href) => isArtifactRefHref(href) || isValidImageURL(href),
|
||||
});
|
||||
|
||||
// 计算属性:将 Markdown 文本转换为 tokens
|
||||
|
|
@ -336,6 +379,13 @@ const handleAddToKnowledge = () => {
|
|||
// 处理 markdown-content 中图片的点击事件
|
||||
const handleMarkdownImageClick = (e) => {
|
||||
const target = e.target;
|
||||
const artifactIndex = artifactIndexFromEventTarget(target);
|
||||
if (artifactIndex !== null) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openArtifactDrawer(artifactIndex);
|
||||
return;
|
||||
}
|
||||
if (target && target.tagName === 'IMG') {
|
||||
const src = target.getAttribute('src');
|
||||
if (src) {
|
||||
|
|
@ -356,6 +406,7 @@ watch(renderedHTML, () => {
|
|||
onUpdated(() => {
|
||||
nextTick(async () => {
|
||||
await hydrateProtectedFileImages(parentMd.value);
|
||||
await hydrateArtifactImages(parentMd.value, artifactRefContext.value);
|
||||
refreshMarkdownEnhancements(parentMd.value);
|
||||
if (props.session?.is_completed) {
|
||||
await renderMermaidInContainer(parentMd.value);
|
||||
|
|
@ -371,6 +422,7 @@ onMounted(async () => {
|
|||
}
|
||||
rebindCitations();
|
||||
await hydrateProtectedFileImages(parentMd.value);
|
||||
await hydrateArtifactImages(parentMd.value, artifactRefContext.value);
|
||||
await enhanceMarkdownContainer(parentMd.value);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -259,6 +259,11 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata, shellExecEnabl
|
|||
builder.WriteString(" - `input`: Pass data directly via stdin (use this when you have data in memory, e.g. JSON string)\n")
|
||||
builder.WriteString(" - `args`: Command-line arguments; pass absolute `/workspace/input/...` paths from `<sandbox_attachments>` for user-uploaded files\n")
|
||||
builder.WriteString(" - Treat `/workspace/input` as read-only and write generated files only to `$WEKNORA_SKILL_OUTPUT_DIR`\n")
|
||||
builder.WriteString(sandboxArtifactReferenceGuidance())
|
||||
builder.WriteString(" - Each skill keeps its dependencies to itself (virtualenv or node_modules); ")
|
||||
builder.WriteString("this tool already runs scripts the right way. A bare `python3 -c` / `node -e` ")
|
||||
builder.WriteString("sees none of them, so never conclude from that that a skill cannot run, and ")
|
||||
builder.WriteString("never reinstall a skill's dependencies — they would live in this session only\n")
|
||||
if shellExecEnabled {
|
||||
builder.WriteString("- `shell_exec(command, work_dir, timeout_sec, max_output_bytes, max_stderr_bytes, env)`: Freely execute shell commands and explore the current session's isolated Cube sandbox\n")
|
||||
builder.WriteString(" - User-uploaded files are restored under `/workspace/input` and listed in `<sandbox_attachments>`\n")
|
||||
|
|
@ -273,6 +278,26 @@ func formatSkillsMetadata(skillsMetadata []*skills.SkillMetadata, shellExecEnabl
|
|||
return builder.String()
|
||||
}
|
||||
|
||||
// sandboxArtifactReferenceGuidance tells the model how to point at a file it
|
||||
// generated in the sandbox from its final answer.
|
||||
//
|
||||
// Without this, models improvise a Markdown image with the bare file name
|
||||
// (``), which the browser cannot resolve — the answer
|
||||
// renders a broken image icon. The `sandbox:` prefix makes the intent explicit
|
||||
// so the server can bind the name to the artifact index it hands the client.
|
||||
func sandboxArtifactReferenceGuidance() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(" - To show a generated file inside your answer, reference it as ")
|
||||
builder.WriteString("`` using the exact file name and no directory path\n")
|
||||
builder.WriteString(" - Images render inline; charts, tables, and documents ")
|
||||
builder.WriteString("render as a card the user clicks to preview\n")
|
||||
builder.WriteString(" - Never reference a sandbox path (`/workspace/output/...`) ")
|
||||
builder.WriteString("or a bare file name directly — neither resolves in the browser\n")
|
||||
builder.WriteString(" - Prefer output file names without spaces or parentheses; ")
|
||||
builder.WriteString("they keep the reference unambiguous\n")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// renderPromptPlaceholdersWithStatus renders placeholders including web search status
|
||||
// Supported placeholders:
|
||||
// - {{knowledge_bases}}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ const artifactHistoryEnvVar = "WEKNORA_SKILL_HISTORY_ROOT"
|
|||
// skillDirEnvVar points a script at its own directory inside the sandbox
|
||||
// image. Installed skills run with /workspace as WorkDir, so this is how a
|
||||
// script reaches the data and helpers that were installed beside it. The
|
||||
// install-time smoke run exports the same name.
|
||||
// install-time verification pass exports the same name.
|
||||
const skillDirEnvVar = "WEKNORA_SKILL_DIR"
|
||||
|
||||
// defaultArtifactOutputDir is used when neither the environment variable
|
||||
|
|
@ -269,6 +269,29 @@ func (m *Manager) ListSkillFiles(ctx context.Context, skillName string) ([]strin
|
|||
return m.resolveSource(skillName).ListSkillFiles(skillName)
|
||||
}
|
||||
|
||||
// SandboxSkillDir reports where a skill lives inside the sandbox image, and
|
||||
// whether that path means anything to say out loud.
|
||||
//
|
||||
// Only an installed skill has one. A preloaded skill is uploaded from the host
|
||||
// for the duration of a single call, so its base path names a directory on the
|
||||
// WeKnora machine that no shell command in the sandbox can reach — telling the
|
||||
// model about it would be worse than saying nothing.
|
||||
func (m *Manager) SandboxSkillDir(skillName string) (string, bool) {
|
||||
if m == nil || !m.enabled || !m.isSkillAllowed(skillName) {
|
||||
return "", false
|
||||
}
|
||||
image, ok := m.resolveSource(skillName).(imageSkillSource)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
dir, err := image.GetSkillBasePath(skillName)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
dir = strings.TrimSpace(dir)
|
||||
return dir, dir != ""
|
||||
}
|
||||
|
||||
// ExecuteScript executes a script from a skill in the sandbox
|
||||
func (m *Manager) ExecuteScript(ctx context.Context, skillName, scriptPath string, args []string, stdin string) (*sandbox.ExecuteResult, error) {
|
||||
if !m.enabled {
|
||||
|
|
@ -377,9 +400,9 @@ func buildSkillExecuteConfig(
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The install-time smoke run exports the skill directory under this name,
|
||||
// so a script that located its own resources through it during
|
||||
// verification must be able to do the same when the agent calls it.
|
||||
// The install-time verification pass exports the skill directory under
|
||||
// this name, so the environment a script is checked in is the environment
|
||||
// it is later called in.
|
||||
env[skillDirEnvVar] = basePath
|
||||
return &sandbox.ExecuteConfig{
|
||||
RemoteScriptPath: remoteScript,
|
||||
|
|
|
|||
|
|
@ -248,6 +248,31 @@ func TestManagerRunsATenantSkillFromTheImageWithoutUploading(t *testing.T) {
|
|||
require.Equal(t, "/workspace/output", sandboxMgr.config.Env[artifactOutputEnvVar])
|
||||
}
|
||||
|
||||
// The in-sandbox directory is what read_skill shows the model so it can name
|
||||
// the skill's own interpreter instead of probing the system python3. A
|
||||
// preloaded skill has no such directory: its base path is on the WeKnora host,
|
||||
// which no command in the sandbox can reach.
|
||||
func TestSandboxSkillDirOnlyAnswersForInstalledSkills(t *testing.T) {
|
||||
installed := NewManager(&ManagerConfig{Enabled: true}, nil)
|
||||
installed.WithTenantSource(NewTenantSkillSource([]*types.TenantSkillEntity{{
|
||||
ID: "sk-1", Name: "pdf", Status: types.SkillStatusReady, Enabled: true,
|
||||
}}, nil))
|
||||
require.NoError(t, installed.Initialize(context.Background()))
|
||||
|
||||
dir, ok := installed.SandboxSkillDir("pdf")
|
||||
require.True(t, ok)
|
||||
require.Equal(t, sandbox.SkillsImageRoot+"/pdf", dir)
|
||||
|
||||
preloaded := NewManager(&ManagerConfig{
|
||||
SkillDirs: []string{preloadedSkillDir(t, "pdf", "preloaded description")},
|
||||
Enabled: true,
|
||||
}, nil)
|
||||
require.NoError(t, preloaded.Initialize(context.Background()))
|
||||
|
||||
_, ok = preloaded.SandboxSkillDir("pdf")
|
||||
require.False(t, ok)
|
||||
}
|
||||
|
||||
// Preloaded skills keep uploading from the host and keep running in their own
|
||||
// directory; the tenant source must not change that path at all.
|
||||
func TestManagerKeepsPreloadedSkillExecutionWhenNoTenantSource(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -149,6 +149,11 @@ var shellExecTool = BaseTool{
|
|||
- DO NOT use this to run a skill's main script — use ` + "`execute_skill_script`" + `
|
||||
which handles skill lookup, artifact collection, and proper interpreter
|
||||
selection.
|
||||
- DO NOT judge a skill's dependencies with a bare ` + "`python3 -c`" + ` or
|
||||
` + "`node -e`" + `: each skill keeps its dependencies in its own virtualenv or
|
||||
node_modules, which neither of those resolves from here. ` + "`read_skill`" + `
|
||||
reports the skill's directory and how to reach its environment; reinstalling
|
||||
the packages here only fills a sandbox that is discarded with the session.
|
||||
- DO NOT try to background processes (` + "`&`" + ` at the end, ` + "`nohup`" + `). Sandbox
|
||||
execution is synchronous.
|
||||
|
||||
|
|
@ -175,6 +180,11 @@ var shellExecTool = BaseTool{
|
|||
lines usually carry the crucial error message.
|
||||
- Binary output is never returned to the model. Store binary files under
|
||||
` + "`/workspace/output`" + ` so ArtifactCollector can expose them for download.
|
||||
- To show one of those files in your answer, reference it as
|
||||
` + "``" + ` with the exact file name and no
|
||||
directory path. Images render inline; charts, tables, and documents render as
|
||||
a card the user clicks to preview. A bare file name or a
|
||||
` + "`/workspace/output/...`" + ` path does not resolve in the browser.
|
||||
- ` + "`duration_ms`" + `: wall-clock execution time.
|
||||
|
||||
## Safety
|
||||
|
|
|
|||
|
|
@ -27,6 +27,11 @@ var executeSkillScriptTool = BaseTool{
|
|||
` + "`args`" + ` when a script accepts an input file.
|
||||
- Treat ` + "`/workspace/input`" + ` as read-only. Write generated files only to
|
||||
` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + ` so they can be collected for download.
|
||||
- Scripts reach the dependencies their install put beside them: Python runs
|
||||
with the skill's own virtualenv interpreter, Node resolves the skill's
|
||||
node_modules from the script's location. A failed import under a bare
|
||||
` + "`python3 -c`" + ` or ` + "`node -e`" + ` says nothing about whether this
|
||||
tool can run the script.
|
||||
|
||||
## When to Use
|
||||
- When a skill's instructions reference a utility script (e.g., "Run scripts/analyze_form.py")
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
|
||||
"github.com/Tencent/WeKnora/internal/agent/skills"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
|
@ -148,6 +149,12 @@ func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (*typ
|
|||
resultData["instructions"] = skill.Instructions
|
||||
resultData["instructions_length"] = len(skill.Instructions)
|
||||
resultData["files"] = files
|
||||
|
||||
if dir, ok := t.skillManager.SandboxSkillDir(skill.Name); ok {
|
||||
builder.WriteString(skillEnvironmentSection(dir))
|
||||
resultData["skill_dir"] = dir
|
||||
resultData["skill_python"] = sandbox.SkillVenvPython(dir)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][ReadSkill] Successfully read skill: %s", input.SkillName)
|
||||
|
|
@ -159,6 +166,40 @@ func (t *ReadSkillTool) Execute(ctx context.Context, args json.RawMessage) (*typ
|
|||
}, nil
|
||||
}
|
||||
|
||||
// skillEnvironmentSection tells the model where the skill's dependencies are.
|
||||
//
|
||||
// Every skill keeps its dependencies to itself — Python in its own virtualenv,
|
||||
// Node in its own node_modules — so a bare interpreter started anywhere else
|
||||
// sees none of them. A model that probes with `python3 -c "import pandas"` or
|
||||
// `node -e "require('echarts')"` therefore reads the failure as "this skill
|
||||
// cannot run" and answers it by installing the packages again, into a session
|
||||
// sandbox that is thrown away: the image stays untouched and the next session
|
||||
// repeats the whole thing.
|
||||
//
|
||||
// The two languages fail for different reasons, which is why the advice below
|
||||
// is per-language. Python needs the virtualenv's own interpreter named
|
||||
// explicitly. Node resolves from the importing file's directory, so running a
|
||||
// script by absolute path already finds the skill's node_modules — it is only
|
||||
// `node -e` and friends, which have no file to resolve from, that need the
|
||||
// working directory moved into the skill.
|
||||
func skillEnvironmentSection(skillDir string) string {
|
||||
return fmt.Sprintf(`
|
||||
|
||||
## Execution Environment
|
||||
|
||||
- This skill is installed at `+"`%s`"+` inside the sandbox, and its
|
||||
dependencies live there with it, not in the sandbox's system interpreters.
|
||||
- `+"`execute_skill_script`"+` already runs its scripts the right way. Prefer
|
||||
it over invoking them yourself.
|
||||
- Do NOT decide from a system interpreter whether this skill can run, and do
|
||||
NOT reinstall its dependencies with `+"`pip install`"+` / `+"`npm install`"+`:
|
||||
those packages land in this session only and are lost with it.
|
||||
- To inspect the environment yourself from `+"`shell_exec`"+`: for Python, run
|
||||
`+"`%s`"+` instead of `+"`python3`"+`; for Node, run from `+"`%s`"+` as the
|
||||
working directory so its `+"`node_modules`"+` resolves.
|
||||
`, skillDir, sandbox.SkillVenvPython(skillDir), skillDir)
|
||||
}
|
||||
|
||||
// Cleanup releases any resources (implements Tool interface if needed)
|
||||
func (t *ReadSkillTool) Cleanup(ctx context.Context) error {
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
package tools
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
)
|
||||
|
||||
// A model that probes an installed skill with a bare interpreter reads the
|
||||
// resulting import failure as "this skill is broken" and reinstalls the
|
||||
// packages into a session sandbox that is thrown away. read_skill has to hand
|
||||
// it the way in for both languages, and say why a bare probe proves nothing.
|
||||
//
|
||||
// The two need different answers: Python is reached by naming the virtualenv's
|
||||
// interpreter, Node by moving the working directory into the skill, because
|
||||
// Node resolves from the importing file rather than from the interpreter.
|
||||
func TestSkillEnvironmentSectionNamesTheWayIntoBothEnvironments(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := sandbox.SkillsImageRoot + "/smart-charts"
|
||||
section := skillEnvironmentSection(dir)
|
||||
|
||||
require.Contains(t, section, dir)
|
||||
require.Contains(t, section, sandbox.SkillVenvPython(dir))
|
||||
require.Contains(t, section, "node_modules")
|
||||
require.Contains(t, strings.ToLower(section), "pip install")
|
||||
require.Contains(t, strings.ToLower(section), "npm install")
|
||||
}
|
||||
|
|
@ -71,6 +71,23 @@ func (r *resourceRepository) CreateBinding(ctx context.Context, binding *types.R
|
|||
return r.db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(binding).Error
|
||||
}
|
||||
|
||||
// DeleteBinding removes one owner's claim on a resource. Deleting a claim that
|
||||
// was never recorded is not an error: callers release optimistically, from a
|
||||
// content scan that cannot know which references were bound.
|
||||
func (r *resourceRepository) DeleteBinding(ctx context.Context, resourceID, ownerType, ownerID string) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("resource_id = ? AND owner_type = ? AND owner_id = ?", resourceID, ownerType, ownerID).
|
||||
Delete(&types.ResourceBinding{}).Error
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CountBindings(ctx context.Context, resourceID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.WithContext(ctx).Model(&types.ResourceBinding{}).
|
||||
Where("resource_id = ?", resourceID).
|
||||
Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *resourceRepository) CreateGrant(ctx context.Context, grant *types.ResourceAccessGrant) error {
|
||||
return r.db.WithContext(ctx).Create(grant).Error
|
||||
}
|
||||
|
|
|
|||
|
|
@ -75,8 +75,8 @@ const defaultMaxArtifactFileBytes int64 = 50 * 1024 * 1024
|
|||
// so the resource registry can enumerate / garbage-collect artifacts by
|
||||
// their owning message instead of only via the messages.artifacts JSONB.
|
||||
const (
|
||||
artifactBindingOwnerType = "message"
|
||||
artifactBindingRelation = "artifact"
|
||||
artifactBindingOwnerType = types.ResourceOwnerMessage
|
||||
artifactBindingRelation = types.ResourceRelationArtifact
|
||||
)
|
||||
|
||||
// ArtifactCollector implements the "drain sandbox artifacts on turn
|
||||
|
|
@ -228,6 +228,33 @@ func (c *ArtifactCollector) Collect(
|
|||
messageID string,
|
||||
tenantID uint64,
|
||||
outputDir string,
|
||||
) (types.MessageArtifacts, error) {
|
||||
return c.collect(ctx, sessionID, messageID, tenantID, outputDir, nil)
|
||||
}
|
||||
|
||||
// CollectWithNotify is Collect plus a progress hook fired after the sandbox
|
||||
// listing is filtered, before any file is read or uploaded. The frontend uses
|
||||
// this to show a toolbar placeholder while object-storage uploads (often a
|
||||
// few seconds for HTML charts) finish. notify is skipped when nothing will
|
||||
// be persisted, so ordinary sandbox turns without new files stay quiet.
|
||||
func (c *ArtifactCollector) CollectWithNotify(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
messageID string,
|
||||
tenantID uint64,
|
||||
outputDir string,
|
||||
notify func(pending int),
|
||||
) (types.MessageArtifacts, error) {
|
||||
return c.collect(ctx, sessionID, messageID, tenantID, outputDir, notify)
|
||||
}
|
||||
|
||||
func (c *ArtifactCollector) collect(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
messageID string,
|
||||
tenantID uint64,
|
||||
outputDir string,
|
||||
notify func(pending int),
|
||||
) (types.MessageArtifacts, error) {
|
||||
if c == nil || c.fileService == nil {
|
||||
logger.Infof(ctx, "[ArtifactCollector] skipped: collector or dependencies nil (session=%s)", sessionID)
|
||||
|
|
@ -281,7 +308,17 @@ func (c *ArtifactCollector) Collect(
|
|||
logger.Infof(ctx, "[ArtifactCollector] known set size=%d (session=%s)", len(known), sessionID)
|
||||
}
|
||||
|
||||
artifacts := make(types.MessageArtifacts, 0, len(entries))
|
||||
pending := 0
|
||||
for _, entry := range entries {
|
||||
if c.acceptEntry(entry, known) {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
if pending > 0 && notify != nil {
|
||||
notify(pending)
|
||||
}
|
||||
|
||||
artifacts := make(types.MessageArtifacts, 0, pending)
|
||||
for _, entry := range entries {
|
||||
art, ok := c.maybePersist(ctx, source, sessionID, messageID, tenantID, entry, known)
|
||||
if !ok {
|
||||
|
|
@ -318,6 +355,22 @@ func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string)
|
|||
return set
|
||||
}
|
||||
|
||||
func (c *ArtifactCollector) acceptEntry(entry sandbox.RemoteDirEntry, known map[string]struct{}) bool {
|
||||
if entry.Type != sandbox.RemoteEntryFile {
|
||||
return false
|
||||
}
|
||||
if entry.Path == "" || entry.Name == "" {
|
||||
return false
|
||||
}
|
||||
if entry.Size > c.config.MaxFileBytes {
|
||||
return false
|
||||
}
|
||||
if _, seen := known[artifactKey(entry.Path, entry.ModTime)]; seen {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// maybePersist runs the per-file pipeline (filter → download → upload →
|
||||
// build metadata). Returns ok=false when the entry was skipped for any
|
||||
// reason (already known, too large, upload failed). All skip reasons are
|
||||
|
|
@ -331,24 +384,11 @@ func (c *ArtifactCollector) maybePersist(
|
|||
entry sandbox.RemoteDirEntry,
|
||||
known map[string]struct{},
|
||||
) (types.MessageArtifact, bool) {
|
||||
// Only files reach here (SessionBoundManager.listFilesRecursive filters
|
||||
// directories), but we defensively double-check so callers passing an
|
||||
// alternate SandboxArtifactSource don't break the assumption.
|
||||
if entry.Type != sandbox.RemoteEntryFile {
|
||||
return types.MessageArtifact{}, false
|
||||
}
|
||||
if entry.Path == "" || entry.Name == "" {
|
||||
return types.MessageArtifact{}, false
|
||||
}
|
||||
if entry.Size > c.config.MaxFileBytes {
|
||||
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact: session=%s path=%s size=%d limit=%d",
|
||||
sessionID, entry.Path, entry.Size, c.config.MaxFileBytes)
|
||||
return types.MessageArtifact{}, false
|
||||
}
|
||||
|
||||
modTime := entry.ModTime
|
||||
key := artifactKey(entry.Path, modTime)
|
||||
if _, seen := known[key]; seen {
|
||||
if !c.acceptEntry(entry, known) {
|
||||
if entry.Type == sandbox.RemoteEntryFile && entry.Size > c.config.MaxFileBytes {
|
||||
logger.Warnf(ctx, "[ArtifactCollector] skip oversize artifact: session=%s path=%s size=%d limit=%d",
|
||||
sessionID, entry.Path, entry.Size, c.config.MaxFileBytes)
|
||||
}
|
||||
return types.MessageArtifact{}, false
|
||||
}
|
||||
|
||||
|
|
@ -386,7 +426,7 @@ func (c *ArtifactCollector) maybePersist(
|
|||
FileType: strings.ToLower(filepath.Ext(entry.Name)),
|
||||
FileSize: int64(len(data)),
|
||||
SourcePath: entry.Path,
|
||||
ModTime: modTime,
|
||||
ModTime: entry.ModTime,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}, true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -139,6 +139,12 @@ type bindCall struct {
|
|||
type fakeCatalog struct {
|
||||
binds []bindCall
|
||||
bindErr error
|
||||
// Release scripting, used by the deletion-guard tests. releaseRemaining
|
||||
// maps a reference to the binding count left after the release; a missing
|
||||
// entry answers -1 ("not a catalog handle").
|
||||
releaseRemaining map[string]int64
|
||||
releaseErr error
|
||||
releases []string
|
||||
}
|
||||
|
||||
func (c *fakeCatalog) Register(context.Context, uint64, string, interfaces.ResourceRegistration) (string, error) {
|
||||
|
|
@ -155,6 +161,17 @@ func (c *fakeCatalog) Bind(_ context.Context, ref, ownerType, ownerID, relation
|
|||
return c.bindErr
|
||||
}
|
||||
func (c *fakeCatalog) MarkDeleted(context.Context, string) error { return nil }
|
||||
|
||||
func (c *fakeCatalog) Release(_ context.Context, ref, ownerType, ownerID string) (int64, error) {
|
||||
c.releases = append(c.releases, ref+"|"+ownerType+"|"+ownerID)
|
||||
if c.releaseErr != nil {
|
||||
return -1, c.releaseErr
|
||||
}
|
||||
if remaining, ok := c.releaseRemaining[ref]; ok {
|
||||
return remaining, nil
|
||||
}
|
||||
return -1, nil
|
||||
}
|
||||
func (c *fakeCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
|
@ -218,6 +235,48 @@ func TestArtifactCollector_CollectsNewFiles(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestArtifactCollector_NotifyFiresBeforeUpload(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
src := &fakeSandboxSource{
|
||||
entries: map[string][]sandbox.RemoteDirEntry{
|
||||
"sess-1": {
|
||||
{
|
||||
Name: "a.html", Path: "/workspace/output/a.html",
|
||||
Type: sandbox.RemoteEntryFile, Size: 2,
|
||||
ModTime: mustParseTime("2026-07-10T10:20:33Z"),
|
||||
},
|
||||
{
|
||||
Name: "b.csv", Path: "/workspace/output/b.csv",
|
||||
Type: sandbox.RemoteEntryFile, Size: 2,
|
||||
ModTime: mustParseTime("2026-07-10T10:20:34Z"),
|
||||
},
|
||||
},
|
||||
},
|
||||
contents: map[string][]byte{
|
||||
"/workspace/output/a.html": []byte("ok"),
|
||||
"/workspace/output/b.csv": []byte("x,"),
|
||||
},
|
||||
}
|
||||
c := newTestCollector(src, &fakeStore{}, &fakeFileService{}, 1<<20)
|
||||
|
||||
var notified int
|
||||
got, err := c.CollectWithNotify(ctx, "sess-1", "msg-1", 42, "/workspace/output", func(n int) {
|
||||
if src.readCalls != nil {
|
||||
t.Fatalf("notify ran after ReadSessionFile: %v", src.readCalls)
|
||||
}
|
||||
notified = n
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CollectWithNotify() error = %v", err)
|
||||
}
|
||||
if notified != 2 {
|
||||
t.Fatalf("notify count = %d, want 2", notified)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("CollectWithNotify() len = %d, want 2", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactCollector_SkipsAlreadyKnown(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
mod, _ := time.Parse(time.RFC3339, "2026-07-10T10:20:33Z")
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
|
|
@ -98,7 +99,7 @@ func (s *resourceCatalogFileService) SaveFile(
|
|||
return "", err
|
||||
}
|
||||
if knowledgeID != "" {
|
||||
if err := s.catalog.Bind(ctx, ref, "knowledge", knowledgeID, "source_file"); err != nil {
|
||||
if err := s.catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, knowledgeID, types.ResourceRelationSourceFile); err != nil {
|
||||
_ = s.DeleteFile(ctx, ref)
|
||||
return "", fmt.Errorf("bind stored resource: %w", err)
|
||||
}
|
||||
|
|
@ -182,7 +183,7 @@ func (s *resourceCatalogFileService) CopyFile(
|
|||
return "", err
|
||||
}
|
||||
if knowledgeID != "" {
|
||||
if err := s.catalog.Bind(ctx, ref, "knowledge", knowledgeID, "source_file"); err != nil {
|
||||
if err := s.catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, knowledgeID, types.ResourceRelationSourceFile); err != nil {
|
||||
_ = s.DeleteFile(ctx, ref)
|
||||
return "", fmt.Errorf("bind copied resource: %w", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,6 +47,10 @@ func (c *catalogStub) ResolvePath(_ context.Context, value string) (string, *typ
|
|||
}
|
||||
func (c *catalogStub) Bind(context.Context, string, string, string, string) error { return nil }
|
||||
func (c *catalogStub) MarkDeleted(context.Context, string) error { return nil }
|
||||
|
||||
func (c *catalogStub) Release(context.Context, string, string, string) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (c *catalogStub) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
|
||||
return "GrantTokenAbCdEfGhIjKl", nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,122 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// resolvingCatalog answers Resolve from a fixed handle → tenant map and records
|
||||
// every Bind, which is all bindContentResources exercises.
|
||||
type resolvingCatalog struct {
|
||||
tenantByRef map[string]uint64
|
||||
binds []bindCall
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) Resolve(_ context.Context, ref string) (*types.StoredResource, error) {
|
||||
tenantID, ok := c.tenantByRef[ref]
|
||||
if !ok {
|
||||
return nil, errors.New("resource not found")
|
||||
}
|
||||
handle, _ := types.ParseResourcePath(ref)
|
||||
return &types.StoredResource{ID: handle, Handle: handle, TenantID: tenantID}, nil
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) Bind(_ context.Context, ref, ownerType, ownerID, relation string) error {
|
||||
c.binds = append(c.binds, bindCall{ref, ownerType, ownerID, relation})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) Register(
|
||||
context.Context, uint64, string, interfaces.ResourceRegistration,
|
||||
) (string, error) {
|
||||
return "", errors.New("unused")
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) ResolvePath(
|
||||
_ context.Context, value string,
|
||||
) (string, *types.StoredResource, error) {
|
||||
return value, nil, nil
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) Release(context.Context, string, string, string) (int64, error) {
|
||||
return -1, nil
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) MarkDeleted(context.Context, string) error { return nil }
|
||||
|
||||
func (c *resolvingCatalog) CreateAccessGrant(
|
||||
context.Context, string, time.Duration,
|
||||
) (string, error) {
|
||||
return "", errors.New("unused")
|
||||
}
|
||||
|
||||
func (c *resolvingCatalog) ResolveAccessGrant(
|
||||
context.Context, string,
|
||||
) (*types.StoredResource, error) {
|
||||
return nil, errors.New("unused")
|
||||
}
|
||||
|
||||
func contentRef(char string) string {
|
||||
return types.BuildResourcePath(strings.Repeat(char, types.ResourceHandleLength))
|
||||
}
|
||||
|
||||
// Saving a chat answer into the knowledge base must claim the files it shows
|
||||
// without copying them: the assistant message keeps its own claim, so either
|
||||
// side can be deleted without breaking the other.
|
||||
func TestBindContentResourcesClaimsEveryReferencedFile(t *testing.T) {
|
||||
chart := contentRef("a")
|
||||
table := contentRef("b")
|
||||
catalog := &resolvingCatalog{tenantByRef: map[string]uint64{chart: 7, table: 7}}
|
||||
svc := &knowledgeService{resourceCatalog: catalog}
|
||||
|
||||
content := "## 结论\n\n\n\n数据见 [表格](" + table + ")"
|
||||
svc.bindContentResources(context.Background(), 7, "kn-1", content)
|
||||
|
||||
if len(catalog.binds) != 2 {
|
||||
t.Fatalf("binds = %v, want one per reference", catalog.binds)
|
||||
}
|
||||
for i, want := range []string{chart, table} {
|
||||
got := catalog.binds[i]
|
||||
if got.ref != want {
|
||||
t.Fatalf("binds[%d].ref = %q, want %q", i, got.ref, want)
|
||||
}
|
||||
if got.ownerType != types.ResourceOwnerKnowledge || got.ownerID != "kn-1" {
|
||||
t.Fatalf("binds[%d] owner = (%q, %q), want (%q, kn-1)",
|
||||
i, got.ownerType, got.ownerID, types.ResourceOwnerKnowledge)
|
||||
}
|
||||
if got.relation != types.ResourceRelationAttachment {
|
||||
t.Fatalf("binds[%d].relation = %q, want %q",
|
||||
i, got.relation, types.ResourceRelationAttachment)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A handle pasted from another workspace must not be claimed: binding it would
|
||||
// hand the caller a file it may not read.
|
||||
func TestBindContentResourcesSkipsForeignAndUnknownHandles(t *testing.T) {
|
||||
mine := contentRef("c")
|
||||
theirs := contentRef("d")
|
||||
unknown := contentRef("e")
|
||||
catalog := &resolvingCatalog{tenantByRef: map[string]uint64{mine: 7, theirs: 9}}
|
||||
svc := &knowledgeService{resourceCatalog: catalog}
|
||||
|
||||
content := "  "
|
||||
svc.bindContentResources(context.Background(), 7, "kn-1", content)
|
||||
|
||||
if len(catalog.binds) != 1 || catalog.binds[0].ref != mine {
|
||||
t.Fatalf("binds = %v, want only %q", catalog.binds, mine)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindContentResourcesIsInertWithoutCatalog(t *testing.T) {
|
||||
svc := &knowledgeService{}
|
||||
// Must not panic; a deployment without a resource registry has nothing to
|
||||
// claim and keeps the pre-binding behaviour.
|
||||
svc.bindContentResources(context.Background(), 7, "kn-1", "+")")
|
||||
}
|
||||
|
|
@ -816,6 +816,11 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// Claim the body's files immediately, before publishing. A draft saved from
|
||||
// a chat answer must already own them: the message it came from could be
|
||||
// deleted while the draft is still unpublished.
|
||||
s.bindContentResources(ctx, tenantID, knowledge.ID, cleanContent)
|
||||
|
||||
if status == types.ManualKnowledgeStatusPublish {
|
||||
logger.Infof(ctx, "Manual knowledge created, enqueuing async processing task, ID: %s", knowledge.ID)
|
||||
taskID, err := s.enqueueManualProcessing(ctx, knowledge, cleanContent, false)
|
||||
|
|
@ -1063,6 +1068,7 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
|
|||
logger.Errorf(ctx, "Failed to persist manual draft: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
s.bindContentResources(ctx, tenantID, existing.ID, cleanContent)
|
||||
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeUpdated,
|
||||
"knowledge", existing.ID, types.AuditOutcomeSuccess, map[string]any{
|
||||
"title": existing.Title, "status": status,
|
||||
|
|
@ -1178,6 +1184,42 @@ func sanitizeManualDownloadFilename(title string) string {
|
|||
return safeName
|
||||
}
|
||||
|
||||
// bindContentResources claims every stored file the body references on behalf
|
||||
// of a knowledge entry.
|
||||
//
|
||||
// A manual document routinely points at files it did not upload: an answer saved
|
||||
// from a chat carries the very `resource://` handles the assistant message still
|
||||
// shows. Claiming them is what makes that copy safe — no bytes are duplicated,
|
||||
// and neither the message nor the document can delete a file the other still
|
||||
// needs. Handles belonging to another workspace are skipped, so a pasted
|
||||
// reference cannot pull in a file the caller may not read.
|
||||
//
|
||||
// Best-effort by design: the document is already saved, and a missed claim
|
||||
// degrades to the old behaviour rather than failing the save.
|
||||
func (s *knowledgeService) bindContentResources(
|
||||
ctx context.Context, tenantID uint64, knowledgeID, content string,
|
||||
) {
|
||||
if s.resourceCatalog == nil || knowledgeID == "" {
|
||||
return
|
||||
}
|
||||
for _, ref := range types.ScanResourceReferences(content) {
|
||||
resource, err := s.resourceCatalog.Resolve(ctx, ref)
|
||||
if err != nil || resource == nil {
|
||||
logger.Warnf(ctx, "Skip binding unknown resource %s to knowledge %s: %v", ref, knowledgeID, err)
|
||||
continue
|
||||
}
|
||||
if resource.TenantID != tenantID {
|
||||
logger.Warnf(ctx, "Skip binding cross-workspace resource %s to knowledge %s", ref, knowledgeID)
|
||||
continue
|
||||
}
|
||||
if err := s.resourceCatalog.Bind(
|
||||
ctx, ref, types.ResourceOwnerKnowledge, knowledgeID, types.ResourceRelationAttachment,
|
||||
); err != nil {
|
||||
logger.Warnf(ctx, "Failed to bind resource %s to knowledge %s: %v", ref, knowledgeID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, content string, doSync bool,
|
||||
) {
|
||||
|
|
@ -1208,6 +1250,11 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
|||
}
|
||||
}
|
||||
|
||||
// Re-claim the body's stored files. This runs after cleanupKnowledgeResources
|
||||
// released the previous run's claims, so a republished document keeps the
|
||||
// files its new body still references.
|
||||
s.bindContentResources(ctx, knowledge.TenantID, knowledge.ID, clean)
|
||||
|
||||
// Keep manually entered CRLF text aligned with the LF values sent by the
|
||||
// chunking preview endpoint.
|
||||
clean = chunker.NormalizeLineEndings(clean)
|
||||
|
|
|
|||
|
|
@ -40,15 +40,78 @@ func collectImageURLs(ctx context.Context, imageInfos []string) []string {
|
|||
return urls
|
||||
}
|
||||
|
||||
// knowledgeResourceOwners builds the releaser for a set of knowledge entries
|
||||
// being deleted. A nil catalog (no resource registry) yields nil, which
|
||||
// deleteExtractedImages treats as "delete unconditionally", i.e. the behaviour
|
||||
// from before bindings were tracked.
|
||||
func knowledgeResourceOwners(catalog interfaces.ResourceCatalog, knowledgeIDs ...string) *resourceReleaser {
|
||||
if catalog == nil || len(knowledgeIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &resourceReleaser{catalog: catalog, ownerType: types.ResourceOwnerKnowledge, ownerIDs: knowledgeIDs}
|
||||
}
|
||||
|
||||
// resourceReleaser decides whether a stored file's bytes may be deleted along
|
||||
// with the domain object that referenced them.
|
||||
//
|
||||
// A file can be claimed by more than one owner — an answer saved into the
|
||||
// knowledge base shares the very blob the chat message still shows, and two
|
||||
// knowledge entries can share an image. Deleting one owner must drop only that
|
||||
// owner's claim; the bytes go away when the last claim does.
|
||||
type resourceReleaser struct {
|
||||
catalog interfaces.ResourceCatalog
|
||||
ownerType string
|
||||
ownerIDs []string
|
||||
}
|
||||
|
||||
// deletable drops this releaser's claims on ref and reports whether the bytes
|
||||
// are now unreferenced.
|
||||
//
|
||||
// An unreadable binding count keeps the file. The cost of keeping it is an
|
||||
// orphaned blob that a later delete can still reclaim; the cost of guessing
|
||||
// wrong the other way is an image vanishing from a conversation or document
|
||||
// that nobody deleted.
|
||||
func (r *resourceReleaser) deletable(ctx context.Context, ref string) bool {
|
||||
if r == nil || r.catalog == nil {
|
||||
return true
|
||||
}
|
||||
remaining := int64(-1)
|
||||
for _, ownerID := range r.ownerIDs {
|
||||
count, err := r.catalog.Release(ctx, ref, r.ownerType, ownerID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to release resource %s from %s %s: %v",
|
||||
ref, r.ownerType, ownerID, err)
|
||||
return false
|
||||
}
|
||||
if count >= 0 {
|
||||
remaining = count
|
||||
}
|
||||
}
|
||||
// -1 means the reference is not a catalog handle: no claims to account
|
||||
// for, so fall back to deleting it as before.
|
||||
return remaining <= 0
|
||||
}
|
||||
|
||||
// deleteExtractedImages deletes all extracted image files from storage.
|
||||
// Standalone function — callable from both knowledgeService and knowledgeBaseService.
|
||||
// Errors are logged but do not fail the overall deletion.
|
||||
func deleteExtractedImages(ctx context.Context, fileSvc interfaces.FileService, imageURLs []string) {
|
||||
//
|
||||
// releaser may be nil, in which case every file is deleted unconditionally.
|
||||
func deleteExtractedImages(
|
||||
ctx context.Context,
|
||||
fileSvc interfaces.FileService,
|
||||
releaser *resourceReleaser,
|
||||
imageURLs []string,
|
||||
) {
|
||||
if len(imageURLs) == 0 {
|
||||
return
|
||||
}
|
||||
logger.Infof(ctx, "Deleting %d extracted images", len(imageURLs))
|
||||
for _, url := range imageURLs {
|
||||
if !releaser.deletable(ctx, url) {
|
||||
logger.Infof(ctx, "Keeping extracted image %s: another owner may still reference it", url)
|
||||
continue
|
||||
}
|
||||
if err := fileSvc.DeleteFile(ctx, url); err != nil {
|
||||
logger.Errorf(ctx, "Failed to delete extracted image %s: %v", url, err)
|
||||
}
|
||||
|
|
@ -191,7 +254,7 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error
|
|||
logger.GetLogger(ctx).WithField("error", err).Errorf("DeleteKnowledge delete file failed")
|
||||
}
|
||||
}
|
||||
deleteExtractedImages(ctx, kbFileSvc, imageURLs)
|
||||
deleteExtractedImages(ctx, kbFileSvc, knowledgeResourceOwners(s.resourceCatalog, knowledge.ID), imageURLs)
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
tenantInfo.StorageUsed -= knowledge.StorageSize
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, -knowledge.StorageSize); err != nil {
|
||||
|
|
@ -554,6 +617,10 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
|||
for kbID, infos := range kbImageInfos {
|
||||
kbImageURLs[kbID] = collectImageURLs(ctx, infos)
|
||||
}
|
||||
kbKnowledgeIDs := make(map[string][]string) // kbID → knowledge IDs releasing their claims
|
||||
for _, k := range knowledgeList {
|
||||
kbKnowledgeIDs[k.KnowledgeBaseID] = append(kbKnowledgeIDs[k.KnowledgeBaseID], k.ID)
|
||||
}
|
||||
|
||||
wg := errgroup.Group{}
|
||||
// 2. Delete knowledge embeddings from vector store
|
||||
|
|
@ -662,7 +729,7 @@ func (s *knowledgeService) DeleteKnowledgeList(ctx context.Context, ids []string
|
|||
logger.Warnf(ctx, "No file service for KB %s, skipping %d image deletions", kbID, len(urls))
|
||||
continue
|
||||
}
|
||||
deleteExtractedImages(ctx, fSvc, urls)
|
||||
deleteExtractedImages(ctx, fSvc, knowledgeResourceOwners(s.resourceCatalog, kbKnowledgeIDs[kbID]...), urls)
|
||||
}
|
||||
tenantInfo.StorageUsed += storageAdjust
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, storageAdjust); err != nil {
|
||||
|
|
@ -754,8 +821,10 @@ func (s *knowledgeService) cleanupKnowledgeResources(ctx context.Context, knowle
|
|||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
}
|
||||
|
||||
// Delete extracted images after chunks are deleted
|
||||
deleteExtractedImages(ctx, fileSvc, imageURLs)
|
||||
// Delete extracted images after chunks are deleted. The claims released
|
||||
// here are re-taken by triggerManualProcessing, which always runs after
|
||||
// this cleanup and re-binds whatever the new body still references.
|
||||
deleteExtractedImages(ctx, fileSvc, knowledgeResourceOwners(s.resourceCatalog, knowledge.ID), imageURLs)
|
||||
|
||||
namespace := types.NameSpace{KnowledgeBase: knowledge.KnowledgeBaseID, Knowledge: knowledge.ID}
|
||||
if err := s.graphEngine.DelGraph(ctx, []types.NameSpace{namespace}); err != nil {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,106 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// deleteRecorder captures which files a cleanup actually removed.
|
||||
type deleteRecorder struct {
|
||||
fakeFileService
|
||||
deleted []string
|
||||
}
|
||||
|
||||
func (f *deleteRecorder) DeleteFile(_ context.Context, filePath string) error {
|
||||
f.deleted = append(f.deleted, filePath)
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleRef(char string) string {
|
||||
return types.BuildResourcePath(strings.Repeat(char, types.ResourceHandleLength))
|
||||
}
|
||||
|
||||
func TestDeleteExtractedImagesKeepsFilesAnotherOwnerStillClaims(t *testing.T) {
|
||||
shared := handleRef("a") // also shown by the chat message it was saved from
|
||||
exclusive := handleRef("b") // only this knowledge references it
|
||||
legacy := "local://7/exports/old.png"
|
||||
|
||||
catalog := &fakeCatalog{releaseRemaining: map[string]int64{shared: 1, exclusive: 0}}
|
||||
files := &deleteRecorder{}
|
||||
|
||||
deleteExtractedImages(
|
||||
context.Background(), files,
|
||||
knowledgeResourceOwners(catalog, "kn-1"),
|
||||
[]string{shared, exclusive, legacy},
|
||||
)
|
||||
|
||||
want := []string{exclusive, legacy}
|
||||
if len(files.deleted) != len(want) {
|
||||
t.Fatalf("deleted %v, want %v", files.deleted, want)
|
||||
}
|
||||
for i, url := range want {
|
||||
if files.deleted[i] != url {
|
||||
t.Fatalf("deleted[%d] = %q, want %q", i, files.deleted[i], url)
|
||||
}
|
||||
}
|
||||
if len(catalog.releases) != 3 {
|
||||
t.Fatalf("released %v, want one call per reference", catalog.releases)
|
||||
}
|
||||
if got := catalog.releases[0]; got != shared+"|"+types.ResourceOwnerKnowledge+"|kn-1" {
|
||||
t.Fatalf("unexpected release call %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A knowledge base delete releases every entry's claim before deciding, so a
|
||||
// file shared between two entries of the same base is still removed.
|
||||
func TestDeleteExtractedImagesReleasesEveryOwnerBeforeDeciding(t *testing.T) {
|
||||
shared := handleRef("c")
|
||||
catalog := &fakeCatalog{releaseRemaining: map[string]int64{shared: 0}}
|
||||
files := &deleteRecorder{}
|
||||
|
||||
deleteExtractedImages(
|
||||
context.Background(), files,
|
||||
knowledgeResourceOwners(catalog, "kn-1", "kn-2"),
|
||||
[]string{shared},
|
||||
)
|
||||
|
||||
if len(files.deleted) != 1 {
|
||||
t.Fatalf("deleted %v, want the shared file removed once", files.deleted)
|
||||
}
|
||||
if len(catalog.releases) != 2 {
|
||||
t.Fatalf("released %v, want both owners released", catalog.releases)
|
||||
}
|
||||
}
|
||||
|
||||
// An unreadable binding count must not destroy bytes: an orphaned blob can be
|
||||
// reclaimed later, an image missing from a document nobody deleted cannot.
|
||||
func TestDeleteExtractedImagesKeepsFileWhenReleaseFails(t *testing.T) {
|
||||
catalog := &fakeCatalog{releaseErr: errors.New("db down")}
|
||||
files := &deleteRecorder{}
|
||||
|
||||
deleteExtractedImages(
|
||||
context.Background(), files,
|
||||
knowledgeResourceOwners(catalog, "kn-1"),
|
||||
[]string{handleRef("d")},
|
||||
)
|
||||
|
||||
if len(files.deleted) != 0 {
|
||||
t.Fatalf("deleted %v, want nothing deleted while the count is unknown", files.deleted)
|
||||
}
|
||||
}
|
||||
|
||||
// Without a catalog the guard is inert and cleanup behaves as it always did.
|
||||
func TestDeleteExtractedImagesWithoutCatalogDeletesEverything(t *testing.T) {
|
||||
files := &deleteRecorder{}
|
||||
urls := []string{handleRef("e"), "local://7/exports/x.png"}
|
||||
|
||||
deleteExtractedImages(context.Background(), files, knowledgeResourceOwners(nil, "kn-1"), urls)
|
||||
|
||||
if len(files.deleted) != len(urls) {
|
||||
t.Fatalf("deleted %v, want %v", files.deleted, urls)
|
||||
}
|
||||
}
|
||||
|
|
@ -48,6 +48,7 @@ type knowledgeBaseService struct {
|
|||
syncLogRepo interfaces.SyncLogRepository
|
||||
dsScheduler *datasource.Scheduler
|
||||
audit interfaces.AuditLogService
|
||||
resourceCatalog interfaces.ResourceCatalog
|
||||
}
|
||||
|
||||
// NewKnowledgeBaseService creates a new knowledge base service
|
||||
|
|
@ -70,6 +71,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
|||
syncLogRepo interfaces.SyncLogRepository,
|
||||
dsScheduler *datasource.Scheduler,
|
||||
audit interfaces.AuditLogService,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
) interfaces.KnowledgeBaseService {
|
||||
return &knowledgeBaseService{
|
||||
repo: repo,
|
||||
|
|
@ -91,6 +93,7 @@ func NewKnowledgeBaseService(repo interfaces.KnowledgeBaseRepository,
|
|||
syncLogRepo: syncLogRepo,
|
||||
dsScheduler: dsScheduler,
|
||||
audit: audit,
|
||||
resourceCatalog: resourceCatalog,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -932,7 +935,7 @@ func (s *knowledgeBaseService) ProcessKBDelete(ctx context.Context, t *asynq.Tas
|
|||
}
|
||||
storageAdjust -= knowledge.StorageSize
|
||||
}
|
||||
deleteExtractedImages(ctx, s.fileSvc, imageURLs)
|
||||
deleteExtractedImages(ctx, s.fileSvc, knowledgeResourceOwners(s.resourceCatalog, knowledgeIDs...), imageURLs)
|
||||
if storageAdjust != 0 {
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantID, storageAdjust); err != nil {
|
||||
logger.Warnf(ctx, "Failed to adjust tenant storage: %v", err)
|
||||
|
|
|
|||
|
|
@ -155,6 +155,33 @@ func (s *resourceCatalog) Bind(ctx context.Context, reference, ownerType, ownerI
|
|||
})
|
||||
}
|
||||
|
||||
// Release implements interfaces.ResourceCatalog.
|
||||
//
|
||||
// Unbinding and counting are deliberately not a single transaction. A racing
|
||||
// bind that lands between them makes the count too high, which keeps a live
|
||||
// file — the safe direction. The opposite ordering could delete bytes another
|
||||
// owner had just claimed.
|
||||
func (s *resourceCatalog) Release(
|
||||
ctx context.Context, reference, ownerType, ownerID string,
|
||||
) (int64, error) {
|
||||
if strings.TrimSpace(ownerType) == "" || strings.TrimSpace(ownerID) == "" {
|
||||
return -1, fmt.Errorf("resource release requires owner type and id")
|
||||
}
|
||||
if _, ok := types.ParseResourcePath(reference); !ok {
|
||||
// A raw provider path predates the catalog and has no bindings to
|
||||
// account for; the caller keeps its previous delete behaviour.
|
||||
return -1, nil
|
||||
}
|
||||
resource, err := s.Resolve(ctx, reference)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
if err := s.repo.DeleteBinding(ctx, resource.ID, ownerType, ownerID); err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return s.repo.CountBindings(ctx, resource.ID)
|
||||
}
|
||||
|
||||
func (s *resourceCatalog) MarkDeleted(ctx context.Context, reference string) error {
|
||||
resource, err := s.Resolve(ctx, reference)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -66,6 +66,63 @@ func TestResourceCatalogBindingAndAccessGrant(t *testing.T) {
|
|||
require.Equal(t, uint64(9), resource.TenantID)
|
||||
}
|
||||
|
||||
// The two-owner case that "save this answer to the knowledge base" creates:
|
||||
// one blob, claimed by both the assistant message and the new document.
|
||||
// Deleting either owner must leave the other's copy intact.
|
||||
func TestResourceCatalogReleaseKeepsFileWhileAnotherOwnerClaimsIt(t *testing.T) {
|
||||
catalog, _ := newResourceCatalogForTest(t)
|
||||
ctx := context.Background()
|
||||
ref, err := catalog.Register(ctx, 7, "local://7/exports/chart.html", interfaces.ResourceRegistration{})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, catalog.Bind(ctx, ref, types.ResourceOwnerMessage, "msg-1", types.ResourceRelationArtifact))
|
||||
require.NoError(t, catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationAttachment))
|
||||
|
||||
remaining, err := catalog.Release(ctx, ref, types.ResourceOwnerKnowledge, "kn-1")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 1, remaining, "the message still shows this file")
|
||||
|
||||
remaining, err = catalog.Release(ctx, ref, types.ResourceOwnerMessage, "msg-1")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, remaining, "the last claim is gone, the bytes can go too")
|
||||
}
|
||||
|
||||
// Binding twice is how a republished document re-takes its claim, and it must
|
||||
// not inflate the count into a file that can never be collected.
|
||||
func TestResourceCatalogBindIsIdempotentPerOwner(t *testing.T) {
|
||||
catalog, _ := newResourceCatalogForTest(t)
|
||||
ctx := context.Background()
|
||||
ref, err := catalog.Register(ctx, 7, "local://7/exports/a.png", interfaces.ResourceRegistration{})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NoError(t, catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationAttachment))
|
||||
require.NoError(t, catalog.Bind(ctx, ref, types.ResourceOwnerKnowledge, "kn-1", types.ResourceRelationAttachment))
|
||||
|
||||
remaining, err := catalog.Release(ctx, ref, types.ResourceOwnerKnowledge, "kn-1")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, remaining)
|
||||
}
|
||||
|
||||
// Releasing something that was never bound, or is not a handle at all, must be
|
||||
// harmless: callers release optimistically from a content scan.
|
||||
func TestResourceCatalogReleaseUnknownReference(t *testing.T) {
|
||||
catalog, _ := newResourceCatalogForTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
remaining, err := catalog.Release(ctx, "local://7/exports/legacy.png", types.ResourceOwnerKnowledge, "kn-1")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, -1, remaining, "a raw provider path has no claims to account for")
|
||||
|
||||
ref, err := catalog.Register(ctx, 7, "local://7/exports/b.png", interfaces.ResourceRegistration{})
|
||||
require.NoError(t, err)
|
||||
remaining, err = catalog.Release(ctx, ref, types.ResourceOwnerKnowledge, "never-bound")
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 0, remaining)
|
||||
|
||||
_, err = catalog.Release(ctx, ref, "", "kn-1")
|
||||
require.Error(t, err, "an owner is required to release a claim")
|
||||
}
|
||||
|
||||
// Rendering one answer resolves the same image many times, and re-reading a
|
||||
// message history resolves it again on every call. Each resolution used to
|
||||
// insert a capability row; a live one must be reused instead.
|
||||
|
|
|
|||
|
|
@ -189,7 +189,7 @@ func (s *temporaryDocumentService) Create(
|
|||
return nil, fmt.Errorf("create attachment record: %w", err)
|
||||
}
|
||||
if s.resourceCatalog != nil {
|
||||
if err := s.resourceCatalog.Bind(ctx, resourceRef, "temporary_document", document.ID, "source_file"); err != nil {
|
||||
if err := s.resourceCatalog.Bind(ctx, resourceRef, types.ResourceOwnerTemporaryDocument, document.ID, types.ResourceRelationSourceFile); err != nil {
|
||||
_ = s.repo.DeleteScoped(ctx, tenantID, sessionID, document.ID)
|
||||
_ = s.fileService.DeleteFile(ctx, resourceRef)
|
||||
return nil, fmt.Errorf("bind attachment resource: %w", err)
|
||||
|
|
@ -425,7 +425,7 @@ func (s *temporaryDocumentService) parse(ctx context.Context, document *types.Te
|
|||
for _, image := range stored {
|
||||
images = append(images, types.TemporaryDocumentImage{OriginalRef: image.OriginalRef, URL: image.ServingURL, MimeType: image.MimeType})
|
||||
if s.resourceCatalog != nil {
|
||||
_ = s.resourceCatalog.Bind(ctx, image.ServingURL, "temporary_document", document.ID, "extracted_image")
|
||||
_ = s.resourceCatalog.Bind(ctx, image.ServingURL, types.ResourceOwnerTemporaryDocument, document.ID, types.ResourceRelationExtractedImage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,13 +82,7 @@ func (s *TenantSkillService) InstallSkill(
|
|||
now := s.now()
|
||||
if existing != nil {
|
||||
skillID = existing.ID
|
||||
existing.Version = bundle.Version
|
||||
existing.Description = bundle.Description
|
||||
existing.Instructions = bundle.Instructions
|
||||
existing.BundleSHA256 = bundle.SHA256
|
||||
existing.Status = types.SkillStatusInstalling
|
||||
existing.Error = ""
|
||||
existing.InstallingSince = &now
|
||||
takeSkillRowForInstall(existing, bundle, now)
|
||||
if err := s.skills.UpdateSkill(ctx, existing); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
|
@ -113,13 +107,7 @@ func (s *TenantSkillService) InstallSkill(
|
|||
return "", err
|
||||
}
|
||||
skillID = winner.ID
|
||||
winner.Version = bundle.Version
|
||||
winner.Description = bundle.Description
|
||||
winner.Instructions = bundle.Instructions
|
||||
winner.BundleSHA256 = bundle.SHA256
|
||||
winner.Status = types.SkillStatusInstalling
|
||||
winner.Error = ""
|
||||
winner.InstallingSince = &now
|
||||
takeSkillRowForInstall(winner, bundle, now)
|
||||
if err := s.skills.UpdateSkill(ctx, winner); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
|
@ -163,6 +151,62 @@ func (s *TenantSkillService) InstallSkill(
|
|||
return skillID, nil
|
||||
}
|
||||
|
||||
// takeSkillRowForInstall hands an existing row to the run about to start.
|
||||
//
|
||||
// The transcript locators are cleared along with the error. They name the
|
||||
// session and message of the run that just ended, and a row that says
|
||||
// "installing" while still pointing at them tells every reader that the
|
||||
// finished conversation is this one's live output — which is how a retry came
|
||||
// to replay the previous attempt's report before its own agent had started.
|
||||
// They are rewritten by beginInstallTranscript once this run has a message of
|
||||
// its own; until then the honest answer is that there is nothing to show yet.
|
||||
func takeSkillRowForInstall(row *types.TenantSkillEntity, bundle *SkillBundle, now time.Time) {
|
||||
row.Version = bundle.Version
|
||||
row.Description = bundle.Description
|
||||
row.Instructions = bundle.Instructions
|
||||
row.BundleSHA256 = bundle.SHA256
|
||||
row.Status = types.SkillStatusInstalling
|
||||
row.Error = ""
|
||||
row.InstallingSince = &now
|
||||
row.InstallSessionID = ""
|
||||
row.InstallMessageID = ""
|
||||
}
|
||||
|
||||
// ReinstallSkill runs the install again from the archive already stored for
|
||||
// this skill. Most failed installs have nothing to do with the archive — an
|
||||
// unreachable sandbox, a package index that timed out, a checker that has
|
||||
// since been corrected — and making the operator find the original zip again
|
||||
// (or the registry URL it came from) is a poor answer to any of them.
|
||||
//
|
||||
// It deliberately goes through InstallSkill rather than jumping to runInstall.
|
||||
// That path owns the in-flight check, the row ownership handover and the
|
||||
// per-config lock, and a retry is exactly the moment two installs of one
|
||||
// config are most likely to overlap.
|
||||
func (s *TenantSkillService) ReinstallSkill(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string,
|
||||
) (string, error) {
|
||||
skill, err := s.skills.GetSkill(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if skill == nil {
|
||||
return "", apperrors.NewNotFoundError("skill not found")
|
||||
}
|
||||
// Reported apart from a generic read failure: nothing a retry does can
|
||||
// recover a skill whose archive is gone, and the operator needs to be told
|
||||
// to upload it rather than to press the button again.
|
||||
if strings.TrimSpace(skill.BundleRef) == "" {
|
||||
return "", apperrors.NewBadRequestError(
|
||||
"the archive of this skill is no longer stored; install it again from the original bundle",
|
||||
)
|
||||
}
|
||||
archive, err := s.skillBundleArchive(ctx, tenantID, configID, skillID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.InstallSkill(ctx, tenantID, configID, archive)
|
||||
}
|
||||
|
||||
func (s *TenantSkillService) runInstall(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string, bundle *SkillBundle,
|
||||
) (err error) {
|
||||
|
|
@ -306,10 +350,11 @@ func (s *TenantSkillService) runInstall(
|
|||
s.publishProgress(ctx, tenantID, configID, skillID, SkillProgress{Percent: 80, Stage: "agent_done"})
|
||||
|
||||
// 4. Hand the tree to the execution user BEFORE verifying it. The agent
|
||||
// created these files as root, and the smoke run below deliberately
|
||||
// runs as the ordinary user: verifying first would test permissions
|
||||
// that never reach the image, and a restrictive root umask would fail a
|
||||
// perfectly good install because the .venv interpreter was unreadable.
|
||||
// created these files as root, and the language passes below
|
||||
// deliberately run as the ordinary user: verifying first would test
|
||||
// permissions that never reach the image, and a restrictive root umask
|
||||
// would fail a perfectly good install because the .venv interpreter was
|
||||
// unreadable.
|
||||
if err := s.normalizeSkillPermissions(ctx, mgr, sess.ID, skillDir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -673,69 +718,12 @@ func (s *TenantSkillService) driveInstallerAgent(
|
|||
return nil
|
||||
}
|
||||
|
||||
// verifySkill is the server's own check. Both structure and smoke run are
|
||||
// gates for the snapshot switch: a broken install must leave the old image live.
|
||||
func (s *TenantSkillService) verifySkill(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -f %s", sandbox.ShellQuote(path.Join(skillDir, "SKILL.md")))); err != nil {
|
||||
return fmt.Errorf("skill directory is incomplete after install: %w", err)
|
||||
}
|
||||
for rel := range bundle.Files {
|
||||
if !strings.HasSuffix(rel, ".py") && !strings.HasSuffix(rel, ".js") &&
|
||||
!strings.HasSuffix(rel, ".mjs") && !strings.HasSuffix(rel, ".sh") {
|
||||
continue
|
||||
}
|
||||
target := path.Join(skillDir, rel)
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -f %s", sandbox.ShellQuote(target))); err != nil {
|
||||
return fmt.Errorf("script %s is missing after install: %w", rel, err)
|
||||
}
|
||||
}
|
||||
if err := s.verifyDeclaredDependencies(ctx, mgr, sessionID, skillDir, bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
if entry := primaryEntryScript(bundle); entry != "" {
|
||||
res, err := s.execSmoke(ctx, mgr, sessionID, skillDir, path.Join(skillDir, entry))
|
||||
if err != nil {
|
||||
return fmt.Errorf("smoke run %s: %w", entry, err)
|
||||
}
|
||||
if res.ExitCode != 0 {
|
||||
return fmt.Errorf("smoke run %s failed (%s)", entry, describeExecFailure(res))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyDeclaredDependencies checks that the isolated trees the installer was
|
||||
// told to create actually exist. Seeded source files surviving is not evidence
|
||||
// that pip/npm ran: those files were written server-side before the agent.
|
||||
func (s *TenantSkillService) verifyDeclaredDependencies(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if bundleHasPythonDeps(bundle) {
|
||||
venvPython := path.Join(skillDir, ".venv", "bin", "python")
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -x %s", sandbox.ShellQuote(venvPython))); err != nil {
|
||||
return fmt.Errorf("python dependencies were not installed into %s/.venv: %w", skillDir, err)
|
||||
}
|
||||
}
|
||||
if bundleHasNodeDeps(bundle) {
|
||||
nodeModules := path.Join(skillDir, "node_modules")
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -d %s", sandbox.ShellQuote(nodeModules))); err != nil {
|
||||
return fmt.Errorf("node dependencies were not installed into %s/node_modules: %w", skillDir, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeSkillPermissions makes the skill tree readable and executable by
|
||||
// the non-root execution user, and writable by nobody. Installs run as root,
|
||||
// so without the mode change the user that actually runs skills could not read
|
||||
// them at all — which is also why this runs before verification: the smoke
|
||||
// test has to exercise the permissions the snapshot will carry.
|
||||
// them at all — which is also why this runs before verification: the checks
|
||||
// read every script as that user, so they have to see the permissions the
|
||||
// snapshot will carry.
|
||||
//
|
||||
// Ownership stays with root rather than moving to the execution user because
|
||||
// this tree is baked into an image every session of the config inherits. A
|
||||
|
|
@ -763,8 +751,23 @@ func (s *TenantSkillService) normalizeSkillPermissions(
|
|||
func (s *TenantSkillService) cleanImageScratch(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID string,
|
||||
) error {
|
||||
user := sandbox.DefaultSandboxExecUser
|
||||
inputRoot := sandbox.ShellQuote(sandbox.SessionInputRoot)
|
||||
outputRoot := sandbox.ShellQuote(sandbox.SessionOutputRoot)
|
||||
cmds := []string{
|
||||
"rm -rf /workspace/* /workspace/.[!.]* || true",
|
||||
// The wipe above takes the base image's own input/output directories
|
||||
// with it, so every session booting from this snapshot would start on
|
||||
// a bare /workspace. Restoring them here is the only place with root:
|
||||
// a provider whose filesystem API runs as root would otherwise
|
||||
// recreate them root-owned, and the session account can neither write
|
||||
// them nor take them over.
|
||||
fmt.Sprintf(
|
||||
"mkdir -p %s %s && chown %s:%s %s %s && chmod 775 %s %s",
|
||||
inputRoot, outputRoot,
|
||||
user, user, inputRoot, outputRoot,
|
||||
inputRoot, outputRoot,
|
||||
),
|
||||
// Spelled out for both accounts on purpose: this runs as root, so "~"
|
||||
// would only ever clear root's caches, while the agent's own installs
|
||||
// populate the exec user's caches and those are what reach the image.
|
||||
|
|
@ -1459,48 +1462,17 @@ Hard requirements:
|
|||
- Each command has a 10-minute budget; you do not need to set timeout_sec.
|
||||
- When finished, report what you installed and any global/system packages you changed.
|
||||
|
||||
The server verifies the result itself before the image is kept, so report what
|
||||
you did rather than whether it passed. Verification parses every script with
|
||||
the interpreter that would run it, resolves the imports each one executes on
|
||||
load, and checks every distribution named in requirements.txt is present in the
|
||||
venv. It never runs the skill's code, so nothing is expected to answer --help.
|
||||
|
||||
SKILL.md:
|
||||
%s
|
||||
`, skillDir, uvAvailable, skillDir, skillDir, skillDir, skillMD)
|
||||
}
|
||||
|
||||
func primaryEntryScript(bundle *SkillBundle) string {
|
||||
if bundle == nil {
|
||||
return ""
|
||||
}
|
||||
preferred := []string{".py", ".js", ".mjs", ".sh"}
|
||||
for _, suffix := range preferred {
|
||||
var matches []string
|
||||
for rel := range bundle.Files {
|
||||
if strings.HasPrefix(rel, "scripts/") && strings.HasSuffix(rel, suffix) {
|
||||
matches = append(matches, rel)
|
||||
}
|
||||
}
|
||||
if len(matches) > 0 {
|
||||
sort.Strings(matches)
|
||||
return matches[0]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func bundleHasPythonDeps(bundle *SkillBundle) bool {
|
||||
if bundle == nil {
|
||||
return false
|
||||
}
|
||||
_, req := bundle.Files["requirements.txt"]
|
||||
_, pyproject := bundle.Files["pyproject.toml"]
|
||||
return req || pyproject
|
||||
}
|
||||
|
||||
func bundleHasNodeDeps(bundle *SkillBundle) bool {
|
||||
if bundle == nil {
|
||||
return false
|
||||
}
|
||||
_, ok := bundle.Files["package.json"]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *TenantSkillService) probeUv(ctx context.Context, mgr sandbox.Manager, sessionID string) bool {
|
||||
_, err := s.execInstall(ctx, mgr, sessionID, "uv --version")
|
||||
return err == nil
|
||||
|
|
@ -1608,35 +1580,6 @@ func (s *TenantSkillService) resolveInstallerModel(
|
|||
return nil, fmt.Errorf("workspace %d has no active chat model for skill installer", tenantID)
|
||||
}
|
||||
|
||||
func (s *TenantSkillService) execSmoke(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir, scriptPath string,
|
||||
) (*sandbox.ExecuteResult, error) {
|
||||
executor, err := installExecutor(mgr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The interpreter argv must survive intact. For Python it is
|
||||
// /bin/sh -c "<script referencing \"$@\">" <argv0>, so every element is
|
||||
// quoted as one literal word and --help is appended AFTER argv0, where it
|
||||
// becomes $1 of the inner script rather than a positional parameter of the
|
||||
// outer shell that nothing ever reads.
|
||||
cmd, args := sandbox.SkillInterpreterCommand(skillDir, scriptPath)
|
||||
words := []string{sandbox.ShellQuote(cmd)}
|
||||
for _, arg := range args {
|
||||
words = append(words, sandbox.ShellQuote(arg))
|
||||
}
|
||||
words = append(words, "--help")
|
||||
return executor.ExecShellCommandWithOptions(ctx, sessionID, strings.Join(words, " "),
|
||||
sandbox.ShellExecOptions{
|
||||
WorkDir: sandbox.SessionWorkspaceRoot,
|
||||
Timeout: installCommandTimeout,
|
||||
Env: map[string]string{
|
||||
"WEKNORA_SKILL_DIR": skillDir,
|
||||
"WEKNORA_SKILL_OUTPUT_DIR": sandbox.SessionOutputRoot,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *TenantSkillService) writeManifestEntry(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillID string, bundle *SkillBundle,
|
||||
) error {
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ func TestRunInstallHappyPathSwitchesPointerLast(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
require.Equal(t, []string{
|
||||
"create-session", "prepare-skill-dir", "seed-files", "agent-execute",
|
||||
"chmod", "verify-structure", "verify-smoke", "write-manifest",
|
||||
"chmod", "verify-structure", "verify-python", "write-manifest",
|
||||
"cleanup-workspace", "create-snapshot",
|
||||
"switch-pointer", "mark-stale", "destroy-sandbox",
|
||||
}, fx.events, "the pointer must move only after the snapshot exists")
|
||||
|
|
@ -60,8 +60,8 @@ func TestRunInstallHappyPathSwitchesPointerLast(t *testing.T) {
|
|||
"the pointer switch must be exactly one config write")
|
||||
require.Empty(t, fx.deletedSnapshots,
|
||||
"a successful install deletes nothing; the previous image stays reachable")
|
||||
require.False(t, fx.smokeRanAsRoot,
|
||||
"smoke must run as the ordinary sandbox user, not install-mode root")
|
||||
require.False(t, fx.loadCheckRanAsRoot,
|
||||
"script verification must run as the ordinary sandbox user, not install-mode root")
|
||||
require.Equal(t, []string{"Skill install"}, fx.sessionTitles)
|
||||
|
||||
skill, err := fx.skillRepo.GetSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
|
|
@ -112,7 +112,7 @@ func TestNextSnapshotGenerationSkipsAbandonedLedgerRows(t *testing.T) {
|
|||
// Ownership and permissions are normalised BEFORE verification on purpose: the
|
||||
// agent creates the tree as root, so a restrictive root umask would leave the
|
||||
// .venv interpreter unreadable and fail a perfectly good install in the
|
||||
// non-root smoke run. The smoke test must exercise the same permissions the
|
||||
// non-root verification pass, which must exercise the same permissions the
|
||||
// snapshot will carry.
|
||||
func TestRunInstallIssuesExactlyTheseCommands(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
|
|
@ -127,28 +127,20 @@ func TestRunInstallIssuesExactlyTheseCommands(t *testing.T) {
|
|||
"chown -R root:root " + installSkillDir,
|
||||
"test -f " + installSkillDir + "/SKILL.md",
|
||||
"test -f " + installSkillDir + "/scripts/extract.py",
|
||||
installSmokeCommand,
|
||||
installPythonVerifyCommand,
|
||||
"rm -rf /workspace/* /workspace/.[!.]* || true",
|
||||
installWorkspaceRestoreCommand,
|
||||
installCacheCleanupCommand,
|
||||
}, fx.commands)
|
||||
}
|
||||
|
||||
func TestRunInstallNormalisesPermissionsBeforeTheSmokeRun(t *testing.T) {
|
||||
func TestRunInstallNormalisesPermissionsBeforeVerifying(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
|
||||
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
|
||||
|
||||
require.Less(t, indexOfEvent(fx.events, "chmod"), indexOfEvent(fx.events, "verify-smoke"),
|
||||
"the non-root smoke run must execute the permissions that get snapshotted")
|
||||
}
|
||||
|
||||
func TestRunInstallSmokeCommandKeepsTheInterpreterArgv(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
|
||||
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
|
||||
|
||||
require.Contains(t, fx.commands, installSmokeCommand,
|
||||
"--help must reach the script as its own argument, not /bin/sh -c's")
|
||||
require.Less(t, indexOfEvent(fx.events, "chmod"), indexOfEvent(fx.events, "verify-python"),
|
||||
"the non-root verification pass must execute the permissions that get snapshotted")
|
||||
}
|
||||
|
||||
func TestRunInstallWipesThePreviousTreeBeforeSeeding(t *testing.T) {
|
||||
|
|
@ -191,9 +183,9 @@ func TestRunInstallReportsTransportFailureCause(t *testing.T) {
|
|||
"the admin's only diagnostic is this row")
|
||||
}
|
||||
|
||||
func TestRunInstallReportsSmokeFailureCause(t *testing.T) {
|
||||
func TestRunInstallReportsVerificationFailureCause(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.smokeResult = &sandbox.ExecuteResult{ExitCode: -1, Killed: true, Error: "sandbox unreachable"}
|
||||
fx.loadCheckResult = &sandbox.ExecuteResult{ExitCode: -1, Killed: true, Error: "sandbox unreachable"}
|
||||
|
||||
err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
|
||||
|
||||
|
|
@ -404,6 +396,76 @@ func TestInstallSkillRetriesAFailedSkillWithTheSameArchive(t *testing.T) {
|
|||
"a failed skill is a retry even when the archive digest is unchanged")
|
||||
}
|
||||
|
||||
// Most failed installs fail for a reason the archive cannot fix, so the retry
|
||||
// runs the bytes already stored rather than asking for them again.
|
||||
func TestReinstallSkillRerunsTheStoredArchive(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
archive := zipBundle(t, map[string]string{
|
||||
"SKILL.md": validSkillMD,
|
||||
"scripts/extract.py": "print('hi')\n",
|
||||
})
|
||||
bundle, err := ParseSkillBundle(archive)
|
||||
require.NoError(t, err)
|
||||
fx.storedBundles = map[string][]byte{"file://bundle.zip": archive}
|
||||
require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), &types.TenantSkillEntity{
|
||||
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
|
||||
Name: bundle.Name, BundleSHA256: bundle.SHA256, BundleRef: "file://bundle.zip",
|
||||
Status: types.SkillStatusFailed, Error: "python verification failed",
|
||||
}))
|
||||
|
||||
id, err := fx.svc.ReinstallSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "sk-1", id, "a retry upgrades the same row, it does not fork a second one")
|
||||
require.Positive(t, fx.getFileCalls.Load(),
|
||||
"the retry must come from the stored archive, not from a re-upload")
|
||||
}
|
||||
|
||||
// A row that says "installing" while still naming the previous run's session
|
||||
// tells every reader that the finished conversation is this run's live output.
|
||||
// The frontend believed it and replayed the last attempt's report as though it
|
||||
// were the retry's own progress, before the retry's agent had even started.
|
||||
func TestTakingARowForInstallDropsThePreviousRunsTranscript(t *testing.T) {
|
||||
row := &types.TenantSkillEntity{
|
||||
ID: "sk-1", Name: "pdf-tools", Status: types.SkillStatusFailed,
|
||||
Error: "python verification failed",
|
||||
InstallSessionID: "sess-old", InstallMessageID: "msg-old",
|
||||
}
|
||||
|
||||
takeSkillRowForInstall(row, &SkillBundle{Name: "pdf-tools", Version: "2.0.0"}, time.Now())
|
||||
|
||||
require.Equal(t, types.SkillStatusInstalling, row.Status)
|
||||
require.Empty(t, row.InstallSessionID, "the retry has no transcript of its own yet")
|
||||
require.Empty(t, row.InstallMessageID, "the retry has no transcript of its own yet")
|
||||
require.Empty(t, row.Error, "the previous failure is not this run's outcome")
|
||||
}
|
||||
|
||||
// Nothing a retry does can recover a skill whose archive is gone, and the
|
||||
// operator has to be told to upload it rather than to press the button again.
|
||||
func TestReinstallSkillRefusesWhenTheArchiveIsGone(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
require.NoError(t, fx.skillRepo.UpdateSkill(context.Background(), &types.TenantSkillEntity{
|
||||
ID: "sk-1", TenantID: 7, SandboxConfigID: "cfg-1",
|
||||
Name: "pdf-tools", Status: types.SkillStatusFailed, BundleRef: "",
|
||||
}))
|
||||
|
||||
_, err := fx.svc.ReinstallSkill(context.Background(), 7, "cfg-1", "sk-1")
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "no longer stored")
|
||||
require.Empty(t, fx.sessionCalls, "a retry that cannot run must not boot a billed sandbox")
|
||||
}
|
||||
|
||||
func TestReinstallSkillRejectsAnUnknownSkill(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
|
||||
_, err := fx.svc.ReinstallSkill(context.Background(), 7, "cfg-1", "nope")
|
||||
|
||||
require.Error(t, err)
|
||||
require.ErrorContains(t, err, "skill not found")
|
||||
require.Empty(t, fx.sessionCalls)
|
||||
}
|
||||
|
||||
func TestInstallSkillReinstallsWhenTheLiveImageNoLongerCarriesTheSkill(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
archive := zipBundle(t, map[string]string{
|
||||
|
|
@ -734,14 +796,92 @@ func TestRunInstallRequiresVenvWhenRequirementsExist(t *testing.T) {
|
|||
require.Nil(t, fx.configRepo.saved)
|
||||
}
|
||||
|
||||
func TestPrimaryEntryScriptIsDeterministic(t *testing.T) {
|
||||
// Verification used to run one guessed "entry script" with --help. Nothing in
|
||||
// the runtime designates an entry script — the model names whichever path it
|
||||
// likes in execute_skill_script — so the guess left every other file unchecked
|
||||
// while failing installs over the one it happened to pick.
|
||||
func TestRunInstallVerifiesEveryScriptOfEveryLanguage(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.bundle.Files["scripts/__init__.py"] = []byte("from .helper import run\n")
|
||||
fx.bundle.Files["scripts/helper.py"] = []byte("def run():\n pass\n")
|
||||
fx.bundle.Files["bin/render.mjs"] = []byte("export const x = 1;\n")
|
||||
fx.bundle.Files["bin/setup.sh"] = []byte("echo hi\n")
|
||||
|
||||
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
|
||||
|
||||
pythonPass := skillPythonVerifyCommand(installSkillDir, []string{
|
||||
"scripts/__init__.py", "scripts/extract.py", "scripts/helper.py",
|
||||
})
|
||||
require.Contains(t, fx.commands, pythonPass,
|
||||
"every python file must be checked, not the first one in sort order")
|
||||
require.Contains(t, fx.commands,
|
||||
skillNodeVerifyCommand(installSkillDir, []string{"bin/render.mjs"}, nil))
|
||||
require.Contains(t, fx.commands,
|
||||
skillShellVerifyCommand(installSkillDir, []string{"bin/setup.sh"}))
|
||||
}
|
||||
|
||||
// The pick that broke a real install: "__" sorts before every lowercase
|
||||
// letter, so a package marker became the smoke target and was executed as a
|
||||
// script, which no relative import can survive.
|
||||
func TestRunInstallDoesNotExecuteAnyScriptToVerifyIt(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.bundle.Files["scripts/__init__.py"] = []byte("from .extract import main\n")
|
||||
|
||||
require.NoError(t, fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle))
|
||||
|
||||
for _, command := range fx.commands {
|
||||
require.NotContains(t, command, "--help",
|
||||
"verification must not invoke a skill script; %q does", command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkillPythonVerifyCommandPrefersTheSkillVenv(t *testing.T) {
|
||||
command := skillPythonVerifyCommand("/opt/skills/demo", []string{"scripts/a.py"})
|
||||
|
||||
require.Contains(t, command, "if [ -x /opt/skills/demo/.venv/bin/python ]; "+
|
||||
"then py=/opt/skills/demo/.venv/bin/python; else py=python3; fi",
|
||||
"the file must be checked by the interpreter that would run it")
|
||||
require.True(t, strings.HasSuffix(command, `"$py" - /opt/skills/demo scripts/a.py`),
|
||||
"the verifier reads from stdin, so the paths are its argv")
|
||||
}
|
||||
|
||||
// A skill may ship a file whose name needs quoting; the command is assembled
|
||||
// by hand, so the shell must never see it as more than one word.
|
||||
func TestSkillVerifyCommandsQuoteAwkwardPaths(t *testing.T) {
|
||||
python := skillPythonVerifyCommand("/opt/skills/demo", []string{"scripts/a b'c.py"})
|
||||
require.Contains(t, python, `'scripts/a b'\''c.py'`)
|
||||
|
||||
shell := skillShellVerifyCommand("/opt/skills/demo", []string{"a b.sh"})
|
||||
require.Equal(t, `for f in '/opt/skills/demo/a b.sh'; do sh -n "$f" || exit 1; done`, shell)
|
||||
}
|
||||
|
||||
func TestSkillNodeVerifyCommandChecksDeclaredDependencies(t *testing.T) {
|
||||
bundle := &SkillBundle{Files: map[string][]byte{
|
||||
"package.json": []byte(`{"dependencies":{"echarts":"^5"},"devDependencies":{"jest":"^29"}}`),
|
||||
}}
|
||||
|
||||
require.Equal(t, []string{"echarts"}, nodeDependencyNames(bundle),
|
||||
"devDependencies are a build-time concern the image is not asked to carry")
|
||||
|
||||
command := skillNodeVerifyCommand("/opt/skills/demo", []string{"a.js"}, []string{"echarts"})
|
||||
require.Contains(t, command, `[ -e /opt/skills/demo/node_modules/"$d" ]`)
|
||||
require.Contains(t, command, `node --check "$f"`)
|
||||
}
|
||||
|
||||
func TestSortedScriptPathsIsDeterministic(t *testing.T) {
|
||||
bundle := &SkillBundle{Files: map[string][]byte{
|
||||
"scripts/z-helper.py": []byte("x"),
|
||||
"scripts/a-main.py": []byte("x"),
|
||||
"scripts/mid.js": []byte("x"),
|
||||
"SKILL.md": []byte("x"),
|
||||
"data/table.csv": []byte("x"),
|
||||
}}
|
||||
require.Equal(t, "scripts/a-main.py", primaryEntryScript(bundle),
|
||||
"python is preferred over js, and the name is sorted so the pick is stable")
|
||||
|
||||
require.Equal(t, []string{"scripts/a-main.py", "scripts/z-helper.py"},
|
||||
sortedScriptPaths(bundle, ".py"))
|
||||
require.Equal(t, []string{"scripts/a-main.py", "scripts/mid.js", "scripts/z-helper.py"},
|
||||
sortedScriptPaths(bundle, allScriptExtensions...),
|
||||
"only files the runtime can execute are scripts")
|
||||
}
|
||||
|
||||
type stubWorkspaceSandboxPolicy struct {
|
||||
|
|
@ -915,12 +1055,12 @@ func TestRunInstallDoesNotFailASkillThatIsAlreadyServing(t *testing.T) {
|
|||
require.Empty(t, skill.Error)
|
||||
}
|
||||
|
||||
func TestRunInstallKeepsOldImageWhenSmokeTestFails(t *testing.T) {
|
||||
func TestRunInstallKeepsOldImageWhenVerificationFails(t *testing.T) {
|
||||
fx := newInstallFixture(t)
|
||||
fx.configRepo.entity.Config.SkillImage = &types.SkillImageConfig{
|
||||
SnapshotID: "snap-old", Generation: 3, OwnerFingerprint: fx.fingerprint,
|
||||
}
|
||||
fx.smokeExitCode = 1
|
||||
fx.loadCheckExitCode = 1
|
||||
|
||||
err := fx.svc.runInstall(context.Background(), 7, "cfg-1", "sk-1", fx.bundle)
|
||||
|
||||
|
|
@ -1142,16 +1282,27 @@ const (
|
|||
" && chown user:user /opt/weknora/tenant/skills " + installSkillDir +
|
||||
" && chmod 755 /opt/weknora/tenant/skills " + installSkillDir
|
||||
|
||||
// The scratch wipe removes the base image's own input/output directories,
|
||||
// so the snapshot must carry them back with the ownership the session
|
||||
// account needs. This is the only step of an install that runs with the
|
||||
// privileges required to set that ownership.
|
||||
installWorkspaceRestoreCommand = "mkdir -p /workspace/input /workspace/output" +
|
||||
" && chown user:user /workspace/input /workspace/output" +
|
||||
" && chmod 775 /workspace/input /workspace/output"
|
||||
|
||||
installCacheCleanupCommand = "rm -rf " +
|
||||
"/root/.cache/pip /root/.cache/uv /root/.npm /root/.local/share/pnpm/store " +
|
||||
"/home/user/.cache/pip /home/user/.cache/uv /home/user/.npm " +
|
||||
"/home/user/.local/share/pnpm/store || true"
|
||||
)
|
||||
|
||||
installSmokeCommand = `/bin/sh -c 'if [ -x ` + installSkillDir + `/.venv/bin/python ]; ` +
|
||||
`then exec ` + installSkillDir + `/.venv/bin/python ` +
|
||||
installSkillDir + `/scripts/extract.py "$@"; ` +
|
||||
`else exec python3 ` + installSkillDir + `/scripts/extract.py "$@"; fi' ` +
|
||||
`weknora-skill --help`
|
||||
// installPythonVerifyCommand is built from the same helper the install path
|
||||
// uses. Pinning the literal text would mean re-encoding the embedded verifier
|
||||
// by hand on every edit to it, which is a test that fails for the wrong
|
||||
// reason; the properties worth stating verbatim are asserted separately in
|
||||
// TestSkillPythonVerifyCommand*.
|
||||
var installPythonVerifyCommand = skillPythonVerifyCommand(
|
||||
installSkillDir, []string{"scripts/extract.py"},
|
||||
)
|
||||
|
||||
func indexOfEvent(events []string, needle string) int {
|
||||
|
|
@ -1183,20 +1334,22 @@ type installFixture struct {
|
|||
// events are the coarse milestones the ordering tests read; commands is
|
||||
// the full, ordered shell transcript so a new command can never hide
|
||||
// behind an older substring match.
|
||||
events []string
|
||||
commands []string
|
||||
fingerprint string
|
||||
smokeExitCode int
|
||||
smokeResult *sandbox.ExecuteResult
|
||||
events []string
|
||||
commands []string
|
||||
fingerprint string
|
||||
// loadCheck* drive the per-language script verification pass, which is
|
||||
// the last gate before the snapshot.
|
||||
loadCheckExitCode int
|
||||
loadCheckResult *sandbox.ExecuteResult
|
||||
// depsExitCode fails the declared-dependency check (venv / node_modules).
|
||||
depsExitCode int
|
||||
// execResult is scoped to execResultCommand: an unscoped stub result
|
||||
// applies to the first command issued, which is not the command any of
|
||||
// these tests is about.
|
||||
execResultCommand string
|
||||
execResult *sandbox.ExecuteResult
|
||||
smokeRanAsRoot bool
|
||||
agentErr error
|
||||
execResultCommand string
|
||||
execResult *sandbox.ExecuteResult
|
||||
loadCheckRanAsRoot bool
|
||||
agentErr error
|
||||
// beforeExecute runs at the moment the engine would start, so a test can
|
||||
// observe the state an attaching console would see mid-install.
|
||||
beforeExecute func()
|
||||
|
|
@ -1856,13 +2009,15 @@ func (m *installSandboxManager) ExecShellCommandWithOptions(
|
|||
if m.fx.depsExitCode != 0 {
|
||||
return &sandbox.ExecuteResult{ExitCode: m.fx.depsExitCode, Stderr: "deps missing"}, nil
|
||||
}
|
||||
case command == installSmokeCommand:
|
||||
m.fx.smokeRanAsRoot = opts.AsRoot
|
||||
m.fx.record("verify-smoke")
|
||||
if m.fx.smokeResult != nil {
|
||||
return m.fx.smokeResult, nil
|
||||
case command == installPythonVerifyCommand:
|
||||
m.fx.loadCheckRanAsRoot = opts.AsRoot
|
||||
m.fx.record("verify-python")
|
||||
if m.fx.loadCheckResult != nil {
|
||||
return m.fx.loadCheckResult, nil
|
||||
}
|
||||
return &sandbox.ExecuteResult{ExitCode: m.fx.smokeExitCode, Stderr: "smoke failed"}, nil
|
||||
return &sandbox.ExecuteResult{
|
||||
ExitCode: m.fx.loadCheckExitCode, Stderr: "scripts/extract.py imports pandas",
|
||||
}, nil
|
||||
case command == removeSkillDirCommand:
|
||||
m.fx.record("remove-skill-dir")
|
||||
if m.fx.removeDelay > 0 {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,275 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/sandbox"
|
||||
)
|
||||
|
||||
// skillPythonVerifier is the source of the in-sandbox Python checker. It is
|
||||
// shipped as a file rather than a Go string literal so it can be linted and
|
||||
// read as Python; the install path base64-encodes it into one shell command.
|
||||
//
|
||||
//go:embed tenant_skill_verify.py
|
||||
var skillPythonVerifier string
|
||||
|
||||
// verifySkill is the server's own check, and the last gate before the image
|
||||
// pointer moves: a broken install must leave the previous snapshot serving.
|
||||
//
|
||||
// It deliberately proves loadability rather than behaviour. Nothing in the
|
||||
// runtime designates an entry point — the model names any script it likes in
|
||||
// execute_skill_script — so there is no single command whose success would
|
||||
// stand in for the skill working. What every one of those calls does need is
|
||||
// that the interpreter can parse the file and resolve its imports inside this
|
||||
// image, and that is checkable for all scripts at once without executing a
|
||||
// line of the skill's own code.
|
||||
//
|
||||
// Not executing is the point, not a limitation. The previous implementation
|
||||
// ran one guessed script with --help; skills that do not parse arguments
|
||||
// simply ran their whole main path inside the tree about to be snapshotted.
|
||||
func (s *TenantSkillService) verifySkill(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if err := s.verifySkillTree(ctx, mgr, sessionID, skillDir, bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.verifyDeclaredDependencies(ctx, mgr, sessionID, skillDir, bundle); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.verifyScriptsLoad(ctx, mgr, sessionID, skillDir, bundle)
|
||||
}
|
||||
|
||||
// verifySkillTree confirms the files the agent was given are still the files
|
||||
// the image carries. The agent has a root shell in this directory, so "we
|
||||
// wrote it before the agent ran" is not evidence that it survived.
|
||||
func (s *TenantSkillService) verifySkillTree(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -f %s", sandbox.ShellQuote(path.Join(skillDir, "SKILL.md")))); err != nil {
|
||||
return fmt.Errorf("skill directory is incomplete after install: %w", err)
|
||||
}
|
||||
for _, rel := range sortedScriptPaths(bundle, allScriptExtensions...) {
|
||||
target := path.Join(skillDir, rel)
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -f %s", sandbox.ShellQuote(target))); err != nil {
|
||||
return fmt.Errorf("script %s is missing after install: %w", rel, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyDeclaredDependencies checks that the isolated trees the installer was
|
||||
// told to create actually exist. Seeded source files surviving is not evidence
|
||||
// that pip/npm ran: those files were written server-side before the agent.
|
||||
//
|
||||
// This is only the shape of the install. Whether the individual packages
|
||||
// landed is checked by the language passes below, which read the manifests.
|
||||
func (s *TenantSkillService) verifyDeclaredDependencies(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if bundleHasPythonDeps(bundle) {
|
||||
venvPython := path.Join(skillDir, ".venv", "bin", "python")
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -x %s", sandbox.ShellQuote(venvPython))); err != nil {
|
||||
return fmt.Errorf("python dependencies were not installed into %s/.venv: %w", skillDir, err)
|
||||
}
|
||||
}
|
||||
if bundleHasNodeDeps(bundle) {
|
||||
nodeModules := path.Join(skillDir, "node_modules")
|
||||
if _, err := s.execInstall(ctx, mgr, sessionID,
|
||||
fmt.Sprintf("test -d %s", sandbox.ShellQuote(nodeModules))); err != nil {
|
||||
return fmt.Errorf("node dependencies were not installed into %s/node_modules: %w", skillDir, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyScriptsLoad runs one pass per language present in the bundle. Each
|
||||
// pass covers every script of that language, because every one of them is a
|
||||
// script the model may name at runtime.
|
||||
func (s *TenantSkillService) verifyScriptsLoad(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir string, bundle *SkillBundle,
|
||||
) error {
|
||||
if scripts := sortedScriptPaths(bundle, ".py"); len(scripts) > 0 {
|
||||
if err := s.execVerify(ctx, mgr, sessionID, skillDir, "python",
|
||||
skillPythonVerifyCommand(skillDir, scripts)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if scripts := sortedScriptPaths(bundle, ".js", ".mjs"); len(scripts) > 0 {
|
||||
if err := s.execVerify(ctx, mgr, sessionID, skillDir, "node",
|
||||
skillNodeVerifyCommand(skillDir, scripts, nodeDependencyNames(bundle))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if scripts := sortedScriptPaths(bundle, ".sh"); len(scripts) > 0 {
|
||||
if err := s.execVerify(ctx, mgr, sessionID, skillDir, "shell",
|
||||
skillShellVerifyCommand(skillDir, scripts)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// execVerify runs one verification pass as the ordinary sandbox user, with the
|
||||
// same working directory and environment a real skill call gets. Running it as
|
||||
// install-mode root would test permissions that never reach a session.
|
||||
func (s *TenantSkillService) execVerify(
|
||||
ctx context.Context, mgr sandbox.Manager, sessionID, skillDir, label, command string,
|
||||
) error {
|
||||
executor, err := installExecutor(mgr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := executor.ExecShellCommandWithOptions(ctx, sessionID, command,
|
||||
sandbox.ShellExecOptions{
|
||||
WorkDir: sandbox.SessionWorkspaceRoot,
|
||||
Timeout: installCommandTimeout,
|
||||
Env: map[string]string{
|
||||
"WEKNORA_SKILL_DIR": skillDir,
|
||||
"WEKNORA_SKILL_OUTPUT_DIR": sandbox.SessionOutputRoot,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s verification: %w", label, err)
|
||||
}
|
||||
if res.ExitCode != 0 {
|
||||
return fmt.Errorf("%s verification failed (%s)", label, describeExecFailure(res))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// skillPythonVerifyCommand pipes the verifier into the same interpreter a
|
||||
// runtime skill call would use, and names the files to check on the command
|
||||
// line. The list is explicit rather than a directory walk so the pass covers
|
||||
// exactly the uploaded sources — never .venv, node_modules or anything else
|
||||
// the agent created while installing.
|
||||
func skillPythonVerifyCommand(skillDir string, scripts []string) string {
|
||||
venv := path.Join(skillDir, ".venv", "bin", "python")
|
||||
quotedVenv := sandbox.ShellQuote(venv)
|
||||
args := []string{sandbox.ShellQuote(skillDir)}
|
||||
for _, rel := range scripts {
|
||||
args = append(args, sandbox.ShellQuote(rel))
|
||||
}
|
||||
// The script arrives base64-encoded on stdin: it contains quotes, newlines
|
||||
// and backslashes, and a heredoc would still be at the mercy of whatever
|
||||
// the remote exec layer does with multi-line command strings.
|
||||
return fmt.Sprintf(
|
||||
"if [ -x %s ]; then py=%s; else py=python3; fi; printf %%s '%s' | base64 -d | \"$py\" - %s",
|
||||
quotedVenv, quotedVenv,
|
||||
base64.StdEncoding.EncodeToString([]byte(skillPythonVerifier)),
|
||||
strings.Join(args, " "),
|
||||
)
|
||||
}
|
||||
|
||||
// skillNodeVerifyCommand parses every JavaScript file and, when the bundle
|
||||
// declares runtime dependencies, checks each one resolves. `node --check` is
|
||||
// parse-only: it never runs the module body.
|
||||
func skillNodeVerifyCommand(skillDir string, scripts, deps []string) string {
|
||||
parts := make([]string, 0, 2)
|
||||
if len(deps) > 0 {
|
||||
quoted := make([]string, 0, len(deps))
|
||||
for _, dep := range deps {
|
||||
quoted = append(quoted, sandbox.ShellQuote(dep))
|
||||
}
|
||||
parts = append(parts, fmt.Sprintf(
|
||||
"for d in %s; do [ -e %s/\"$d\" ] || "+
|
||||
"{ echo \"package.json declares $d but node_modules/$d is missing\" >&2; exit 1; }; done",
|
||||
strings.Join(quoted, " "), sandbox.ShellQuote(path.Join(skillDir, "node_modules")),
|
||||
))
|
||||
}
|
||||
parts = append(parts, forEachScript(skillDir, scripts, "node --check \"$f\""))
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// skillShellVerifyCommand parses every shell script. `sh -n` reads the file
|
||||
// and exits without executing any of it.
|
||||
func skillShellVerifyCommand(skillDir string, scripts []string) string {
|
||||
return forEachScript(skillDir, scripts, "sh -n \"$f\"")
|
||||
}
|
||||
|
||||
func forEachScript(skillDir string, scripts []string, check string) string {
|
||||
quoted := make([]string, 0, len(scripts))
|
||||
for _, rel := range scripts {
|
||||
quoted = append(quoted, sandbox.ShellQuote(path.Join(skillDir, rel)))
|
||||
}
|
||||
return fmt.Sprintf("for f in %s; do %s || exit 1; done", strings.Join(quoted, " "), check)
|
||||
}
|
||||
|
||||
// allScriptExtensions is every suffix the runtime knows how to execute, which
|
||||
// is what makes a bundle file a script the model can name.
|
||||
var allScriptExtensions = []string{".py", ".js", ".mjs", ".sh"}
|
||||
|
||||
// sortedScriptPaths returns the bundle's files with any of the given suffixes,
|
||||
// in a stable order so the emitted command is deterministic.
|
||||
func sortedScriptPaths(bundle *SkillBundle, suffixes ...string) []string {
|
||||
if bundle == nil {
|
||||
return nil
|
||||
}
|
||||
var matches []string
|
||||
for rel := range bundle.Files {
|
||||
for _, suffix := range suffixes {
|
||||
if strings.HasSuffix(rel, suffix) {
|
||||
matches = append(matches, rel)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(matches)
|
||||
return matches
|
||||
}
|
||||
|
||||
// nodeDependencyNames lists the runtime dependencies package.json declares.
|
||||
// devDependencies are excluded: they are a build-time concern and the image
|
||||
// is not asked to carry them.
|
||||
func nodeDependencyNames(bundle *SkillBundle) []string {
|
||||
if bundle == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := bundle.Files["package.json"]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
var manifest struct {
|
||||
Dependencies map[string]string `json:"dependencies"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||
// A package.json the installer could not read is the agent's problem
|
||||
// to report, not a reason to fail verification on a parse we only
|
||||
// needed for a nicer error message.
|
||||
return nil
|
||||
}
|
||||
names := make([]string, 0, len(manifest.Dependencies))
|
||||
for name := range manifest.Dependencies {
|
||||
if strings.TrimSpace(name) != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
func bundleHasPythonDeps(bundle *SkillBundle) bool {
|
||||
if bundle == nil {
|
||||
return false
|
||||
}
|
||||
_, req := bundle.Files["requirements.txt"]
|
||||
_, pyproject := bundle.Files["pyproject.toml"]
|
||||
return req || pyproject
|
||||
}
|
||||
|
||||
func bundleHasNodeDeps(bundle *SkillBundle) bool {
|
||||
if bundle == nil {
|
||||
return false
|
||||
}
|
||||
_, ok := bundle.Files["package.json"]
|
||||
return ok
|
||||
}
|
||||
|
|
@ -0,0 +1,255 @@
|
|||
"""Verify that an installed skill's Python sources can be loaded in this image.
|
||||
|
||||
Run inside the sandbox, by the interpreter a real skill call would use, as the
|
||||
ordinary execution user, after the tree has been given its final permissions:
|
||||
|
||||
python3 - <skill-dir> <relative-script> [<relative-script> ...]
|
||||
|
||||
Nothing here executes the skill's own code. Everything it reports is decided
|
||||
from the parse tree and from what the environment can resolve, so a skill that
|
||||
writes files or calls the network on import cannot do either while being
|
||||
checked, and a script that never learned --help cannot be failed for it.
|
||||
|
||||
Exits 1 and writes one line per problem to stderr; exits 0 otherwise.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
root = os.path.abspath(sys.argv[1])
|
||||
relative_scripts = sys.argv[2:]
|
||||
problems = []
|
||||
|
||||
# Directories that belong to the installed environment rather than the skill's
|
||||
# own sources, and would drown the scan below in third-party module names.
|
||||
PRUNED = {".venv", "venv", "node_modules", "__pycache__", ".git"}
|
||||
|
||||
|
||||
def under_root(candidate):
|
||||
return candidate == root or candidate.startswith(root + os.sep)
|
||||
|
||||
|
||||
def own_top_level_names():
|
||||
"""Top-level names that refer to something the skill itself ships.
|
||||
|
||||
Only the skill root is consulted. A nested file such as vendor/requests.py
|
||||
must not make `import requests` look first-party — that name is a
|
||||
dependency the installer was asked to put in the venv, and skipping it
|
||||
would snapshot a broken install.
|
||||
|
||||
An import of one of these is the skill reaching for its own code, and
|
||||
whether it resolves depends on how the script arranges sys.path at run
|
||||
time — commonly by inserting its parent before importing `scripts.x`.
|
||||
That is a runtime decision this checker cannot evaluate without executing
|
||||
the file, so such imports are left to the skill. Sibling modules still
|
||||
resolve through find_spec, which puts the script's own directory first.
|
||||
"""
|
||||
names = set()
|
||||
try:
|
||||
entries = os.listdir(root)
|
||||
except OSError:
|
||||
return names
|
||||
for name in entries:
|
||||
if name in PRUNED or name.startswith("."):
|
||||
continue
|
||||
full = os.path.join(root, name)
|
||||
if os.path.isdir(full):
|
||||
names.add(name)
|
||||
elif name.endswith(".py"):
|
||||
names.add(name[:-3])
|
||||
return names
|
||||
|
||||
|
||||
own_modules = own_top_level_names()
|
||||
|
||||
|
||||
def is_package(directory):
|
||||
return os.path.isfile(os.path.join(directory, "__init__.py"))
|
||||
|
||||
|
||||
def module_exists(base, dotted):
|
||||
"""Whether a dotted name resolves to a file or package under base."""
|
||||
target = os.path.join(base, *dotted.split(".")) if dotted else base
|
||||
return os.path.isfile(target + ".py") or os.path.isfile(
|
||||
os.path.join(target, "__init__.py")
|
||||
)
|
||||
|
||||
|
||||
def is_importable(name, script_dir):
|
||||
"""Whether a top-level name is available to this script at run time.
|
||||
|
||||
find_spec consults the finders without importing, so a missing dependency
|
||||
is reported without the side effects of loading a present one. script_dir
|
||||
leads the path because that is where the interpreter puts the directory of
|
||||
the script it was handed, which is how sibling modules resolve at runtime.
|
||||
"""
|
||||
if name in own_modules:
|
||||
return True
|
||||
saved = sys.path[:]
|
||||
sys.path.insert(0, script_dir)
|
||||
try:
|
||||
return importlib.util.find_spec(name) is not None
|
||||
except Exception:
|
||||
return False
|
||||
finally:
|
||||
sys.path[:] = saved
|
||||
|
||||
|
||||
def check_imports(rel, tree, script_dir):
|
||||
"""Check the imports that running this file is guaranteed to execute.
|
||||
|
||||
Only statements at module level are checked, and only unconditionally: an
|
||||
import nested in try/except, in an `if`, or inside a function is how a
|
||||
skill declares an optional or lazily loaded dependency, and failing an
|
||||
install over one would reject a working skill.
|
||||
"""
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
top = alias.name.split(".")[0]
|
||||
if not is_importable(top, script_dir):
|
||||
problems.append(
|
||||
"%s imports %s, which is not available in this image"
|
||||
% (rel, top)
|
||||
)
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.level:
|
||||
check_relative_import(rel, node, script_dir)
|
||||
elif node.module:
|
||||
top = node.module.split(".")[0]
|
||||
if not is_importable(top, script_dir):
|
||||
problems.append(
|
||||
"%s imports %s, which is not available in this image"
|
||||
% (rel, top)
|
||||
)
|
||||
|
||||
|
||||
def check_relative_import(rel, node, script_dir):
|
||||
spelling = "." * node.level + (node.module or "")
|
||||
if not is_package(script_dir):
|
||||
problems.append(
|
||||
"%s uses the relative import '%s' but its directory has no "
|
||||
"__init__.py, so the import can never resolve when the script is "
|
||||
"run directly" % (rel, spelling)
|
||||
)
|
||||
return
|
||||
base = script_dir
|
||||
for _ in range(node.level - 1):
|
||||
base = os.path.dirname(base)
|
||||
if not under_root(base):
|
||||
problems.append(
|
||||
"%s uses the relative import '%s', which reaches outside the "
|
||||
"skill directory" % (rel, spelling)
|
||||
)
|
||||
return
|
||||
# A bare `from . import name` may be pulling something the package's
|
||||
# __init__ defines rather than a submodule, so only the package itself is
|
||||
# checked in that case.
|
||||
if node.module and not module_exists(base, node.module):
|
||||
problems.append(
|
||||
"%s imports '%s', which does not exist in the skill" % (rel, spelling)
|
||||
)
|
||||
|
||||
|
||||
def distribution_name(raw):
|
||||
"""The distribution a requirement line names, or '' if it cannot be read.
|
||||
|
||||
Options (-r, -e, --index-url), VCS URLs, local paths and archives name no
|
||||
distribution of their own, and inventing one would fail an install over a
|
||||
requirement that is present.
|
||||
"""
|
||||
line = raw.split("#")[0].strip()
|
||||
if not line or line.startswith("-"):
|
||||
return ""
|
||||
name = re.split(r"[\s<>=!~;\[@]", line)[0].strip()
|
||||
if not re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", name):
|
||||
return ""
|
||||
return name
|
||||
|
||||
|
||||
def load_pyproject(path):
|
||||
try:
|
||||
import tomllib
|
||||
except ImportError:
|
||||
return None
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
return tomllib.load(handle)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def declared_requirement_lines():
|
||||
"""(source, requirement-line) pairs from requirements.txt and pyproject.toml."""
|
||||
requirements = os.path.join(root, "requirements.txt")
|
||||
if os.path.isfile(requirements):
|
||||
with open(requirements, encoding="utf-8", errors="replace") as handle:
|
||||
for line in handle:
|
||||
yield "requirements.txt", line
|
||||
pyproject = os.path.join(root, "pyproject.toml")
|
||||
if not os.path.isfile(pyproject):
|
||||
return
|
||||
data = load_pyproject(pyproject)
|
||||
if not data:
|
||||
return
|
||||
for item in data.get("project", {}).get("dependencies") or []:
|
||||
if isinstance(item, str):
|
||||
yield "pyproject.toml", item
|
||||
poetry = ((data.get("tool") or {}).get("poetry") or {}).get("dependencies") or {}
|
||||
if isinstance(poetry, dict):
|
||||
for name in poetry:
|
||||
if str(name).strip().lower() == "python":
|
||||
continue
|
||||
yield "pyproject.toml", str(name)
|
||||
|
||||
|
||||
def check_declared_requirements():
|
||||
try:
|
||||
from importlib import metadata
|
||||
except ImportError:
|
||||
return
|
||||
for source, raw in declared_requirement_lines():
|
||||
name = distribution_name(raw)
|
||||
if not name:
|
||||
continue
|
||||
try:
|
||||
metadata.distribution(name)
|
||||
except Exception:
|
||||
problems.append(
|
||||
"%s declares %s but it is not installed in %s"
|
||||
% (source, name, sys.prefix)
|
||||
)
|
||||
|
||||
|
||||
for relative in relative_scripts:
|
||||
script = os.path.join(root, relative)
|
||||
try:
|
||||
with open(script, "rb") as source:
|
||||
code = source.read()
|
||||
except OSError as exc:
|
||||
problems.append(
|
||||
"%s cannot be read by the skill execution user (%s)" % (relative, exc)
|
||||
)
|
||||
continue
|
||||
try:
|
||||
parsed = ast.parse(code, filename=relative)
|
||||
except SyntaxError as exc:
|
||||
problems.append(
|
||||
"%s has a syntax error on line %s: %s" % (relative, exc.lineno, exc.msg)
|
||||
)
|
||||
continue
|
||||
check_imports(relative, parsed, os.path.dirname(script))
|
||||
|
||||
check_declared_requirements()
|
||||
|
||||
if problems:
|
||||
sys.stderr.write("\n".join(problems) + "\n")
|
||||
sys.exit(1)
|
||||
|
||||
print(
|
||||
"verified %d python file(s) against %s"
|
||||
% (len(relative_scripts), sys.executable or "python3")
|
||||
)
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The Go tests above pin which commands an install issues. These run the
|
||||
// embedded checker itself, because its judgement is what decides whether a
|
||||
// working skill installs — and a check that is too strict fails good skills
|
||||
// just as surely as one that is too loose passes broken ones. Every case here
|
||||
// is a shape a real skill ships.
|
||||
func TestSkillPythonVerifier(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
files map[string]string
|
||||
// wantProblem is a substring of the expected stderr. Empty means the
|
||||
// tree must verify cleanly.
|
||||
wantProblem string
|
||||
}{{
|
||||
name: "a package whose __init__ imports its own submodules",
|
||||
files: map[string]string{
|
||||
"scripts/__init__.py": "from .chart_generator import ChartGenerator\n",
|
||||
"scripts/chart_generator.py": "class ChartGenerator:\n pass\n",
|
||||
},
|
||||
}, {
|
||||
// The shape that failed a real install: sys.path is rearranged at run
|
||||
// time, so the absolute import of the skill's own package resolves
|
||||
// only once the file executes. Deciding it statically is not possible,
|
||||
// and guessing wrong rejects a working skill.
|
||||
name: "a script that puts the skill root on sys.path and imports its own package",
|
||||
files: map[string]string{
|
||||
"scripts/__init__.py": "",
|
||||
"scripts/helper.py": "def go():\n pass\n",
|
||||
"scripts/ux_regression_check.py": "import sys\n" +
|
||||
"from pathlib import Path\n" +
|
||||
"sys.path.insert(0, str(Path(__file__).resolve().parent.parent))\n" +
|
||||
"from scripts.helper import go\n",
|
||||
},
|
||||
}, {
|
||||
name: "a script importing a sibling module directly",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "import helper\n",
|
||||
"scripts/helper.py": "x = 1\n",
|
||||
"scripts/README.txt": "not python\n",
|
||||
},
|
||||
}, {
|
||||
name: "an optional dependency behind try/except",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "try:\n import matplotlib\nexcept ImportError:\n" +
|
||||
" matplotlib = None\n",
|
||||
},
|
||||
}, {
|
||||
name: "a dependency imported lazily inside a function",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "def render():\n import matplotlib\n return matplotlib\n",
|
||||
},
|
||||
}, {
|
||||
name: "a dependency the installer never installed",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "import totally_absent_package\n",
|
||||
},
|
||||
wantProblem: "scripts/run.py imports totally_absent_package, " +
|
||||
"which is not available in this image",
|
||||
}, {
|
||||
name: "a syntax error",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "def broken(:\n pass\n",
|
||||
},
|
||||
wantProblem: "scripts/run.py has a syntax error on line 1",
|
||||
}, {
|
||||
name: "a relative import in a directory that is not a package",
|
||||
files: map[string]string{
|
||||
"scripts/run.py": "from .helper import go\n",
|
||||
"scripts/helper.py": "def go():\n pass\n",
|
||||
"scripts/notinit.py": "",
|
||||
},
|
||||
wantProblem: "has no __init__.py",
|
||||
}, {
|
||||
name: "a relative import of a module the skill does not ship",
|
||||
files: map[string]string{
|
||||
"pkg/__init__.py": "",
|
||||
"pkg/sub/__init__.py": "",
|
||||
"pkg/sub/run.py": "from ..missing import go\n",
|
||||
},
|
||||
wantProblem: "pkg/sub/run.py imports '..missing', which does not exist in the skill",
|
||||
}, {
|
||||
name: "a requirement the venv does not carry",
|
||||
files: map[string]string{
|
||||
"requirements.txt": "# pinned\npandas==3.0.1\n-r other.txt\n" +
|
||||
"totally_absent_package>=1.0 ; python_version>=\"3.9\"\n",
|
||||
"scripts/run.py": "x = 1\n",
|
||||
},
|
||||
wantProblem: "requirements.txt declares totally_absent_package but it is not installed",
|
||||
}, {
|
||||
name: "a nested file name is not treated as a first-party import",
|
||||
files: map[string]string{
|
||||
"vendor/totally_absent_package.py": "x = 1\n",
|
||||
"scripts/run.py": "import totally_absent_package\n",
|
||||
},
|
||||
wantProblem: "scripts/run.py imports totally_absent_package, " +
|
||||
"which is not available in this image",
|
||||
}, {
|
||||
name: "a pyproject.toml dependency the venv does not carry",
|
||||
files: map[string]string{
|
||||
"pyproject.toml": "[project]\nname = \"demo\"\ndependencies = [\n" +
|
||||
" \"totally_absent_package>=1.0\",\n]\n",
|
||||
"scripts/run.py": "x = 1\n",
|
||||
},
|
||||
wantProblem: "pyproject.toml declares totally_absent_package but it is not installed",
|
||||
}, {
|
||||
// Lines that name a distribution only indirectly cannot be checked by
|
||||
// name, and inventing one from the URL would fail installs whose
|
||||
// requirements are all present.
|
||||
name: "requirements that point at a VCS, an archive or a local path",
|
||||
files: map[string]string{
|
||||
"requirements.txt": "git+https://example.com/x/y.git#egg=y\n" +
|
||||
"./vendor/local-wheel.whl\n" +
|
||||
"https://example.com/pkg-1.0.tar.gz\n" +
|
||||
"--index-url https://example.com/simple\n",
|
||||
"scripts/run.py": "x = 1\n",
|
||||
},
|
||||
}}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
root := writeSkillTree(t, tc.files)
|
||||
stdout, stderr, err := runSkillPythonVerifier(t, root, pythonFiles(tc.files))
|
||||
|
||||
if tc.wantProblem == "" {
|
||||
require.NoError(t, err, "this skill must install; stderr: %s", stderr)
|
||||
require.Contains(t, stdout, "verified")
|
||||
return
|
||||
}
|
||||
require.Error(t, err, "this skill is broken and must not reach a snapshot")
|
||||
require.Contains(t, stderr, tc.wantProblem)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Verification must be able to read a skill that writes files or opens sockets
|
||||
// the moment it is imported, without doing either.
|
||||
func TestSkillPythonVerifierNeverExecutesTheSkill(t *testing.T) {
|
||||
root := writeSkillTree(t, map[string]string{
|
||||
"scripts/run.py": "import os\n" +
|
||||
"open(os.path.join(os.path.dirname(__file__), 'SIDE_EFFECT'), 'w').close()\n",
|
||||
})
|
||||
|
||||
_, stderr, err := runSkillPythonVerifier(t, root, []string{"scripts/run.py"})
|
||||
|
||||
require.NoError(t, err, stderr)
|
||||
_, statErr := os.Stat(filepath.Join(root, "scripts", "SIDE_EFFECT"))
|
||||
require.True(t, os.IsNotExist(statErr),
|
||||
"the checker ran the skill's module body instead of reading it")
|
||||
}
|
||||
|
||||
// The skill tree is owned by root and readable by everyone; a file the
|
||||
// execution user cannot open is an install that would fail on first use.
|
||||
func TestSkillPythonVerifierReportsAnUnreadableScript(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root can read a 000 file, so this states nothing when tests run as root")
|
||||
}
|
||||
root := writeSkillTree(t, map[string]string{"scripts/run.py": "x = 1\n"})
|
||||
require.NoError(t, os.Chmod(filepath.Join(root, "scripts", "run.py"), 0o000))
|
||||
|
||||
_, stderr, err := runSkillPythonVerifier(t, root, []string{"scripts/run.py"})
|
||||
|
||||
require.Error(t, err)
|
||||
require.Contains(t, stderr, "cannot be read by the skill execution user")
|
||||
}
|
||||
|
||||
func writeSkillTree(t *testing.T, files map[string]string) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for rel, content := range files {
|
||||
full := filepath.Join(root, filepath.FromSlash(rel))
|
||||
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o755))
|
||||
require.NoError(t, os.WriteFile(full, []byte(content), 0o644))
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func pythonFiles(files map[string]string) []string {
|
||||
var scripts []string
|
||||
for rel := range files {
|
||||
if strings.HasSuffix(rel, ".py") {
|
||||
scripts = append(scripts, rel)
|
||||
}
|
||||
}
|
||||
sort.Strings(scripts)
|
||||
return scripts
|
||||
}
|
||||
|
||||
// runSkillPythonVerifier feeds the embedded checker to a real interpreter the
|
||||
// same way the sandbox command does: on stdin, with the tree and the files to
|
||||
// check as argv.
|
||||
func runSkillPythonVerifier(t *testing.T, root string, scripts []string) (string, string, error) {
|
||||
t.Helper()
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 is not on PATH")
|
||||
}
|
||||
cmd := exec.Command(python, append([]string{"-", root}, scripts...)...)
|
||||
cmd.Stdin = strings.NewReader(skillPythonVerifier)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
runErr := cmd.Run()
|
||||
return stdout.String(), stderr.String(), runErr
|
||||
}
|
||||
|
|
@ -57,6 +57,7 @@ type sandboxSkillService interface {
|
|||
InstallSkillFromSource(
|
||||
ctx context.Context, tenantID uint64, configID, source string,
|
||||
) (string, error)
|
||||
ReinstallSkill(ctx context.Context, tenantID uint64, configID, skillID string) (string, error)
|
||||
RemoveSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
|
||||
LastProgress(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string,
|
||||
|
|
@ -351,6 +352,31 @@ func (h *SandboxSkillHandler) installFromSource(c *gin.Context) {
|
|||
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
|
||||
}
|
||||
|
||||
// Reinstall godoc
|
||||
// @Summary Retry a skill install
|
||||
// @Description Retry a failed install from the stored archive; does not re-upload.
|
||||
// @Tags SandboxConfig
|
||||
// @Produce json
|
||||
// @Param id path string true "Sandbox config ID"
|
||||
// @Param skillId path string true "Skill ID"
|
||||
// @Success 202 {object} map[string]interface{} "Reinstall accepted"
|
||||
// @Failure 400 {object} apperrors.AppError "The stored archive is gone"
|
||||
// @Failure 401 {object} map[string]interface{} "Unauthorized"
|
||||
// @Failure 404 {object} apperrors.AppError "Skill not found"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /sandbox-configs/{id}/skills/{skillId}/reinstall [post]
|
||||
func (h *SandboxSkillHandler) Reinstall(c *gin.Context) {
|
||||
skillID, err := h.service.ReinstallSkill(
|
||||
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), c.Param("skillId"),
|
||||
)
|
||||
if err != nil {
|
||||
respondSkillServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
|
||||
}
|
||||
|
||||
func skillTooLargeError() error {
|
||||
return apperrors.NewBadRequestError(
|
||||
fmt.Sprintf("skill bundle cannot exceed %d MB", secutils.GetMaxFileSizeMB()))
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ type fakeSandboxSkillService struct {
|
|||
installErr error
|
||||
installSource string
|
||||
sourceErr error
|
||||
reinstallErr error
|
||||
removeErr error
|
||||
|
||||
files []service.SkillFileEntry
|
||||
|
|
@ -61,11 +62,16 @@ type fakeSandboxSkillService struct {
|
|||
installTenant uint64
|
||||
installConfig string
|
||||
installBytes []byte
|
||||
removeTenant uint64
|
||||
removeConfig string
|
||||
removeSkill string
|
||||
patchEnabled bool
|
||||
closed bool
|
||||
|
||||
reinstallTenant uint64
|
||||
reinstallConfig string
|
||||
reinstallSkill string
|
||||
|
||||
removeTenant uint64
|
||||
removeConfig string
|
||||
removeSkill string
|
||||
patchEnabled bool
|
||||
closed bool
|
||||
// onGet runs on every read, so a test can model a row that disappears
|
||||
// while the client is streaming.
|
||||
onGet func(calls int)
|
||||
|
|
@ -170,6 +176,13 @@ func (f *fakeSandboxSkillService) InstallSkillFromSource(
|
|||
return f.installID, f.sourceErr
|
||||
}
|
||||
|
||||
func (f *fakeSandboxSkillService) ReinstallSkill(
|
||||
_ context.Context, tenantID uint64, configID, skillID string,
|
||||
) (string, error) {
|
||||
f.reinstallTenant, f.reinstallConfig, f.reinstallSkill = tenantID, configID, skillID
|
||||
return f.installID, f.reinstallErr
|
||||
}
|
||||
|
||||
func (f *fakeSandboxSkillService) RemoveSkill(
|
||||
_ context.Context, tenantID uint64, configID, skillID string,
|
||||
) error {
|
||||
|
|
@ -240,6 +253,7 @@ func newSkillTestRouter(h *SandboxSkillHandler) *gin.Engine {
|
|||
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.POST("/sandbox-configs/:id/skills/:skillId/reinstall", h.Reinstall)
|
||||
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)
|
||||
|
|
@ -538,6 +552,37 @@ func TestSandboxSkillDeleteIsAccepted(t *testing.T) {
|
|||
require.Equal(t, "skill-1", svc.removeSkill)
|
||||
}
|
||||
|
||||
// A retry boots a sandbox and runs for minutes, exactly like the upload it
|
||||
// stands in for, so it is accepted and followed rather than awaited.
|
||||
func TestSandboxSkillReinstallIsAccepted(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{installID: "skill-1"}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost,
|
||||
"/sandbox-configs/cfg-a/skills/skill-1/reinstall", nil))
|
||||
|
||||
require.Equal(t, http.StatusAccepted, w.Code)
|
||||
require.Equal(t, testSkillTenantID, svc.reinstallTenant,
|
||||
"a retry must be scoped to the caller's workspace")
|
||||
require.Equal(t, "cfg-a", svc.reinstallConfig)
|
||||
require.Equal(t, "skill-1", svc.reinstallSkill)
|
||||
require.Contains(t, w.Body.String(), `"skill_id":"skill-1"`)
|
||||
}
|
||||
|
||||
func TestSandboxSkillReinstallReportsAMissingSkill(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{
|
||||
reinstallErr: apperrors.NewNotFoundError("skill not found"),
|
||||
}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest(http.MethodPost,
|
||||
"/sandbox-configs/cfg-a/skills/nope/reinstall", nil))
|
||||
|
||||
require.Equal(t, http.StatusNotFound, w.Code)
|
||||
}
|
||||
|
||||
func decodeSSEEvents(t *testing.T, body string) []map[string]any {
|
||||
t.Helper()
|
||||
var events []map[string]any
|
||||
|
|
|
|||
|
|
@ -659,12 +659,13 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
|
|||
// produced — those cases must not disturb the completion path.
|
||||
if h.artifactCollector != nil {
|
||||
collectCtx := context.WithoutCancel(h.ctx)
|
||||
artifacts, err := h.artifactCollector.Collect(
|
||||
artifacts, err := h.artifactCollector.CollectWithNotify(
|
||||
collectCtx,
|
||||
h.sessionID,
|
||||
h.assistantMessageID,
|
||||
h.tenantID,
|
||||
skills.ArtifactOutputDir(),
|
||||
h.emitArtifactsPending,
|
||||
)
|
||||
if err != nil {
|
||||
logger.GetLogger(h.ctx).Warnf(
|
||||
|
|
@ -673,6 +674,13 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
|
|||
)
|
||||
} else if len(artifacts) > 0 {
|
||||
h.assistantMessage.Artifacts = artifacts
|
||||
// The answer text names generated files the way the model saw
|
||||
// them in the sandbox. Bind those names to artifact indices now
|
||||
// that the index space is final, so a reloaded conversation
|
||||
// renders them instead of showing a broken link.
|
||||
h.assistantMessage.Content = rewriteArtifactReferences(
|
||||
h.assistantMessage.Content, artifacts,
|
||||
)
|
||||
logger.GetLogger(h.ctx).Infof(
|
||||
"artifact collect attached %d file(s) to message=%s session=%s",
|
||||
len(artifacts), h.assistantMessageID, h.sessionID,
|
||||
|
|
@ -756,16 +764,39 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Event
|
|||
return nil
|
||||
}
|
||||
|
||||
// emitArtifactsPending tells the live UI that sandbox files exist and are
|
||||
// being uploaded. It must not take h.mu — Collect calls it while
|
||||
// handleComplete already holds the lock.
|
||||
func (h *AgentStreamHandler) emitArtifactsPending(count int) {
|
||||
if h == nil || h.streamManager == nil || count <= 0 {
|
||||
return
|
||||
}
|
||||
if err := h.streamManager.AppendEvent(h.ctx, h.sessionID, h.assistantMessageID, interfaces.StreamEvent{
|
||||
ID: fmt.Sprintf("artifacts-pending-%d", time.Now().UnixMilli()),
|
||||
Type: types.ResponseTypeArtifactsPending,
|
||||
Timestamp: time.Now(),
|
||||
Data: map[string]interface{}{
|
||||
"count": count,
|
||||
},
|
||||
}); err != nil {
|
||||
logger.GetLogger(h.ctx).Warnf(
|
||||
"append artifacts_pending failed session=%s message=%s: %v",
|
||||
h.sessionID, h.assistantMessageID, err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// publicArtifactViews returns a redacted view of the artifact list suitable
|
||||
// for direct serialization onto the SSE stream. The storage URL and any
|
||||
// other server-only fields are stripped; the frontend uses (index, name,
|
||||
// size, source_path, mod_time, created_at) to render the download drawer
|
||||
// and calls /artifacts/:index/download to fetch the bytes.
|
||||
// for direct serialization onto the SSE stream. The physical storage path is
|
||||
// stripped; the resource handle is kept because it is what the answer body
|
||||
// references, and the frontend needs it to tie an inline reference to the file
|
||||
// it names. Bytes are fetched through /artifacts/:index/download.
|
||||
func publicArtifactViews(list types.MessageArtifacts) []map[string]interface{} {
|
||||
out := make([]map[string]interface{}, 0, len(list))
|
||||
for i, a := range list {
|
||||
out = append(out, map[string]interface{}{
|
||||
"index": i,
|
||||
"handle": artifactHandle(a),
|
||||
"file_name": a.FileName,
|
||||
"file_type": a.FileType,
|
||||
"file_size": a.FileSize,
|
||||
|
|
|
|||
|
|
@ -69,14 +69,11 @@ func (h *Handler) ListSessionArtifacts(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
|
||||
// Strip the storage URL before serialising to the client; the URL is a
|
||||
// server-side implementation detail (provider:// path) that must never
|
||||
// escape the process. The client references artifacts by index in the
|
||||
// download URL instead.
|
||||
items := make([]artifactListItem, 0, len(artifacts))
|
||||
for i, a := range artifacts {
|
||||
items = append(items, artifactListItem{
|
||||
Index: i,
|
||||
Handle: artifactHandle(a),
|
||||
FileName: a.FileName,
|
||||
FileType: a.FileType,
|
||||
FileSize: a.FileSize,
|
||||
|
|
@ -128,6 +125,7 @@ func (h *Handler) ListMessageArtifacts(c *gin.Context) {
|
|||
for i, a := range msg.Artifacts {
|
||||
items = append(items, artifactListItem{
|
||||
Index: i,
|
||||
Handle: artifactHandle(a),
|
||||
FileName: a.FileName,
|
||||
FileType: a.FileType,
|
||||
FileSize: a.FileSize,
|
||||
|
|
@ -220,11 +218,16 @@ func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
|
|||
}
|
||||
|
||||
// artifactListItem is the JSON shape returned by ListSessionArtifacts /
|
||||
// ListMessageArtifacts. It intentionally omits the URL: clients reference
|
||||
// each artifact through its position in the parent message's Artifacts
|
||||
// array so the storage path never leaves the server.
|
||||
// ListMessageArtifacts. It carries the resource handle but never the storage
|
||||
// path: the handle is the artifact's public identity — it is what the answer
|
||||
// body references and what an authorizing proxy resolves — while the physical
|
||||
// bucket/key stays server side.
|
||||
type artifactListItem struct {
|
||||
Index int `json:"index"`
|
||||
Index int `json:"index"`
|
||||
// Handle is the artifact's `resource://<handle>` reference, matching the
|
||||
// destinations in the message body. Empty when the deployment runs without
|
||||
// a resource catalog, in which case the body references files by name.
|
||||
Handle string `json:"handle,omitempty"`
|
||||
FileName string `json:"file_name"`
|
||||
FileType string `json:"file_type"`
|
||||
FileSize int64 `json:"file_size"`
|
||||
|
|
@ -304,7 +307,11 @@ func (urlPathEscaper) escape(s string) string {
|
|||
return b.String()
|
||||
}
|
||||
|
||||
// ensureAssistantOwnsArtifact is a small helper reserved for future
|
||||
// authorisation refinements (per-message role checks). It is unused today
|
||||
// but kept close to the handlers so future changes stay obvious.
|
||||
var _ = types.MessageArtifact{}
|
||||
// artifactHandle returns the artifact's `resource://<handle>` reference, or ""
|
||||
// when the deployment stores artifacts without a resource catalog.
|
||||
func artifactHandle(artifact types.MessageArtifact) string {
|
||||
if handle, ok := types.ParseResourcePath(artifact.URL); ok {
|
||||
return types.BuildResourcePath(handle)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,270 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Models routinely reference the files they generated in the sandbox from
|
||||
// their final answer, most often as a Markdown image (``).
|
||||
// A bare file name resolves to nothing once the sandbox is gone, so this is the
|
||||
// boundary where an answer's transient, sandbox-local references are normalized
|
||||
// into the one reference form that survives: `resource://<handle>`.
|
||||
//
|
||||
// The handle is the same identity every other stored file uses (knowledge-base
|
||||
// images, chat attachments), which is what makes a saved answer keep working:
|
||||
// re-binding the handle to a knowledge entry is enough, with no copy and no
|
||||
// second rewrite. It is also opaque — the physical storage path stays server
|
||||
// side, and every read still goes through an authorizing proxy.
|
||||
//
|
||||
// A deployment without the resource catalog has no handle to point at, so those
|
||||
// references are normalized to the canonical `sandbox:<name>` spelling instead
|
||||
// and resolved by name against the message's own artifact list. That keeps the
|
||||
// answer readable in the chat, and only there.
|
||||
//
|
||||
// The rewrite runs once per turn, after ArtifactCollector has drained
|
||||
// /workspace/output, so every artifact already has its handle.
|
||||
|
||||
// fencedOrInlineCodeRE splits content so destinations inside code samples are
|
||||
// never rewritten — a documentation snippet showing the syntax must survive.
|
||||
var fencedOrInlineCodeRE = regexp.MustCompile("(?s)(```.*?```|~~~.*?~~~|`[^`\n]*`)")
|
||||
|
||||
// schemeRE matches an already-qualified URL (http://, resource://, data:, …).
|
||||
var schemeRE = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.\-]*:`)
|
||||
|
||||
// titleSuffixRE splits the optional title off a link destination
|
||||
// (`file.png "caption"`).
|
||||
var titleSuffixRE = regexp.MustCompile(`(?s)^(.*?)(\s+(?:"[^"]*"|'[^']*'))$`)
|
||||
|
||||
// rewriteArtifactReferences replaces every Markdown link/image destination that
|
||||
// names one of the turn's artifacts with that artifact's stable reference.
|
||||
//
|
||||
// Three destination spellings are accepted, because models are inconsistent
|
||||
// about the prefix even when the prompt asks for one:
|
||||
//
|
||||
// 
|
||||
// 
|
||||
// 
|
||||
//
|
||||
// Anything else — an http URL, a resource:// handle the model copied from
|
||||
// context, an unknown file name — is returned unchanged so existing behaviour
|
||||
// (knowledge-base images, web links) is untouched.
|
||||
func rewriteArtifactReferences(content string, artifacts types.MessageArtifacts) string {
|
||||
if content == "" || len(artifacts) == 0 {
|
||||
return content
|
||||
}
|
||||
byName := artifactRefByName(artifacts)
|
||||
if len(byName) == 0 {
|
||||
return content
|
||||
}
|
||||
|
||||
parts := fencedOrInlineCodeRE.Split(content, -1)
|
||||
if len(parts) == 1 {
|
||||
return rewriteArtifactReferencesInSegment(content, byName)
|
||||
}
|
||||
code := fencedOrInlineCodeRE.FindAllString(content, -1)
|
||||
var out strings.Builder
|
||||
out.Grow(len(content))
|
||||
for i, part := range parts {
|
||||
out.WriteString(rewriteArtifactReferencesInSegment(part, byName))
|
||||
if i < len(code) {
|
||||
out.WriteString(code[i])
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// rewriteArtifactReferencesInSegment walks every inline Markdown link/image in
|
||||
// one non-code segment and rebinds the ones that name an artifact.
|
||||
//
|
||||
// Destinations are located by matching parentheses rather than by regex,
|
||||
// because skill-generated file names routinely contain both spaces and
|
||||
// parentheses (`腾讯控股(00700) 成交量_838ccc.html`). A regex that stops at the
|
||||
// first space or paren would capture half the name and never match.
|
||||
func rewriteArtifactReferencesInSegment(segment string, byName map[string]string) string {
|
||||
if segment == "" || !strings.Contains(segment, "](") {
|
||||
return segment
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
out.Grow(len(segment))
|
||||
cursor := 0
|
||||
for cursor < len(segment) {
|
||||
relative := strings.Index(segment[cursor:], "](")
|
||||
if relative < 0 {
|
||||
break
|
||||
}
|
||||
closeBracket := cursor + relative
|
||||
open := closeBracket + 1
|
||||
|
||||
inner, end, ok := scanLinkDestination(segment, open)
|
||||
if !ok || !hasLinkLabelBefore(segment, closeBracket) {
|
||||
out.WriteString(segment[cursor : open+1])
|
||||
cursor = open + 1
|
||||
continue
|
||||
}
|
||||
|
||||
destination, title := splitDestinationTitle(inner)
|
||||
ref, matched := lookupArtifactRef(destination, byName, markdownImageBefore(segment, closeBracket))
|
||||
if !matched {
|
||||
out.WriteString(segment[cursor : end+1])
|
||||
cursor = end + 1
|
||||
continue
|
||||
}
|
||||
|
||||
out.WriteString(segment[cursor : open+1])
|
||||
out.WriteString(ref)
|
||||
out.WriteString(title)
|
||||
out.WriteString(")")
|
||||
cursor = end + 1
|
||||
}
|
||||
out.WriteString(segment[cursor:])
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// scanLinkDestination returns the text between the `(` at openIndex and its
|
||||
// matching `)`, plus the index of that closing paren. A destination never spans
|
||||
// a line break, so a newline ends the scan unsuccessfully.
|
||||
func scanLinkDestination(text string, openIndex int) (string, int, bool) {
|
||||
depth := 1
|
||||
for i := openIndex + 1; i < len(text); i++ {
|
||||
switch text[i] {
|
||||
case '\n':
|
||||
return "", 0, false
|
||||
case '(':
|
||||
depth++
|
||||
case ')':
|
||||
depth--
|
||||
if depth == 0 {
|
||||
return text[openIndex+1 : i], i, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", 0, false
|
||||
}
|
||||
|
||||
// hasLinkLabelBefore reports whether `](` is preceded by a `[` on the same
|
||||
// line, i.e. whether this really is a link rather than incidental punctuation.
|
||||
func hasLinkLabelBefore(text string, closeBracketIndex int) bool {
|
||||
for i := closeBracketIndex - 1; i >= 0; i-- {
|
||||
switch text[i] {
|
||||
case '\n':
|
||||
return false
|
||||
case '[':
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// splitDestinationTitle separates `dest "title"` into its two parts, returning
|
||||
// the title with its leading whitespace so it can be re-emitted verbatim.
|
||||
func splitDestinationTitle(inner string) (string, string) {
|
||||
if groups := titleSuffixRE.FindStringSubmatch(inner); groups != nil {
|
||||
return strings.TrimSpace(groups[1]), groups[2]
|
||||
}
|
||||
return strings.TrimSpace(inner), ""
|
||||
}
|
||||
|
||||
func markdownImageBefore(text string, closeBracketIndex int) bool {
|
||||
for i := closeBracketIndex - 1; i >= 0; i-- {
|
||||
switch text[i] {
|
||||
case '\n':
|
||||
return false
|
||||
case '[':
|
||||
return i > 0 && text[i-1] == '!'
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func looksLikeSandboxOutputPath(candidate string) bool {
|
||||
c := strings.TrimPrefix(strings.TrimSpace(candidate), "./")
|
||||
c = strings.TrimPrefix(c, "/")
|
||||
return strings.HasPrefix(c, "workspace/output/") || strings.HasPrefix(c, "output/")
|
||||
}
|
||||
|
||||
// lookupArtifactRef resolves one Markdown destination to an artifact reference.
|
||||
func lookupArtifactRef(destination string, byName map[string]string, image bool) (string, bool) {
|
||||
candidate := strings.TrimSpace(destination)
|
||||
if candidate == "" {
|
||||
return "", false
|
||||
}
|
||||
// Trim the optional angle-bracket form Markdown allows around a
|
||||
// destination: `[x](<name with space>)` — kept for completeness even
|
||||
// though the outer regex rejects inner whitespace.
|
||||
candidate = strings.TrimPrefix(strings.TrimSuffix(candidate, ">"), "<")
|
||||
|
||||
hadSandboxPrefix := false
|
||||
for _, prefix := range []string{"sandbox://", "sandbox:"} {
|
||||
if len(candidate) >= len(prefix) && strings.EqualFold(candidate[:len(prefix)], prefix) {
|
||||
candidate = candidate[len(prefix):]
|
||||
hadSandboxPrefix = true
|
||||
break
|
||||
}
|
||||
}
|
||||
// A destination that already carries a scheme is a real URL, not a file
|
||||
// name. `sandbox:` is the one exception and was stripped above.
|
||||
if !hadSandboxPrefix && schemeRE.MatchString(candidate) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Models percent-encode non-ASCII names about half the time.
|
||||
if decoded, err := url.PathUnescape(candidate); err == nil {
|
||||
candidate = decoded
|
||||
}
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
// Bare names are rewritten for images (``) because that is
|
||||
// how models actually cite generated files. Ordinary links (`[docs](README.md)`)
|
||||
// are left alone unless they already carry a sandbox prefix or path —
|
||||
// otherwise a colliding artifact name would hijack a real hyperlink.
|
||||
if !hadSandboxPrefix && !image && !looksLikeSandboxOutputPath(candidate) {
|
||||
return "", false
|
||||
}
|
||||
// Directory prefixes (`./`, `output/`, `/workspace/output/`) carry no
|
||||
// information the artifact list does not already have.
|
||||
candidate = path.Base(candidate)
|
||||
if candidate == "" || candidate == "." || candidate == "/" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
ref, ok := byName[candidate]
|
||||
return ref, ok
|
||||
}
|
||||
|
||||
// artifactRefByName maps each artifact's file name to the reference that
|
||||
// replaces it in the answer. A duplicate name keeps the first occurrence:
|
||||
// silently preferring the later file would make the reference point at
|
||||
// something the model did not describe.
|
||||
func artifactRefByName(artifacts types.MessageArtifacts) map[string]string {
|
||||
byName := make(map[string]string, len(artifacts))
|
||||
for _, artifact := range artifacts {
|
||||
name := strings.TrimSpace(artifact.FileName)
|
||||
if name == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := byName[name]; exists {
|
||||
continue
|
||||
}
|
||||
byName[name] = artifactReference(artifact)
|
||||
}
|
||||
return byName
|
||||
}
|
||||
|
||||
// artifactReference returns the destination an answer should carry for one
|
||||
// artifact: its catalog handle when the deployment has a resource registry,
|
||||
// otherwise the canonical chat-only `sandbox:<name>` form.
|
||||
//
|
||||
// The raw storage path is never a candidate. It names a bucket and key, which
|
||||
// is both an information leak and useless to a client that has no credentials
|
||||
// for the object store.
|
||||
func artifactReference(artifact types.MessageArtifact) string {
|
||||
if handle, ok := types.ParseResourcePath(artifact.URL); ok {
|
||||
return types.BuildResourcePath(handle)
|
||||
}
|
||||
return "sandbox:" + strings.TrimSpace(artifact.FileName)
|
||||
}
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// handleFor builds a syntactically valid 22-character resource handle for
|
||||
// artifact i, so tests exercise the same ParseResourcePath path as production.
|
||||
func handleFor(i int) string {
|
||||
base := fmt.Sprintf("art%d", i)
|
||||
return base + strings.Repeat("x", types.ResourceHandleLength-len(base))
|
||||
}
|
||||
|
||||
func refFor(i int) string {
|
||||
return types.BuildResourcePath(handleFor(i))
|
||||
}
|
||||
|
||||
// artifactsFixture builds artifacts whose storage URL is a catalog handle —
|
||||
// the normal deployment. Use artifactsWithoutCatalog for the degraded case.
|
||||
func artifactsFixture(names ...string) types.MessageArtifacts {
|
||||
list := make(types.MessageArtifacts, 0, len(names))
|
||||
for i, name := range names {
|
||||
list = append(list, types.MessageArtifact{FileName: name, URL: refFor(i)})
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func artifactsWithoutCatalog(names ...string) types.MessageArtifacts {
|
||||
list := make(types.MessageArtifacts, 0, len(names))
|
||||
for _, name := range names {
|
||||
list = append(list, types.MessageArtifact{FileName: name, URL: "local://7/exports/" + name})
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
func TestRewriteArtifactReferences(t *testing.T) {
|
||||
artifacts := artifactsFixture(
|
||||
"市场画像评分_e7edba.html",
|
||||
"concept_ranking.csv",
|
||||
"trend.png",
|
||||
"腾讯控股(00700) 成交量_838ccc.html",
|
||||
)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "file name with spaces and parentheses",
|
||||
content: " 成交量_838ccc.html)",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "file name with spaces and parentheses, no prefix",
|
||||
content: " 成交量_838ccc.html)",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "bare file name in image",
|
||||
content: "",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "sandbox prefix",
|
||||
content: "",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "sandbox scheme with slashes",
|
||||
content: "",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "directory prefix is dropped",
|
||||
content: "[榜单](/workspace/output/concept_ranking.csv)",
|
||||
want: "[榜单](" + refFor(1) + ")",
|
||||
},
|
||||
{
|
||||
name: "percent-encoded name",
|
||||
content: "",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "title is preserved",
|
||||
content: ``,
|
||||
want: ` + ` "走势")`,
|
||||
},
|
||||
{
|
||||
name: "ordinary link with a colliding name is not rewritten",
|
||||
content: "见 [说明](trend.png)",
|
||||
want: "见 [说明](trend.png)",
|
||||
},
|
||||
{
|
||||
name: "sandbox-prefixed link is rewritten even when not an image",
|
||||
content: "数据见 [表格](sandbox:concept_ranking.csv)",
|
||||
want: "数据见 [表格](" + refFor(1) + ")",
|
||||
},
|
||||
{
|
||||
name: "already-rewritten reference is left alone",
|
||||
content: " + ")",
|
||||
want: " + ")",
|
||||
},
|
||||
{
|
||||
name: "prose parentheses are not link destinations",
|
||||
content: "腾讯控股(00700) 的成交量见下图。",
|
||||
want: "腾讯控股(00700) 的成交量见下图。",
|
||||
},
|
||||
{
|
||||
name: "unknown file name untouched",
|
||||
content: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "http url untouched",
|
||||
content: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "knowledge base image untouched",
|
||||
content: "",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "fenced code untouched",
|
||||
content: "```\n\n```",
|
||||
want: "```\n\n```",
|
||||
},
|
||||
{
|
||||
name: "inline code untouched",
|
||||
content: "写成 `` 即可",
|
||||
want: "写成 `` 即可",
|
||||
},
|
||||
{
|
||||
name: "plain prose untouched",
|
||||
content: "生成了 trend.png 和 concept_ranking.csv 两个文件。",
|
||||
want: "生成了 trend.png 和 concept_ranking.csv 两个文件。",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := rewriteArtifactReferences(tc.content, artifacts); got != tc.want {
|
||||
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteArtifactReferencesMixedContent(t *testing.T) {
|
||||
artifacts := artifactsFixture("chart.html", "data.csv")
|
||||
content := "## 图表\n\n\n\n数据见 [表格](sandbox:data.csv)," +
|
||||
"外链 [文档](https://example.com/chart.html) 不受影响。"
|
||||
want := "## 图表\n\n + ")\n\n数据见 [表格](" + refFor(1) + ")," +
|
||||
"外链 [文档](https://example.com/chart.html) 不受影响。"
|
||||
|
||||
if got := rewriteArtifactReferences(content, artifacts); got != want {
|
||||
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A knowledge-base image and a skill artifact routinely appear in the same
|
||||
// answer. Only the artifact is rebound; the existing reference must survive
|
||||
// byte for byte, since it already is the canonical form.
|
||||
func TestRewriteArtifactReferencesKeepsExistingResourceImages(t *testing.T) {
|
||||
artifacts := artifactsFixture("chart.html")
|
||||
kbImage := types.BuildResourcePath(strings.Repeat("Z", types.ResourceHandleLength))
|
||||
content := "\n\n"
|
||||
want := "\n\n + ")"
|
||||
|
||||
if got := rewriteArtifactReferences(content, artifacts); got != want {
|
||||
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Without a resource catalog there is no durable handle, so references are
|
||||
// normalized to the chat-only sandbox form rather than leaking a storage path.
|
||||
func TestRewriteArtifactReferencesWithoutCatalog(t *testing.T) {
|
||||
artifacts := artifactsWithoutCatalog("chart.html")
|
||||
got := rewriteArtifactReferences("", artifacts)
|
||||
if want := ""; got != want {
|
||||
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
|
||||
}
|
||||
if strings.Contains(got, "local://") {
|
||||
t.Fatalf("storage path leaked into content: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRewriteArtifactReferencesNoArtifacts(t *testing.T) {
|
||||
content := ""
|
||||
if got := rewriteArtifactReferences(content, nil); got != content {
|
||||
t.Fatalf("rewriteArtifactReferences() = %q, want unchanged", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactRefByNameKeepsFirstDuplicate(t *testing.T) {
|
||||
byName := artifactRefByName(artifactsFixture("a.html", "a.html", "b.html"))
|
||||
if byName["a.html"] != refFor(0) {
|
||||
t.Fatalf("duplicate name resolved to %q, want %q", byName["a.html"], refFor(0))
|
||||
}
|
||||
if byName["b.html"] != refFor(2) {
|
||||
t.Fatalf("b.html resolved to %q, want %q", byName["b.html"], refFor(2))
|
||||
}
|
||||
}
|
||||
|
|
@ -82,6 +82,10 @@ func (s *stubResourceCatalog) Bind(context.Context, string, string, string, stri
|
|||
panic("unexpected Bind")
|
||||
}
|
||||
|
||||
func (s *stubResourceCatalog) Release(context.Context, string, string, string) (int64, error) {
|
||||
panic("unexpected Release")
|
||||
}
|
||||
|
||||
func (s *stubResourceCatalog) MarkDeleted(context.Context, string) error {
|
||||
panic("unexpected MarkDeleted")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ func RegisterSandboxConfigRoutes(
|
|||
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.POST("/:id/skills/:skillId/reinstall", g.Admin(), skills.Reinstall)
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -45,7 +45,12 @@ const (
|
|||
DefaultTimeout = 60 * time.Second
|
||||
DefaultMemoryLimit = 256 * 1024 * 1024 // 256MB
|
||||
DefaultCPULimit = 1.0 // 1 CPU core
|
||||
DefaultDockerImage = "wechatopenai/weknora-sandbox:latest"
|
||||
// DefaultDockerImage tracks main rather than latest. The latest tag only
|
||||
// moves when a version is released, so it still carries the image from
|
||||
// before /workspace and its input/output directories were handed to the
|
||||
// sandbox account — a sandbox built from it cannot write its own artifact
|
||||
// directory. Point this back at latest once a release ships that fix.
|
||||
DefaultDockerImage = "wechatopenai/weknora-sandbox:main"
|
||||
|
||||
// DefaultCubeTemplateImage is the same environment with Cube's envd daemon
|
||||
// baked in (target "cube" of docker/Dockerfile.sandbox).
|
||||
|
|
|
|||
|
|
@ -28,7 +28,6 @@ import (
|
|||
"fmt"
|
||||
"log"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
|
@ -49,6 +48,12 @@ const SessionOutputRoot = "/workspace/output"
|
|||
// skillOutputEnvVar matches the skills manager's WEKNORA_SKILL_OUTPUT_DIR.
|
||||
const skillOutputEnvVar = "WEKNORA_SKILL_OUTPUT_DIR"
|
||||
|
||||
// sessionInputEnvVar matches the skills manager's WEKNORA_SESSION_INPUT_DIR.
|
||||
// Both names are injected into the sandbox environment itself, not only into
|
||||
// the skill-script Execute call, so an agent exploring with shell_exec reads
|
||||
// the same paths the skills framework uses.
|
||||
const sessionInputEnvVar = "WEKNORA_SESSION_INPUT_DIR"
|
||||
|
||||
// SessionWorkspaceRoot is the writable workspace root inside remote sandboxes.
|
||||
// shell_exec work_dir must stay underneath this path.
|
||||
const SessionWorkspaceRoot = "/workspace"
|
||||
|
|
@ -264,65 +269,107 @@ func (m *SessionBoundManager) Execute(ctx context.Context, cfg *ExecuteConfig) (
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.ensureExecutionOutputDir(ctx, handle, cfg)
|
||||
m.ensureSessionWorkspaceDirs(ctx, handle, executionOutputDir(cfg))
|
||||
return m.ephemeral.ExecuteOnHandle(ctx, handle, cfg)
|
||||
}
|
||||
|
||||
// ensureExecutionOutputDir creates the skill artifact directory and makes sure
|
||||
// DefaultSandboxExecUser can write to it before script execution.
|
||||
// ensureSessionWorkspaceDirs materialises the input and artifact directories
|
||||
// and makes sure DefaultSandboxExecUser can write to them. It runs before
|
||||
// every operation rather than only before script execution: a snapshot-derived
|
||||
// image has no /workspace tree at all (skill install wipes it before the
|
||||
// snapshot), an agent that explores with shell_exec first would otherwise find
|
||||
// neither directory, and a later `rm -rf` of those paths must be repaired
|
||||
// rather than left missing until the process restarts.
|
||||
//
|
||||
// This runs AS that account, never as root. The directory sits inside the
|
||||
// session's own writable workspace, and chown/chmod follow symlinks, so a
|
||||
// This runs AS the sandbox account, never as root. The directories sit inside
|
||||
// the session's own writable workspace, and chown/chmod follow symlinks, so a
|
||||
// root-run bootstrap can be aimed at any directory in the container: a session
|
||||
// that swaps its artifact directory for a link to /etc gets handed ownership of
|
||||
// /etc, and from there uid 0 by rewriting passwd. Running as the sandbox
|
||||
// account makes that a no-op — chown succeeds on the directory MakeDir just
|
||||
// created for it and is refused by the kernel on anything else.
|
||||
// account makes that a no-op — the kernel refuses everything the account does
|
||||
// not already own.
|
||||
//
|
||||
// Best-effort: failures are logged and do not abort the upcoming execution.
|
||||
func (m *SessionBoundManager) ensureExecutionOutputDir(
|
||||
// The command is a no-op when the directories already exist and are writable,
|
||||
// so repeating it is cheap relative to recreating a missing tree. Best-effort:
|
||||
// failures are logged and do not abort the upcoming operation.
|
||||
func (m *SessionBoundManager) ensureSessionWorkspaceDirs(
|
||||
ctx context.Context,
|
||||
handle RemoteSandboxHandle,
|
||||
cfg *ExecuteConfig,
|
||||
outputDir string,
|
||||
) {
|
||||
if m == nil || m.client == nil || handle == nil {
|
||||
return
|
||||
}
|
||||
outputDir := executionOutputDir(cfg)
|
||||
if outputDir == "" {
|
||||
if m == nil || m.client == nil || handle == nil || outputDir == "" {
|
||||
return
|
||||
}
|
||||
execUser := DefaultSandboxExecUser
|
||||
if err := m.client.MakeDir(ctx, handle, outputDir); err != nil {
|
||||
log.Printf("[sandbox] ensure output dir %s failed: %v", outputDir, err)
|
||||
return
|
||||
}
|
||||
quoted := strconv.Quote(outputDir)
|
||||
line := fmt.Sprintf(
|
||||
"chown %s:%s %s && chmod 775 %s",
|
||||
execUser, execUser, quoted, quoted,
|
||||
)
|
||||
result, err := m.client.Exec(ctx, handle, RemoteExecRequest{
|
||||
Shell: true,
|
||||
Command: line,
|
||||
Command: workspaceBootstrapCommand(SessionInputRoot, outputDir),
|
||||
User: execUser,
|
||||
Timeout: sessionArtifactDirBootstrapTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
switch {
|
||||
case err != nil:
|
||||
log.Printf(
|
||||
"[sandbox] grant output dir %s to %s failed: %v",
|
||||
outputDir, execUser, err,
|
||||
"[sandbox] prepare workspace dirs (%s, %s) for %s failed: %v",
|
||||
SessionInputRoot, outputDir, execUser, err,
|
||||
)
|
||||
return
|
||||
}
|
||||
if result != nil && result.ExitCode != 0 {
|
||||
case result != nil && result.ExitCode != 0:
|
||||
// The account cannot create or take over these directories, which
|
||||
// means /workspace itself does not belong to it. No runtime step can
|
||||
// repair that; the image or template has to be rebuilt from a base
|
||||
// where /workspace is owned by the sandbox account.
|
||||
log.Printf(
|
||||
"[sandbox] grant output dir %s to %s: exit=%d stderr=%s",
|
||||
outputDir, execUser, result.ExitCode, strings.TrimSpace(result.Stderr),
|
||||
"[sandbox] prepare workspace dirs (%s, %s) for %s: exit=%d stderr=%s "+
|
||||
"— rebuild the sandbox image/template so /workspace is owned by %s",
|
||||
SessionInputRoot, outputDir, execUser,
|
||||
result.ExitCode, strings.TrimSpace(result.Stderr), execUser,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// workspaceBootstrapCommand builds the repair script the sandbox account runs.
|
||||
//
|
||||
// Each directory is handled in three steps because all three states occur in
|
||||
// the field: missing (snapshot images carry no /workspace tree), present but
|
||||
// not a directory (a symlink an earlier turn left behind), and present but
|
||||
// owned by another account (a provider whose filesystem API creates
|
||||
// directories as root). The last one is repaired by moving the directory aside
|
||||
// instead of chowning it: deletion rights come from the parent, so the account
|
||||
// that owns /workspace can always replace a child it does not own, and nothing
|
||||
// here needs privileges.
|
||||
func workspaceBootstrapCommand(dirs ...string) string {
|
||||
quoted := make([]string, 0, len(dirs))
|
||||
for _, dir := range dirs {
|
||||
quoted = append(quoted, ShellQuote(dir))
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
`set -e; for d in %s; do `+
|
||||
`if [ -d "$d" ] && [ -w "$d" ] && [ ! -L "$d" ]; then continue; fi; `+
|
||||
`if [ -L "$d" ] || { [ -e "$d" ] && [ ! -d "$d" ]; }; then rm -f "$d"; fi; `+
|
||||
`[ -d "$d" ] || mkdir -p "$d"; `+
|
||||
`if [ ! -w "$d" ]; then mv -f "$d" "$d.unwritable.$(date +%%s)"; mkdir "$d"; fi; `+
|
||||
`chmod 775 "$d"; done`,
|
||||
strings.Join(quoted, " "),
|
||||
)
|
||||
}
|
||||
|
||||
// withWorkspaceEnvDefaults stamps the workspace paths onto the sandbox's own
|
||||
// environment. A tenant-configured value wins: an operator who points the
|
||||
// artifact directory somewhere else must not have it overwritten here.
|
||||
func withWorkspaceEnvDefaults(env map[string]string) map[string]string {
|
||||
if env == nil {
|
||||
env = make(map[string]string, 2)
|
||||
}
|
||||
if strings.TrimSpace(env[skillOutputEnvVar]) == "" {
|
||||
env[skillOutputEnvVar] = SessionOutputRoot
|
||||
}
|
||||
if strings.TrimSpace(env[sessionInputEnvVar]) == "" {
|
||||
env[sessionInputEnvVar] = SessionInputRoot
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// executionOutputDir resolves the artifact directory for this Execute call.
|
||||
// It prefers WEKNORA_SKILL_OUTPUT_DIR from cfg.Env when the path stays under
|
||||
// SessionWorkspaceRoot; otherwise it falls back to SessionOutputRoot.
|
||||
|
|
@ -654,6 +701,11 @@ func (m *SessionBoundManager) ExecShellCommandWithOptions(
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The model reaches the sandbox through this path too, and typically
|
||||
// before any skill script runs. Without the same bootstrap it would find
|
||||
// no artifact directory and no place to read attachments from, and would
|
||||
// improvise somewhere the collector never looks.
|
||||
m.ensureSessionWorkspaceDirs(ctx, handle, SessionOutputRoot)
|
||||
if workDir != "" {
|
||||
if mkErr := m.client.MakeDir(ctx, handle, workDir); mkErr != nil {
|
||||
log.Printf("[sandbox] shell_exec: MakeDir %s failed (continuing): %v", workDir, mkErr)
|
||||
|
|
@ -962,7 +1014,7 @@ func cleanSessionWorkDir(workDir string, allowSkillsRoot bool) (string, error) {
|
|||
// authoritative source of identity — it selects the correct Config fields so
|
||||
// Cube and E2B never read each other's templates or TTLs.
|
||||
func buildSessionCreateRequest(provider RemoteProvider, cfg *Config) (RemoteCreateRequest, error) {
|
||||
envVars := cloneMetadata(cfg.EnvVars)
|
||||
envVars := withWorkspaceEnvDefaults(cloneMetadata(cfg.EnvVars))
|
||||
|
||||
switch provider {
|
||||
case SandboxTypeCube:
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package sandbox
|
|||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -81,20 +82,76 @@ func TestSessionBoundManagerExecuteEnsuresOutputDir(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
|
||||
client.mu.Lock()
|
||||
paths := append([]string(nil), client.makeDirPaths...)
|
||||
execs := append([]RemoteExecRequest(nil), client.execRequests...)
|
||||
client.mu.Unlock()
|
||||
require.Contains(t, paths, SessionOutputRoot)
|
||||
require.NotEmpty(t, execs)
|
||||
require.True(t, execs[0].Shell)
|
||||
require.Contains(t, execs[0].Command, "chown user:user")
|
||||
require.Contains(t, execs[0].Command, SessionOutputRoot)
|
||||
require.Contains(t, execs[0].Command, SessionInputRoot,
|
||||
"the attachment directory is prepared alongside the artifact one; a "+
|
||||
"snapshot-derived image carries neither")
|
||||
require.Equal(t, DefaultSandboxExecUser, execs[0].User,
|
||||
"chown follows symlinks, so a root-run bootstrap can be aimed at /etc by "+
|
||||
"a session that swaps its artifact directory for a link; running as the "+
|
||||
"sandbox account is what makes that attempt fail")
|
||||
}
|
||||
|
||||
// A directory the sandbox account cannot write is the state an image built
|
||||
// before /workspace was handed to that account leaves behind, and the state a
|
||||
// provider whose filesystem API runs as root recreates. The bootstrap has to
|
||||
// repair it without privileges, which is why it replaces the directory rather
|
||||
// than chowning it.
|
||||
func TestWorkspaceBootstrapCommandRepairsUnwritableDirs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cmd := workspaceBootstrapCommand(SessionInputRoot, SessionOutputRoot)
|
||||
require.Contains(t, cmd, "for d in /workspace/input /workspace/output")
|
||||
require.Contains(t, cmd, `mkdir -p "$d"`)
|
||||
require.Contains(t, cmd, `[ -d "$d" ] && [ -w "$d" ] && [ ! -L "$d" ]`,
|
||||
"directories that already belong to the account are left alone")
|
||||
require.Contains(t, cmd, `[ -L "$d" ]`,
|
||||
"a symlink left at the path must be removed, not followed")
|
||||
require.Contains(t, cmd, `mv -f "$d"`,
|
||||
"an unwritable directory is moved aside; the account owns the parent, "+
|
||||
"so this needs no privileges")
|
||||
require.NotContains(t, cmd, "chown",
|
||||
"nothing here may depend on privileges the sandbox account lacks")
|
||||
}
|
||||
|
||||
// The agent can delete /workspace/output between turns. Preparing only once
|
||||
// per process would leave later writes failing until WeKnora restarted.
|
||||
func TestSessionBoundManagerPreparesWorkspaceOnEveryCall(t *testing.T) {
|
||||
client := newFakeRemoteClient(SandboxTypeCube)
|
||||
cfg := DefaultConfig()
|
||||
cfg.CubeTemplate = "tpl-test"
|
||||
mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{
|
||||
Config: cfg,
|
||||
Client: client,
|
||||
Store: NewMemorySessionSandboxBindingStore(),
|
||||
Checker: &fakeSessionExistenceChecker{exists: true},
|
||||
SkipHealthProbe: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
|
||||
for i := 0; i < 3; i++ {
|
||||
_, err := mgr.ExecShellCommand(ctx, "session-a", "echo hi", "", time.Second, nil)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
client.mu.Lock()
|
||||
execs := append([]RemoteExecRequest(nil), client.execRequests...)
|
||||
client.mu.Unlock()
|
||||
|
||||
bootstraps := 0
|
||||
for _, exec := range execs {
|
||||
if strings.Contains(exec.Command, SessionInputRoot) {
|
||||
bootstraps++
|
||||
}
|
||||
}
|
||||
require.Equal(t, 3, bootstraps)
|
||||
}
|
||||
|
||||
// shell_exec carries a command line the model wrote, which makes it the exec
|
||||
// path an injected prompt reaches most directly. The account it runs as is
|
||||
// pinned here rather than left to each adapter, so that reading this call site
|
||||
|
|
|
|||
|
|
@ -68,6 +68,14 @@ func SkillDirForImageScript(scriptPath string) (string, bool) {
|
|||
return path.Join(cleanRoot, parts[0]), true
|
||||
}
|
||||
|
||||
// SkillVenvPython is where a skill's own Python interpreter lives when the
|
||||
// install created one. It is exported because the model needs to be told: the
|
||||
// system python3 deliberately carries no skill dependencies, so anything that
|
||||
// inspects or debugs a Python skill has to name this path.
|
||||
func SkillVenvPython(skillDir string) string {
|
||||
return path.Join(skillDir, ".venv", "bin", "python")
|
||||
}
|
||||
|
||||
// SkillInterpreterCommand picks how to run one script of a skill.
|
||||
//
|
||||
// The interpreter is derived per script rather than stored per skill: one skill
|
||||
|
|
@ -80,7 +88,7 @@ func SkillDirForImageScript(scriptPath string) (string, bool) {
|
|||
func SkillInterpreterCommand(skillDir, scriptPath string) (string, []string) {
|
||||
switch strings.ToLower(path.Ext(scriptPath)) {
|
||||
case ".py":
|
||||
venvPython := path.Join(skillDir, ".venv", "bin", "python")
|
||||
venvPython := SkillVenvPython(skillDir)
|
||||
script := ShellQuote(scriptPath)
|
||||
return "/bin/sh", []string{"-c", fmt.Sprintf(
|
||||
`if [ -x %s ]; then exec %s %s "$@"; else exec python3 %s "$@"; fi`,
|
||||
|
|
|
|||
|
|
@ -221,6 +221,11 @@ const (
|
|||
ResponseTypeAgentQuery ResponseType = "agent_query"
|
||||
// Complete response type (agent complete)
|
||||
ResponseTypeComplete ResponseType = "complete"
|
||||
// ResponseTypeArtifactsPending is sent while skill/sandbox output is being
|
||||
// copied into persistent storage after the answer has already streamed.
|
||||
// The UI shows a toolbar placeholder until ResponseTypeComplete carries
|
||||
// the file list.
|
||||
ResponseTypeArtifactsPending ResponseType = "artifacts_pending"
|
||||
// ToolApprovalRequired: MCP tool marked dangerous — UI must collect user approval before execution continues
|
||||
ResponseTypeToolApprovalRequired ResponseType = "tool_approval_required"
|
||||
// ToolApprovalResolved: user approved/rejected (or timeout); informational for UI replay
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ type ResourceRepository interface {
|
|||
GetByTenantLocation(ctx context.Context, tenantID uint64, locationHash string) (*types.StoredResource, error)
|
||||
MarkDeleted(ctx context.Context, id string) error
|
||||
CreateBinding(ctx context.Context, binding *types.ResourceBinding) error
|
||||
DeleteBinding(ctx context.Context, resourceID, ownerType, ownerID string) error
|
||||
CountBindings(ctx context.Context, resourceID string) (int64, error)
|
||||
CreateGrant(ctx context.Context, grant *types.ResourceAccessGrant) error
|
||||
GetValidGrant(ctx context.Context, tokenHash string, now time.Time) (*types.ResourceAccessGrant, error)
|
||||
DeleteExpiredGrants(ctx context.Context, before time.Time) error
|
||||
|
|
@ -46,6 +48,16 @@ type ResourceCatalog interface {
|
|||
Resolve(ctx context.Context, reference string) (*types.StoredResource, error)
|
||||
ResolvePath(ctx context.Context, value string) (string, *types.StoredResource, error)
|
||||
Bind(ctx context.Context, reference, ownerType, ownerID, relation string) error
|
||||
// Release drops one owner's claim on a resource and reports how many
|
||||
// claims remain. Callers use the count to decide whether the bytes may be
|
||||
// deleted: a resource still referenced by another owner — the assistant
|
||||
// message an answer was saved from, a second knowledge entry — must
|
||||
// survive the owner being removed.
|
||||
//
|
||||
// remaining is -1 when the answer is unknown (the reference is not a
|
||||
// catalog handle, or the count could not be read), which callers should
|
||||
// treat as "delete as before" rather than as "keep forever".
|
||||
Release(ctx context.Context, reference, ownerType, ownerID string) (remaining int64, err error)
|
||||
MarkDeleted(ctx context.Context, reference string) error
|
||||
CreateAccessGrant(ctx context.Context, reference string, ttl time.Duration) (string, error)
|
||||
ResolveAccessGrant(ctx context.Context, token string) (*types.StoredResource, error)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -18,6 +20,24 @@ const (
|
|||
ResourceLifecycleTemporary = "temporary"
|
||||
)
|
||||
|
||||
// Resource binding owner types. A binding is a claim on a stored object: the
|
||||
// bytes live as long as at least one owner still claims them, which is what
|
||||
// lets a chat answer be saved into the knowledge base without copying its
|
||||
// files, and lets either copy be deleted without breaking the other.
|
||||
const (
|
||||
ResourceOwnerKnowledge = "knowledge"
|
||||
ResourceOwnerMessage = "message"
|
||||
ResourceOwnerTemporaryDocument = "temporary_document"
|
||||
)
|
||||
|
||||
// Resource binding relations describe why an owner claims a resource.
|
||||
const (
|
||||
ResourceRelationSourceFile = "source_file"
|
||||
ResourceRelationExtractedImage = "extracted_image"
|
||||
ResourceRelationArtifact = "artifact"
|
||||
ResourceRelationAttachment = "attachment"
|
||||
)
|
||||
|
||||
// StoredResource is the stable application identity of one stored object. PhysicalPath
|
||||
// is deliberately internal: API responses, persisted rich text and LLM prompts
|
||||
// use resource://<handle> instead.
|
||||
|
|
@ -121,11 +141,49 @@ func ParseResourcePath(value string) (string, bool) {
|
|||
if len(handle) != ResourceHandleLength {
|
||||
return "", false
|
||||
}
|
||||
for _, char := range handle {
|
||||
if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') &&
|
||||
(char < '0' || char > '9') && char != '_' && char != '-' {
|
||||
for i := 0; i < len(handle); i++ {
|
||||
if !isResourceHandleChar(handle[i]) {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return handle, true
|
||||
}
|
||||
|
||||
func isResourceHandleChar(char byte) bool {
|
||||
return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') ||
|
||||
(char >= '0' && char <= '9') || char == '_' || char == '-'
|
||||
}
|
||||
|
||||
var resourceReferenceRE = regexp.MustCompile(
|
||||
ResourceScheme + `[A-Za-z0-9_-]{` + strconv.Itoa(ResourceHandleLength) + `}`,
|
||||
)
|
||||
|
||||
// ScanResourceReferences returns every distinct resource:// reference embedded
|
||||
// in text, in order of first appearance.
|
||||
//
|
||||
// Rich text (a chat answer, a manual knowledge document) is the only place a
|
||||
// reference's owner can be discovered after the fact: the body is what gets
|
||||
// copied between a message and a knowledge entry, so re-binding on copy starts
|
||||
// by reading the handles back out of it.
|
||||
func ScanResourceReferences(text string) []string {
|
||||
if !strings.Contains(text, ResourceScheme) {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
var refs []string
|
||||
for _, span := range resourceReferenceRE.FindAllStringIndex(text, -1) {
|
||||
// A longer run of handle characters is not a 22-char handle with
|
||||
// trailing text — it is a different (invalid) token, and binding the
|
||||
// truncated prefix would attach the wrong file.
|
||||
if span[1] < len(text) && isResourceHandleChar(text[span[1]]) {
|
||||
continue
|
||||
}
|
||||
ref := text[span[0]:span[1]]
|
||||
if _, exists := seen[ref]; exists {
|
||||
continue
|
||||
}
|
||||
seen[ref] = struct{}{}
|
||||
refs = append(refs, ref)
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,71 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseResourcePathRejectsMalformedHandles(t *testing.T) {
|
||||
valid := strings.Repeat("a", ResourceHandleLength)
|
||||
if handle, ok := ParseResourcePath(ResourceScheme + valid); !ok || handle != valid {
|
||||
t.Fatalf("ParseResourcePath(valid) = (%q, %v), want (%q, true)", handle, ok, valid)
|
||||
}
|
||||
|
||||
for _, value := range []string{
|
||||
"",
|
||||
"local://7/exports/a.png",
|
||||
ResourceScheme + strings.Repeat("a", ResourceHandleLength-1),
|
||||
ResourceScheme + strings.Repeat("a", ResourceHandleLength+1),
|
||||
ResourceScheme + strings.Repeat("a", ResourceHandleLength-1) + "/",
|
||||
// Multi-byte input must not slip through a byte-wise character check.
|
||||
ResourceScheme + strings.Repeat("中", ResourceHandleLength),
|
||||
} {
|
||||
if _, ok := ParseResourcePath(value); ok {
|
||||
t.Errorf("ParseResourcePath(%q) accepted a malformed reference", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanResourceReferences(t *testing.T) {
|
||||
first := ResourceScheme + strings.Repeat("a", ResourceHandleLength)
|
||||
second := ResourceScheme + strings.Repeat("b", ResourceHandleLength)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
text string
|
||||
want []string
|
||||
}{
|
||||
{name: "no references", text: "普通正文,没有引用。", want: nil},
|
||||
{
|
||||
name: "markdown image and link",
|
||||
text: "\n\n[表格](" + second + ")",
|
||||
want: []string{first, second},
|
||||
},
|
||||
{
|
||||
name: "repeated reference is reported once",
|
||||
text: " ",
|
||||
want: []string{first},
|
||||
},
|
||||
{
|
||||
// A longer run of handle characters is a different token; binding
|
||||
// its 22-char prefix would attach the wrong file.
|
||||
name: "over-long handle is not truncated into a match",
|
||||
text: ResourceScheme + strings.Repeat("a", ResourceHandleLength+3),
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "trailing punctuation still delimits a handle",
|
||||
text: "见 " + first + "。",
|
||||
want: []string{first},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := ScanResourceReferences(tc.text); !reflect.DeepEqual(got, tc.want) {
|
||||
t.Fatalf("ScanResourceReferences() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -216,11 +216,14 @@ build_sandbox_image() {
|
|||
|
||||
cd "$PROJECT_ROOT"
|
||||
|
||||
# 同时打上 main:默认镜像跟的是 main(见 sandbox.go 的 DefaultDockerImage),
|
||||
# 而 Docker 后端只在本地缺失时才去拉,本地不打这个标签就等于白构建。
|
||||
docker build \
|
||||
--platform $PLATFORM \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target sandbox \
|
||||
-t wechatopenai/weknora-sandbox:latest \
|
||||
-t wechatopenai/weknora-sandbox:main \
|
||||
.
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
|
|
@ -231,13 +234,14 @@ build_sandbox_image() {
|
|||
# Cube 从镜像直接构建模板,并以 :49983/health 探活,缺 envd 必然失败,
|
||||
# 因此 Cube 用的是注入了 envd 的变体镜像。详见 docs/sandbox-cluster.md。
|
||||
# 固定 linux/amd64:envd 的来源镜像 cubesandbox-base 不发布 arm64。
|
||||
log_info "构建沙箱镜像 Cube 变体 (weknora-sandbox:latest-cube)..."
|
||||
log_info "构建沙箱镜像 Cube 变体 (weknora-sandbox:main-cube)..."
|
||||
|
||||
docker build \
|
||||
--platform linux/amd64 \
|
||||
-f docker/Dockerfile.sandbox \
|
||||
--target cube \
|
||||
-t wechatopenai/weknora-sandbox:latest-cube \
|
||||
-t wechatopenai/weknora-sandbox:main-cube \
|
||||
.
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
|
|
@ -333,6 +337,8 @@ clean_images() {
|
|||
docker rmi wechatopenai/weknora-ui:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:latest-cube 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main 2>/dev/null || true
|
||||
docker rmi wechatopenai/weknora-sandbox:main-cube 2>/dev/null || true
|
||||
|
||||
docker image prune -f
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue