diff --git a/client/README.md b/client/README.md index de2a2bc6..f4162c60 100644 --- a/client/README.md +++ b/client/README.md @@ -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 diff --git a/client/README_EN.md b/client/README_EN.md index 0f454993..303f5413 100644 --- a/client/README_EN.md +++ b/client/README_EN.md @@ -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 diff --git a/client/agent.go b/client/agent.go index ccc9ee84..dc6d64f0 100644 --- a/client/agent.go +++ b/client/agent.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 diff --git a/client/skill.go b/client/skill.go index ce15f472..4548c437 100644 --- a/client/skill.go +++ b/client/skill.go @@ -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"` diff --git a/docs/agent-skills.md b/docs/agent-skills.md index a809f590..841b6f87 100644 --- a/docs/agent-skills.md +++ b/docs/agent-skills.md @@ -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 ``` diff --git a/docs/api/chat.md b/docs/api/chat.md index 1cc040cd..25a8e0ce 100644 --- a/docs/api/chat.md +++ b/docs/api/chat.md @@ -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` | 错误信息 | diff --git a/docs/api/skill.md b/docs/api/skill.md index a835ad24..b13f9c00 100644 --- a/docs/api/skill.md +++ b/docs/api/skill.md @@ -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` 所在目录),不启动沙箱。 diff --git a/docs/docs.go b/docs/docs.go index b6119a6b..5214272a 100644 --- a/docs/docs.go +++ b/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": [ diff --git a/docs/sandbox-cluster.md b/docs/sandbox-cluster.md index dea6b34b..d6b0ab5d 100644 --- a/docs/sandbox-cluster.md +++ b/docs/sandbox-cluster.md @@ -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` 下。 diff --git a/docs/swagger.json b/docs/swagger.json index b2b78777..2f6d0c8e 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -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": [ diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 9d04c7e0..ff0bf02b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -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: |- diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index 71f67b2d..0fb4b5f8 100644 --- a/frontend/src/api/chat/index.ts +++ b/frontend/src/api/chat/index.ts @@ -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://` — 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; diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index aac241ed..51760de1 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -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, diff --git a/frontend/src/components/SandboxConfigEditorDrawer.vue b/frontend/src/components/SandboxConfigEditorDrawer.vue index 0abb3246..97b7ce14 100644 --- a/frontend/src/components/SandboxConfigEditorDrawer.vue +++ b/frontend/src/components/SandboxConfigEditorDrawer.vue @@ -220,7 +220,7 @@ -

{{ 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() } diff --git a/frontend/src/components/SandboxSkillsPanel.vue b/frontend/src/components/SandboxSkillsPanel.vue index 8fa76ad4..1ccb7de6 100644 --- a/frontend/src/components/SandboxSkillsPanel.vue +++ b/frontend/src/components/SandboxSkillsPanel.vue @@ -133,11 +133,17 @@ :class="{ 'skill-item--focused': focusedSkillId === skill.id }" >

+ + + +
-

{{ failedError(skill) }}

+
    +
  • {{ line }}
  • +
@@ -344,6 +367,7 @@ import { updateSandboxConfigById, listConfigSkills, patchConfigSkill, + reinstallConfigSkill, uploadConfigSkill, installConfigSkillFromSource, type ConfigSkill, @@ -378,6 +402,7 @@ const skills = ref([]) const skillImage = ref(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 { diff --git a/frontend/src/components/css/chat-markdown.less b/frontend/src/components/css/chat-markdown.less index 1a3fe844..cdf0be79 100644 --- a/frontend/src/components/css/chat-markdown.less +++ b/frontend/src/components/css/chat-markdown.less @@ -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(); } diff --git a/frontend/src/components/css/chat-message-shared.less b/frontend/src/components/css/chat-message-shared.less index f0e560dd..f4d1b314 100644 --- a/frontend/src/components/css/chat-message-shared.less +++ b/frontend/src/components/css/chat-message-shared.less @@ -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; } diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 3959af6f..c11e438f 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -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 + 播放器 diff --git a/frontend/src/components/document-preview.vue b/frontend/src/components/document-preview.vue index f83ef2c0..966b14db 100644 --- a/frontend/src/components/document-preview.vue +++ b/frontend/src/components/document-preview.vue @@ -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('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(null); const docxContainer = ref(null); const imageNaturalWidth = ref(0); @@ -52,62 +70,14 @@ function toggleFullscreen() { } -const fileTypeMap: Record = {}; -['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 = { - 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 = { - 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 { if (props.knowledgeId) { return previewKnowledgeFile(props.knowledgeId); @@ -266,40 +240,80 @@ async function fetchPreviewBlob(): Promise { 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(() => {
+ + + + + @@ -409,6 +434,18 @@ onUnmounted(() => {