From 72581cb462611341c3fa3f1a75762d76bc56600c Mon Sep 17 00:00:00 2001 From: lyingbug Date: Fri, 11 Sep 2026 17:39:34 +0800 Subject: [PATCH] =?UTF-8?q?Revert=20"feat(sandbox):=20add=20safe=20live=20?= =?UTF-8?q?file=20management=20to=20session=20sandboxes=20(#3=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 01205b3d56c1f007457c76be223f7aad568d9593. --- client/README.md | 5 +- client/README_EN.md | 5 +- client/session_sandbox_files.go | 161 ----- docs/api/session.md | 63 -- docs/docs.go | 613 +---------------- docs/images/sandbox-live-files-panel.svg | 5 - docs/sandbox-live-files.md | 183 ----- docs/swagger.json | 615 +---------------- docs/swagger.yaml | 407 +---------- frontend/src/api/chat/sandbox-files.ts | 61 -- .../components/chat/SandboxSidePanel.test.mjs | 8 +- .../src/components/chat/SandboxSidePanel.vue | 19 +- .../src/composables/useChatSandboxPanel.ts | 2 +- frontend/src/i18n/locales/en-US.ts | 25 +- frontend/src/i18n/locales/ja-JP.ts | 25 +- frontend/src/i18n/locales/ko-KR.ts | 25 +- frontend/src/i18n/locales/ru-RU.ts | 25 +- frontend/src/i18n/locales/zh-CN.ts | 25 +- frontend/src/utils/request.ts | 6 +- .../components/SandboxFilesPanel.test.mjs | 33 - .../chat/components/SandboxFilesPanel.vue | 383 ----------- .../service/sandbox_live_files_service.go | 121 ---- .../sandbox_live_files_service_test.go | 86 --- internal/container/container.go | 3 - internal/handler/session/handler.go | 6 - .../handler/session/sandbox_live_files.go | 280 -------- .../session/sandbox_live_files_test.go | 339 ---------- .../router_api_key_capabilities_test.go | 5 - internal/router/routes_chat.go | 5 - internal/sandbox/capabilities.go | 44 -- internal/sandbox/docker_integration_test.go | 186 ------ internal/sandbox/session_live_files.go | 630 ------------------ internal/sandbox/session_live_files_test.go | 129 ---- 33 files changed, 31 insertions(+), 4497 deletions(-) delete mode 100644 client/session_sandbox_files.go delete mode 100644 docs/images/sandbox-live-files-panel.svg delete mode 100644 docs/sandbox-live-files.md delete mode 100644 frontend/src/api/chat/sandbox-files.ts delete mode 100644 frontend/src/views/chat/components/SandboxFilesPanel.test.mjs delete mode 100644 frontend/src/views/chat/components/SandboxFilesPanel.vue delete mode 100644 internal/application/service/sandbox_live_files_service.go delete mode 100644 internal/application/service/sandbox_live_files_service_test.go delete mode 100644 internal/handler/session/sandbox_live_files.go delete mode 100644 internal/handler/session/sandbox_live_files_test.go delete mode 100644 internal/sandbox/session_live_files.go delete mode 100644 internal/sandbox/session_live_files_test.go diff --git a/client/README.md b/client/README.md index 9410d04a..a0b7be99 100644 --- a/client/README.md +++ b/client/README.md @@ -16,9 +16,8 @@ 8. **消息管理**:获取和删除会话消息 9. **模型管理**:创建、获取、更新和删除模型 10. **沙箱技能**:向沙箱配置安装技能(zip 上传,或从 ClawHub / SkillHub / GitHub 等来源),并配置技能所需的环境变量 -11. **会话沙箱文件**:列出、上传、下载、重命名、删除会话已绑定沙箱的 `/workspace/output` 文件(`ListSandboxLiveFiles` / `OpenSandboxLiveFile` / `UploadSandboxLiveFile` / `RenameSandboxLiveFile` / `DeleteSandboxLiveFile`) -12. **长期记忆**:当前用户的跨会话记忆(设置开关、条目增删改、确认/否决、主题、文档亲和度、导出、立刻整理) -13. **认证**:登录、刷新令牌、切换激活空间(`SwitchTenant` 会写入最近活跃租户偏好) +11. **长期记忆**:当前用户的跨会话记忆(设置开关、条目增删改、确认/否决、主题、文档亲和度、导出、立刻整理) +12. **认证**:登录、刷新令牌、切换激活空间(`SwitchTenant` 会写入最近活跃租户偏好) ## 使用方法 diff --git a/client/README_EN.md b/client/README_EN.md index a4c62e9f..7c75e154 100644 --- a/client/README_EN.md +++ b/client/README_EN.md @@ -16,9 +16,8 @@ The client includes the following main functional modules: 8. **Model Management**: Create, retrieve, update, and delete models 9. **Evaluation Function**: Start evaluation tasks and get evaluation results 10. **Sandbox skills**: Install a skill onto a sandbox config (zip upload, or ClawHub / SkillHub / GitHub source) and configure the environment variables it needs -11. **Session sandbox files**: List, upload, download, rename, and delete files under the session sandbox `/workspace/output` root (`ListSandboxLiveFiles`, `OpenSandboxLiveFile`, `UploadSandboxLiveFile`, `RenameSandboxLiveFile`, `DeleteSandboxLiveFile`) -12. **Long-term memory**: The caller's cross-session memories (settings, items, confirm/reject, topics, document affinity, export, consolidate) -13. **Auth**: Login, refresh tokens, and switch the active workspace (`SwitchTenant` records the last-active-tenant preference) +11. **Long-term memory**: The caller's cross-session memories (settings, items, confirm/reject, topics, document affinity, export, consolidate) +12. **Auth**: Login, refresh tokens, and switch the active workspace (`SwitchTenant` records the last-active-tenant preference) ## Usage diff --git a/client/session_sandbox_files.go b/client/session_sandbox_files.go deleted file mode 100644 index 575fdcfa..00000000 --- a/client/session_sandbox_files.go +++ /dev/null @@ -1,161 +0,0 @@ -package client - -import ( - "bytes" - "context" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/url" -) - -// SandboxLiveFileEntry is one relative entry under a session sandbox's -// /workspace/output root. Type is "file", "directory", or "other". -type SandboxLiveFileEntry struct { - Name string `json:"name"` - Path string `json:"path"` - Type string `json:"type"` - Size int64 `json:"size"` - ModTime string `json:"mod_time"` -} - -type sandboxLiveFileListResponse struct { - Success bool `json:"success"` - Data []SandboxLiveFileEntry `json:"data"` -} - -func sandboxLiveFilesPath(sessionID string) string { - return "/api/v1/sessions/" + url.PathEscape(sessionID) + "/sandbox/files" -} - -// ListSandboxLiveFiles lists one directory level below /workspace/output. -// An empty relativeDir lists the output root. This call does not create or -// resume a paused sandbox. -func (c *Client) ListSandboxLiveFiles( - ctx context.Context, sessionID, relativeDir string, -) ([]SandboxLiveFileEntry, error) { - if sessionID == "" { - return nil, fmt.Errorf("session ID is required") - } - query := url.Values{} - if relativeDir != "" { - query.Set("path", relativeDir) - } - resp, err := c.doRequest(ctx, http.MethodGet, sandboxLiveFilesPath(sessionID), nil, query) - if err != nil { - return nil, err - } - var response sandboxLiveFileListResponse - if err := parseResponse(resp, &response); err != nil { - return nil, err - } - if response.Data == nil { - return []SandboxLiveFileEntry{}, nil - } - return response.Data, nil -} - -// OpenSandboxLiveFile starts a download of one live output file and returns -// the server-suggested filename plus a streaming reader. Callers MUST Close -// the reader. -func (c *Client) OpenSandboxLiveFile( - ctx context.Context, sessionID, relativePath string, -) (string, io.ReadCloser, error) { - if sessionID == "" { - return "", nil, fmt.Errorf("session ID is required") - } - if relativePath == "" { - return "", nil, fmt.Errorf("path is required") - } - query := url.Values{"path": {relativePath}} - resp, err := c.doRequest(ctx, http.MethodGet, sandboxLiveFilesPath(sessionID)+"/content", nil, query) - if err != nil { - return "", nil, err - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, _ := io.ReadAll(resp.Body) - _ = resp.Body.Close() - return "", nil, newAPIError(resp.StatusCode, body) - } - filename := filenameFromContentDisposition(resp.Header.Get("Content-Disposition")) - return filename, resp.Body, nil -} - -// UploadSandboxLiveFile writes a new file under /workspace/output without -// overwriting an existing entry. relativePath is POSIX-relative to that root. -func (c *Client) UploadSandboxLiveFile( - ctx context.Context, sessionID, relativePath, filename string, content []byte, -) error { - if sessionID == "" { - return fmt.Errorf("session ID is required") - } - if relativePath == "" { - return fmt.Errorf("path is required") - } - if filename == "" { - filename = relativePath - } - var body bytes.Buffer - writer := multipart.NewWriter(&body) - if err := writer.WriteField("path", relativePath); err != nil { - return fmt.Errorf("write sandbox upload path: %w", err) - } - part, err := writer.CreateFormFile("file", filename) - if err != nil { - return fmt.Errorf("create sandbox upload part: %w", err) - } - if _, err := part.Write(content); err != nil { - return fmt.Errorf("write sandbox upload part: %w", err) - } - if err := writer.Close(); err != nil { - return fmt.Errorf("close sandbox upload form: %w", err) - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+sandboxLiveFilesPath(sessionID), nil) - if err != nil { - return err - } - req.Header.Set("Content-Type", writer.FormDataContentType()) - c.applyAuthHeaders(ctx, req) - req.Body = io.NopCloser(bytes.NewReader(body.Bytes())) - req.ContentLength = int64(body.Len()) - - resp, err := c.httpClient.Do(req) - if err != nil { - return err - } - return parseResponse(resp, nil) -} - -// RenameSandboxLiveFile atomically renames a live-file entry without replacing -// an existing target. -func (c *Client) RenameSandboxLiveFile(ctx context.Context, sessionID, source, target string) error { - if sessionID == "" { - return fmt.Errorf("session ID is required") - } - resp, err := c.doRequest(ctx, http.MethodPatch, sandboxLiveFilesPath(sessionID), map[string]string{ - "source": source, - "target": target, - }, nil) - if err != nil { - return err - } - return parseResponse(resp, nil) -} - -// DeleteSandboxLiveFile removes a live-file entry or a prevalidated directory tree. -func (c *Client) DeleteSandboxLiveFile(ctx context.Context, sessionID, relativePath string) error { - if sessionID == "" { - return fmt.Errorf("session ID is required") - } - if relativePath == "" { - return fmt.Errorf("path is required") - } - query := url.Values{"path": {relativePath}} - resp, err := c.doRequest(ctx, http.MethodDelete, sandboxLiveFilesPath(sessionID), nil, query) - if err != nil { - return err - } - return parseResponse(resp, nil) -} diff --git a/docs/api/session.md b/docs/api/session.md index a1a88891..e95a6ff2 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -18,11 +18,6 @@ | POST | `/sessions/:session_id/pin` | 置顶会话 | | DELETE | `/sessions/:id/pin` | 取消置顶会话 | | GET | `/sessions/continue-stream/:session_id` | 继续未完成的流式响应 | -| GET | `/sessions/:id/sandbox/files` | 列出沙箱 `/workspace/output` 一层目录 | -| GET | `/sessions/:id/sandbox/files/content` | 下载沙箱输出文件(附件,≤16 MiB) | -| POST | `/sessions/:session_id/sandbox/files` | 上传新文件到输出目录(不覆盖) | -| PATCH | `/sessions/:id/sandbox/files` | 重命名输出条目(不覆盖) | -| DELETE | `/sessions/:id/sandbox/files` | 删除输出文件或安全目录树 | > **路由命名说明**:置顶接口的 POST 与 DELETE 使用了不同的路径参数名(POST 用 `:session_id`,DELETE 用 `:id`)。这是由于 gin 路由器为每个 HTTP 方法维护独立的 radix tree,且既有树中的通配符命名不同,必须保留以避免注册时的 `wildcard conflicts` panic。两者语义上都指会话 ID。 @@ -480,61 +475,3 @@ curl --location 'http://localhost:8080/api/v1/sessions/continue-stream/ceb9babb- **响应格式**: 服务器端事件流(Server-Sent Events),事件结构与 `/knowledge-chat/:session_id`、`/agent-chat/:session_id` 返回结果一致。若该消息当前在流中已无事件返回 `404 No stream events found`;若消息记录不存在返回 `404 Incomplete message not found`。 - -## GET `/sessions/:id/sandbox/files` - 列出沙箱实时输出文件 - -列出当前会话已绑定沙箱中 `/workspace/output` 的**一层**目录。浏览器只传相对 POSIX 路径,空 `path` 表示输出根。该接口是 lookup-only:没有绑定返回 409,沙箱已暂停也返回 409(`session sandbox is paused`),**不会**创建或唤醒实例。 - -目录条目的 `type` 为 `file`、`directory` 或 `other`(符号链接等不可操作节点)。单层最多 1024 条。 - -**请求**: - -```curl -curl --location 'http://localhost:8080/api/v1/sessions/ceb9babb-1e30-41d7-817d-fd584954304b/sandbox/files?path=reports' \ ---header 'X-API-Key: sk-xxxxx' -``` - -**查询参数**: - -| 字段 | 类型 | 必填 | 描述 | -| ------ | ------ | ---- | ---------------------------- | -| `path` | string | 否 | 相对目录,空或省略表示输出根 | - -**响应**: - -```json -{ - "success": true, - "data": [ - { - "name": "result.txt", - "path": "reports/result.txt", - "type": "file", - "size": 24, - "mod_time": "2026-09-11T04:00:00Z" - } - ] -} -``` - -## GET `/sessions/:id/sandbox/files/content` - 下载沙箱输出文件 - -以 `Content-Disposition: attachment` 下载单个常规文件,上限 16 MiB。同样不会唤醒已暂停沙箱。 - -**查询参数**: `path`(必填,相对文件路径)。 - -## POST `/sessions/:session_id/sandbox/files` - 上传沙箱输出文件 - -`multipart/form-data`:`path` 为相对目标路径,`file` 为文件本体。已存在则 409,超过 16 MiB 则 413。需要会话属主权限。 - -## PATCH `/sessions/:id/sandbox/files` - 重命名沙箱输出条目 - -```json -{ "source": "reports/old.txt", "target": "reports/new.txt" } -``` - -目标已存在返回 409,不会覆盖。 - -## DELETE `/sessions/:id/sandbox/files` - 删除沙箱输出条目 - -查询参数 `path` 为相对路径。目录会在确认树内无符号链接/特殊节点后递归删除;树过深或条目过多返回 400。 diff --git a/docs/docs.go b/docs/docs.go index d4bd3a58..25fb2605 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -8258,7 +8258,7 @@ const docTemplate = `{ "ApiKeyAuth": [] } ], - "description": "获取当前空间的所有MCP服务(含已保存工具目录数量)", + "description": "获取当前空间的所有MCP服务", "consumes": [ "application/json" ], @@ -13119,352 +13119,6 @@ const docTemplate = `{ } } }, - "/sessions/{id}/sandbox/files": { - "get": { - "security": [ - { - "Bearer": [] - } - ], - "description": "返回固定输出根下的一层目录条目。路径为相对 POSIX 路径,空路径表示根。不会创建或唤醒已暂停的沙箱。", - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "列出会话沙箱 /workspace/output 下一层文件", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对目录,空为输出根", - "name": "path", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - }, - "delete": { - "security": [ - { - "Bearer": [] - } - ], - "description": "删除 /workspace/output 下的安全文件或已预校验的目录树。", - "tags": [ - "会话" - ], - "summary": "删除会话沙箱输出条目", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对路径", - "name": "path", - "in": "query", - "required": true - } - ], - "responses": { - "204": { - "description": "No Content" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - }, - "patch": { - "security": [ - { - "Bearer": [] - } - ], - "description": "在 /workspace/output 内原子重命名,目标已存在则冲突。不会覆盖。", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "重命名会话沙箱输出条目", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "源路径与目标路径", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/internal_handler_session.renameLiveFileRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{id}/sandbox/files/content": { - "get": { - "security": [ - { - "Bearer": [] - } - ], - "description": "以附件形式下载 /workspace/output 下的单个常规文件,上限 16 MiB。不会唤醒已暂停的沙箱。", - "produces": [ - "application/octet-stream" - ], - "tags": [ - "会话" - ], - "summary": "下载会话沙箱中的一个输出文件", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对文件路径", - "name": "path", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "file" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "413": { - "description": "Request Entity Too Large", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, - "/sessions/{id}/steer": { - "get": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "列出当前运行中尚未消费的排队消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{id}/steer/{steer_id}": { - "delete": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "删除一条排队中的消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "排队消息 ID", - "name": "steer_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/sessions/{session_id}/artifacts": { "get": { "security": [ @@ -13665,214 +13319,6 @@ const docTemplate = `{ } } }, - "/sessions/{session_id}/sandbox/files": { - "post": { - "security": [ - { - "Bearer": [] - } - ], - "description": "以 multipart 写入一个新文件,不覆盖已有条目。字段 path 为相对路径,file 为文件本体,上限 16 MiB。", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "上传文件到会话沙箱输出目录", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对目标路径", - "name": "path", - "in": "formData", - "required": true - }, - { - "type": "file", - "description": "文件内容", - "name": "file", - "in": "formData", - "required": true - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "413": { - "description": "Request Entity Too Large", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, - "/sessions/{session_id}/steer": { - "post": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "向运行中的对话追加消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "description": "追加消息", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/internal_handler_session.SteerMessageRequest" - } - } - ], - "responses": { - "200": { - "description": "queued | new_run", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "请求参数错误", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "会话不存在", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{session_id}/steer/{steer_id}/inject": { - "post": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "将排队消息改为立即注入", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "排队消息 ID", - "name": "steer_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "queued | new_run", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/sessions/{session_id}/stop": { "post": { "security": [ @@ -18183,10 +17629,6 @@ const docTemplate = `{ "github_com_Tencent_WeKnora_internal_types.AgentStep": { "type": "object", "properties": { - "intermediate_answer": { - "description": "IntermediateAnswer preserves a plain answer followed by a loop-end steer.\nThe canonical final answer is still stored in Message.Content.", - "type": "boolean" - }, "iteration": { "description": "Iteration number (0-indexed)", "type": "integer" @@ -18209,13 +17651,6 @@ const docTemplate = `{ "items": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall" } - }, - "user_messages_before": { - "description": "UserMessagesBefore records consumed steer rows in delivery order, before\nthis model response. Unlike timestamps, this remains unambiguous on replay.", - "type": "array", - "items": { - "type": "string" - } } } }, @@ -26142,37 +25577,6 @@ const docTemplate = `{ } } }, - "internal_handler_session.SteerMessageRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "channel": { - "type": "string" - }, - "delivery": { - "description": "Delivery is \"after\" (default) or \"inject\". See the constants above.", - "type": "string" - }, - "expected_assistant_message_id": { - "description": "Optional for older clients. New clients pin delivery to the run they see\nand supply a stable ID so a consume event may precede the HTTP response.", - "type": "string" - }, - "mentioned_items": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.MentionedItemRequest" - } - }, - "query": { - "type": "string" - }, - "steer_id": { - "type": "string" - } - } - }, "internal_handler_session.StopSessionRequest": { "type": "object", "required": [ @@ -26197,21 +25601,6 @@ const docTemplate = `{ } } } - }, - "internal_handler_session.renameLiveFileRequest": { - "type": "object", - "required": [ - "source", - "target" - ], - "properties": { - "source": { - "type": "string" - }, - "target": { - "type": "string" - } - } } }, "securityDefinitions": { diff --git a/docs/images/sandbox-live-files-panel.svg b/docs/images/sandbox-live-files-panel.svg deleted file mode 100644 index 410e7087..00000000 --- a/docs/images/sandbox-live-files-panel.svg +++ /dev/null @@ -1,5 +0,0 @@ - - WeKnora sandbox live-files panel - The Files tab renders output breadcrumbs and live directory entries with upload, refresh, download, rename, and delete actions. - - diff --git a/docs/sandbox-live-files.md b/docs/sandbox-live-files.md deleted file mode 100644 index fc1b1beb..00000000 --- a/docs/sandbox-live-files.md +++ /dev/null @@ -1,183 +0,0 @@ -# Safe Live Files minimal design - -## Baseline and scope - -- Source of truth: `upstream/main` at `5db13a131e10e8ee2105211f665412ebc13bd98e` (2026-09-10). -- Main already has provider-neutral `SessionFileStore`, `SessionBoundManager`, and Docker/E2B/Cube filesystem primitives. It also has persisted message artifacts and their preview/download UI. -- Main does not expose the live session filesystem to the browser. The sandbox panel still contains a Desktop placeholder. -- PR-02 adds only browse, upload, download, rename, delete, refresh, and breadcrumbs under `/workspace/output`. -- Out of scope: editor, VNC/Desktop, batch operations, archive/zip, audit, terminal changes, resource limits, ArtifactKind, and new provider-specific file managers. - -Open PR #3146 remains merge-dirty and implements a separate Workbench service/ticket/socket/UI stack. It is competition analysis only. PR-02 will reuse current session routes, bearer/API-key authentication, ownership checks, pinned sandbox binding, side panel, and document preview instead of copying that architecture. - -## A. Existing remote FS plus server-side path checks - -Shape: - -```text -relative browser path - -> lexical join with /workspace/output - -> SessionFileStore List/Stat/Read/Write/Remove -``` - -Advantages: - -- smallest code change; -- reuses all current provider data-plane file transfers. - -Rejected as the security boundary because lexical checks cannot stop intermediate symlink traversal. `path.Clean` plus prefix matching proves only the spelling of the path. The current Docker `Stat` documentation explicitly records that `/workspace/output/link-to-etc/passwd` follows the intermediate link. A preflight `Stat` followed by `ReadFile` also has a time-of-check/time-of-use race. - -## B. Fixed in-sandbox safe helper - -Shape: - -```text -authenticated session route - -> pinned SessionBoundManager - -> fixed Python helper through RemoteSandboxClient.Exec - -> open /workspace/output with O_DIRECTORY | O_NOFOLLOW - -> component-by-component dirfd traversal with O_NOFOLLOW - -> operation by *at syscall / dir_fd -``` - -The helper is a server constant, not user-authored shell. A JSON request travels on stdin; path components never enter a shell command. It uses Linux dirfds as the capability boundary: - -- open the root itself with `O_NOFOLLOW`, rejecting an output-root symlink; -- reject absolute, empty component, `.`, `..`, NUL, backslash, and invalid UTF-8 at the Go boundary; -- open every intermediate directory relative to its parent fd with `O_DIRECTORY|O_NOFOLLOW`; -- inspect the final entry with `follow_symlinks=false`; -- accept only regular files and directories appropriate to the operation; -- reject symlinks, FIFO, socket, block/character device, and unknown node types; -- upload through an exclusive temporary regular file in the already-open parent, then atomically publish it without overwriting an existing name; -- rename with source and destination parent dirfds; destination collision is an error; -- recursively delete only after fd-relative traversal confirms the tree contains no special node or symlink. - -Advantages: - -- one implementation for Docker, E2B, and Cube; -- no provider-specific `*FileManager` family; -- the check and mutation use the same directory handles, removing the prefix and intermediate-symlink TOCTOU problem; -- adding a backend only requires the already-existing Exec capability. - -Costs: - -- transfers are JSON/base64 rather than the provider file API, so v1 imposes a strict per-file size cap; -- depends on Python 3 in the standard sandbox image/template, already required by the current agent sandbox runtime. - -Selected for PR-02. - -## C. Optional capability/interface extension - -Adding provider `Rename`/safe-open methods to `RemoteSandboxClient` would force every adapter and fake to implement a new contract, while still not giving E2B/Cube a documented no-follow guarantee. Three adapter implementations would duplicate the same security policy and produce the forbidden Docker/E2B/Cube file-manager split. - -PR-02 instead adds one narrow session-facing `SessionLiveFileManager` capability implemented by `SessionBoundManager`. It does not replace `SessionFileStore`; internal agent/attachment/artifact code continues using the existing interface. The application service narrows to the live-files capability only for browser operations. - -## Security and identity invariants - -```text -browser session id - -> current authenticated tenant/user - -> SessionService.GetSession ownership check - -> SessionSandboxPinner config id - -> tenant-scoped SessionBoundManager - -> binding lookup by tenant + session - -> opaque provider handle -``` - -- The browser never supplies sandbox/container/PTY IDs. -- API paths are relative POSIX paths. The browser-visible root is always `/workspace/output` and is never accepted as input. -- Empty path denotes the root only for listing. -- The service is lookup-only: no live binding returns a not-found/conflict response and never provisions a sandbox. -- Tenant A + Session B and Tenant B + Session A both fail before any provider operation. Non-owned and nonexistent sessions share the same not-found response. -- Download responses use `private, no-store`, attachment disposition, an extension-derived safe content type, and `X-Content-Type-Options: nosniff`. -- Upload/read maximum is 16 MiB of file bytes. Request-body overhead is bounded separately. -- Names returned by the helper are relative to the fixed root; absolute provider paths never reach the browser. -- Browser JSON uses `type=directory` (not the internal remote listing alias `dir`). -- GET list/download and other live-file operations peek the bound sandbox state first. A paused, transitioning, or list-miss binding returns a conflict and does **not** Connect, so opening the Files tab cannot resume (and re-bill) an E2B/Cube/Docker instance. -- Listings cap at 1024 entries; delete trees cap at 64 depth and 8192 entries. - -## API - -All routes stay under the existing authenticated session group: - -| Method | Route | Input | Result | -|---|---|---|---| -| GET | `/sessions/:id/sandbox/files` | query `path` (empty=root) | one directory level | -| POST | `/sessions/:id/sandbox/files` | multipart `path`, `file` | upload, no overwrite | -| GET | `/sessions/:id/sandbox/files/content` | query `path` | attachment download | -| PATCH | `/sessions/:id/sandbox/files` | JSON `source`, `target` | atomic rename, no overwrite | -| DELETE | `/sessions/:id/sandbox/files` | query `path` | delete file or safe directory tree | - -Application errors distinguish invalid path (400), missing file (404), collision or no live sandbox (409), size limit (413), and provider/internal failure (500) without exposing provider paths. - -## UI - -Replace the Desktop placeholder with Files, preserving the existing panel hierarchy: - -```text -Artifacts | Terminal | Files -``` - -`SandboxFilesPanel.vue` owns only live-file state: - -- lazy load when Files becomes active; -- breadcrumb navigation rooted at “Output”; -- manual refresh; -- folder open; -- regular-file download; -- upload into current directory; -- inline rename; -- delete confirmation; -- empty/loading/error states; -- special entries, if ever returned, are non-actionable. - -It does not duplicate `document-preview.vue`; v1 downloads rather than adding a second preview pipeline. - -## Expected production files - -- `internal/sandbox/capabilities.go`: narrow session live-file capability. -- `internal/sandbox/session_live_files.go`: relative path validation, fixed helper protocol, lookup-only operations, size limits, error mapping. -- `internal/application/service/sandbox_live_files_service.go`: pinned manager resolution and browser-safe DTOs. -- `internal/handler/session/sandbox_live_files.go`: authenticated HTTP handlers and bounded multipart/download transport. -- `internal/handler/session/handler.go`, `internal/container/container.go`, `internal/router/routes_chat.go`: normal DI and existing session-route registration. -- `frontend/src/api/chat/sandbox-files.ts`: typed API calls. -- `frontend/src/views/chat/components/SandboxFilesPanel.vue`: focused browser UI. -- `frontend/src/components/chat/SandboxSidePanel.vue`, `frontend/src/composables/useChatSandboxPanel.ts`: replace Desktop tab/placeholder. -- locale files: Files labels only. -- `docs/api/session.md`, `docs/docs.go`, `docs/swagger.json`, `docs/swagger.yaml`: HTTP surface. -- `client/session_sandbox_files.go`: official Go SDK helpers. - -No Docker/E2B/Cube adapter file should need production changes. - -## Test plan - -Unit/service/handler: - -- path parser: root, nested path, absolute, traversal, nested traversal, separators, NUL/control, overlong; -- list and nested list; -- binary upload/download round trip; -- rename and collision; -- delete file/tree, missing entry; -- 16 MiB boundary and oversized request; -- root/intermediate/final symlink; -- upload-parent and rename source/target escape; -- FIFO/socket/special node; -- tenant A/session B and tenant B/session A negative cases; -- no binding does not provision; -- content-disposition/no-store/nosniff headers. - -Real Docker integration: - -- create one actual session sandbox from the standard image; -- list/upload/download/rename/delete nested files through `SessionBoundManager`; -- create symlink/FIFO attack fixtures through a trusted test exec and prove every browser operation refuses them; -- prove another tenant context cannot access the first tenant/session binding. - -Frontend: - -- API relative-path encoding and multipart behavior; -- tab order and Desktop removal; -- breadcrumb, refresh, upload, rename, delete, and error-state source/behavior tests; -- `npm run type-check`. - -Before PR: gofmt, focused tests, real Docker integration, `git diff --check`, diff-scoped lint, UI screenshot/recording, self-review, fetch/rebase latest `upstream/main`, and rerun affected tests. diff --git a/docs/swagger.json b/docs/swagger.json index 81394021..1f1c54b2 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -8251,7 +8251,7 @@ "ApiKeyAuth": [] } ], - "description": "获取当前空间的所有MCP服务(含已保存工具目录数量)", + "description": "获取当前空间的所有MCP服务", "consumes": [ "application/json" ], @@ -13112,352 +13112,6 @@ } } }, - "/sessions/{id}/sandbox/files": { - "get": { - "security": [ - { - "Bearer": [] - } - ], - "description": "返回固定输出根下的一层目录条目。路径为相对 POSIX 路径,空路径表示根。不会创建或唤醒已暂停的沙箱。", - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "列出会话沙箱 /workspace/output 下一层文件", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对目录,空为输出根", - "name": "path", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - }, - "delete": { - "security": [ - { - "Bearer": [] - } - ], - "description": "删除 /workspace/output 下的安全文件或已预校验的目录树。", - "tags": [ - "会话" - ], - "summary": "删除会话沙箱输出条目", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对路径", - "name": "path", - "in": "query", - "required": true - } - ], - "responses": { - "204": { - "description": "No Content" - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - }, - "patch": { - "security": [ - { - "Bearer": [] - } - ], - "description": "在 /workspace/output 内原子重命名,目标已存在则冲突。不会覆盖。", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "重命名会话沙箱输出条目", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "description": "源路径与目标路径", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/internal_handler_session.renameLiveFileRequest" - } - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{id}/sandbox/files/content": { - "get": { - "security": [ - { - "Bearer": [] - } - ], - "description": "以附件形式下载 /workspace/output 下的单个常规文件,上限 16 MiB。不会唤醒已暂停的沙箱。", - "produces": [ - "application/octet-stream" - ], - "tags": [ - "会话" - ], - "summary": "下载会话沙箱中的一个输出文件", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对文件路径", - "name": "path", - "in": "query", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "file" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "413": { - "description": "Request Entity Too Large", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, - "/sessions/{id}/steer": { - "get": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "列出当前运行中尚未消费的排队消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{id}/steer/{steer_id}": { - "delete": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "删除一条排队中的消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "排队消息 ID", - "name": "steer_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/sessions/{session_id}/artifacts": { "get": { "security": [ @@ -13658,214 +13312,6 @@ } } }, - "/sessions/{session_id}/sandbox/files": { - "post": { - "security": [ - { - "Bearer": [] - } - ], - "description": "以 multipart 写入一个新文件,不覆盖已有条目。字段 path 为相对路径,file 为文件本体,上限 16 MiB。", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "tags": [ - "会话" - ], - "summary": "上传文件到会话沙箱输出目录", - "parameters": [ - { - "type": "string", - "description": "会话ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "相对目标路径", - "name": "path", - "in": "formData", - "required": true - }, - { - "type": "file", - "description": "文件内容", - "name": "file", - "in": "formData", - "required": true - } - ], - "responses": { - "201": { - "description": "Created", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "409": { - "description": "Conflict", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "413": { - "description": "Request Entity Too Large", - "schema": { - "type": "object", - "additionalProperties": true - } - } - } - } - }, - "/sessions/{session_id}/steer": { - "post": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "向运行中的对话追加消息", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "description": "追加消息", - "name": "request", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/internal_handler_session.SteerMessageRequest" - } - } - ], - "responses": { - "200": { - "description": "queued | new_run", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "请求参数错误", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "会话不存在", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, - "/sessions/{session_id}/steer/{steer_id}/inject": { - "post": { - "security": [ - { - "Bearer": [] - }, - { - "ApiKeyAuth": [] - } - ], - "description": "把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。", - "produces": [ - "application/json" - ], - "tags": [ - "问答" - ], - "summary": "将排队消息改为立即注入", - "parameters": [ - { - "type": "string", - "description": "会话 ID", - "name": "session_id", - "in": "path", - "required": true - }, - { - "type": "string", - "description": "排队消息 ID", - "name": "steer_id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "queued | new_run", - "schema": { - "type": "object", - "additionalProperties": true - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - }, - "503": { - "description": "活 turn 查询失败,可重试", - "schema": { - "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" - } - } - } - } - }, "/sessions/{session_id}/stop": { "post": { "security": [ @@ -18176,10 +17622,6 @@ "github_com_Tencent_WeKnora_internal_types.AgentStep": { "type": "object", "properties": { - "intermediate_answer": { - "description": "IntermediateAnswer preserves a plain answer followed by a loop-end steer.\nThe canonical final answer is still stored in Message.Content.", - "type": "boolean" - }, "iteration": { "description": "Iteration number (0-indexed)", "type": "integer" @@ -18202,13 +17644,6 @@ "items": { "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall" } - }, - "user_messages_before": { - "description": "UserMessagesBefore records consumed steer rows in delivery order, before\nthis model response. Unlike timestamps, this remains unambiguous on replay.", - "type": "array", - "items": { - "type": "string" - } } } }, @@ -26135,37 +25570,6 @@ } } }, - "internal_handler_session.SteerMessageRequest": { - "type": "object", - "required": [ - "query" - ], - "properties": { - "channel": { - "type": "string" - }, - "delivery": { - "description": "Delivery is \"after\" (default) or \"inject\". See the constants above.", - "type": "string" - }, - "expected_assistant_message_id": { - "description": "Optional for older clients. New clients pin delivery to the run they see\nand supply a stable ID so a consume event may precede the HTTP response.", - "type": "string" - }, - "mentioned_items": { - "type": "array", - "items": { - "$ref": "#/definitions/internal_handler_session.MentionedItemRequest" - } - }, - "query": { - "type": "string" - }, - "steer_id": { - "type": "string" - } - } - }, "internal_handler_session.StopSessionRequest": { "type": "object", "required": [ @@ -26190,21 +25594,6 @@ } } } - }, - "internal_handler_session.renameLiveFileRequest": { - "type": "object", - "required": [ - "source", - "target" - ], - "properties": { - "source": { - "type": "string" - }, - "target": { - "type": "string" - } - } } }, "securityDefinitions": { @@ -26221,4 +25610,4 @@ "in": "header" } } -} \ No newline at end of file +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index bc8cd44c..e47d0677 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -258,11 +258,6 @@ definitions: type: object github_com_Tencent_WeKnora_internal_types.AgentStep: properties: - intermediate_answer: - description: |- - IntermediateAnswer preserves a plain answer followed by a loop-end steer. - The canonical final answer is still stored in Message.Content. - type: boolean iteration: description: Iteration number (0-indexed) type: integer @@ -284,13 +279,6 @@ definitions: items: $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.ToolCall' type: array - user_messages_before: - description: |- - UserMessagesBefore records consumed steer rows in delivery order, before - this model response. Unlike timestamps, this remains unambiguous on replay. - items: - type: string - type: array type: object github_com_Tencent_WeKnora_internal_types.AnswerStrategy: enum: @@ -6455,30 +6443,6 @@ definitions: required: - query type: object - internal_handler_session.SteerMessageRequest: - properties: - channel: - type: string - delivery: - description: Delivery is "after" (default) or "inject". See the constants - above. - type: string - expected_assistant_message_id: - description: |- - Optional for older clients. New clients pin delivery to the run they see - and supply a stable ID so a consume event may precede the HTTP response. - type: string - mentioned_items: - items: - $ref: '#/definitions/internal_handler_session.MentionedItemRequest' - type: array - query: - type: string - steer_id: - type: string - required: - - query - type: object internal_handler_session.StopSessionRequest: properties: message_id: @@ -6495,16 +6459,6 @@ definitions: type: string type: array type: object - internal_handler_session.renameLiveFileRequest: - properties: - source: - type: string - target: - type: string - required: - - source - - target - type: object info: contact: name: WeKnora Github @@ -11793,7 +11747,7 @@ paths: get: consumes: - application/json - description: 获取当前空间的所有MCP服务(含已保存工具目录数量) + description: 获取当前空间的所有MCP服务 produces: - application/json responses: @@ -12046,8 +12000,7 @@ paths: post: consumes: - application/json - description: 显式连接上游并原子替换完整目录。OAuth 服务写入当前用户的快照,Viewer 及以上可调用;静态认证写入租户共享快照,需要 - Admin。 + description: 显式连接上游并原子替换完整目录。OAuth 服务写入当前用户的快照,Viewer 及以上可调用;静态认证写入租户共享快照,需要 Admin。 parameters: - description: MCP服务ID in: path @@ -14838,228 +14791,6 @@ paths: summary: 取消置顶会话 tags: - 会话 - /sessions/{id}/sandbox/files: - delete: - description: 删除 /workspace/output 下的安全文件或已预校验的目录树。 - parameters: - - description: 会话ID - in: path - name: id - required: true - type: string - - description: 相对路径 - in: query - name: path - required: true - type: string - responses: - "204": - description: No Content - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "409": - description: Conflict - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - summary: 删除会话沙箱输出条目 - tags: - - 会话 - get: - description: 返回固定输出根下的一层目录条目。路径为相对 POSIX 路径,空路径表示根。不会创建或唤醒已暂停的沙箱。 - parameters: - - description: 会话ID - in: path - name: id - required: true - type: string - - description: 相对目录,空为输出根 - in: query - name: path - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "409": - description: Conflict - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - summary: 列出会话沙箱 /workspace/output 下一层文件 - tags: - - 会话 - patch: - consumes: - - application/json - description: 在 /workspace/output 内原子重命名,目标已存在则冲突。不会覆盖。 - parameters: - - description: 会话ID - in: path - name: id - required: true - type: string - - description: 源路径与目标路径 - in: body - name: request - required: true - schema: - $ref: '#/definitions/internal_handler_session.renameLiveFileRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "409": - description: Conflict - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - summary: 重命名会话沙箱输出条目 - tags: - - 会话 - /sessions/{id}/sandbox/files/content: - get: - description: 以附件形式下载 /workspace/output 下的单个常规文件,上限 16 MiB。不会唤醒已暂停的沙箱。 - parameters: - - description: 会话ID - in: path - name: id - required: true - type: string - - description: 相对文件路径 - in: query - name: path - required: true - type: string - produces: - - application/octet-stream - responses: - "200": - description: OK - schema: - type: file - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "409": - description: Conflict - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "413": - description: Request Entity Too Large - schema: - additionalProperties: true - type: object - security: - - Bearer: [] - summary: 下载会话沙箱中的一个输出文件 - tags: - - 会话 - /sessions/{id}/steer: - get: - description: 刷新页面后用来恢复输入框上方的队列。没有正在运行的 turn 时返回空列表。 - parameters: - - description: 会话 ID - in: path - name: id - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "503": - description: 活 turn 查询失败,可重试 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - - ApiKeyAuth: [] - summary: 列出当前运行中尚未消费的排队消息 - tags: - - 问答 - /sessions/{id}/steer/{steer_id}: - delete: - description: 从当前运行的排队列表里去掉一条,不再注入也不再作为 follow-up 发出。 - parameters: - - description: 会话 ID - in: path - name: id - required: true - type: string - - description: 排队消息 ID - in: path - name: steer_id - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - additionalProperties: true - type: object - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "503": - description: 活 turn 查询失败,可重试 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - - ApiKeyAuth: [] - summary: 删除一条排队中的消息 - tags: - - 问答 /sessions/{session_id}/artifacts: get: description: 返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL) @@ -15185,140 +14916,6 @@ paths: summary: 置顶会话 tags: - 会话 - /sessions/{session_id}/sandbox/files: - post: - consumes: - - multipart/form-data - description: 以 multipart 写入一个新文件,不覆盖已有条目。字段 path 为相对路径,file 为文件本体,上限 16 MiB。 - parameters: - - description: 会话ID - in: path - name: session_id - required: true - type: string - - description: 相对目标路径 - in: formData - name: path - required: true - type: string - - description: 文件内容 - in: formData - name: file - required: true - type: file - produces: - - application/json - responses: - "201": - description: Created - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "409": - description: Conflict - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "413": - description: Request Entity Too Large - schema: - additionalProperties: true - type: object - security: - - Bearer: [] - summary: 上传文件到会话沙箱输出目录 - tags: - - 会话 - /sessions/{session_id}/steer: - post: - consumes: - - application/json - description: 向运行中的 agent turn 追加用户消息(after 排队 / inject 注入)。无活 turn 时返回 new_run。 - parameters: - - description: 会话 ID - in: path - name: session_id - required: true - type: string - - description: 追加消息 - in: body - name: request - required: true - schema: - $ref: '#/definitions/internal_handler_session.SteerMessageRequest' - produces: - - application/json - responses: - "200": - description: queued | new_run - schema: - additionalProperties: true - type: object - "400": - description: 请求参数错误 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: 会话不存在 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "503": - description: 活 turn 查询失败,可重试 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - - ApiKeyAuth: [] - summary: 向运行中的对话追加消息 - tags: - - 问答 - /sessions/{session_id}/steer/{steer_id}/inject: - post: - description: 把一条 delivery=after 的排队消息改为 inject,运行中的 agent 会在下一轮边界读到它。 - parameters: - - description: 会话 ID - in: path - name: session_id - required: true - type: string - - description: 排队消息 ID - in: path - name: steer_id - required: true - type: string - produces: - - application/json - responses: - "200": - description: queued | new_run - schema: - additionalProperties: true - type: object - "400": - description: Bad Request - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "404": - description: Not Found - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - "503": - description: 活 turn 查询失败,可重试 - schema: - $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' - security: - - Bearer: [] - - ApiKeyAuth: [] - summary: 将排队消息改为立即注入 - tags: - - 问答 /sessions/{session_id}/stop: post: consumes: diff --git a/frontend/src/api/chat/sandbox-files.ts b/frontend/src/api/chat/sandbox-files.ts deleted file mode 100644 index 16fef9b9..00000000 --- a/frontend/src/api/chat/sandbox-files.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { del, get, getDown, patch, postUpload } from '@/utils/request' - -export type SandboxLiveFileType = 'file' | 'directory' | 'dir' | 'other' - -export interface SandboxLiveFileEntry { - name: string - path: string - type: SandboxLiveFileType - size: number - mod_time: string -} - -export const MAX_SANDBOX_LIVE_FILE_BYTES = 16 * 1024 * 1024 - -interface SandboxLiveFileListResponse { - success: boolean - data: SandboxLiveFileEntry[] -} - -const sessionFilesURL = (sessionId: string) => - `/api/v1/sessions/${encodeURIComponent(sessionId)}/sandbox/files` - -export async function listSandboxLiveFiles( - sessionId: string, - relativeDir = '', -): Promise { - const query = new URLSearchParams() - if (relativeDir) query.set('path', relativeDir) - const suffix = query.size ? `?${query.toString()}` : '' - const response = await get(`${sessionFilesURL(sessionId)}${suffix}`) - return response.data -} - -export function downloadSandboxLiveFile(sessionId: string, relativePath: string): Promise { - const query = new URLSearchParams({ path: relativePath }) - return getDown(`${sessionFilesURL(sessionId)}/content?${query.toString()}`) -} - -export function uploadSandboxLiveFile( - sessionId: string, - relativePath: string, - file: File, -): Promise { - const form = new FormData() - form.append('path', relativePath) - form.append('file', file) - return postUpload(sessionFilesURL(sessionId), form) -} - -export function renameSandboxLiveFile( - sessionId: string, - source: string, - target: string, -): Promise { - return patch(sessionFilesURL(sessionId), { source, target }) -} - -export function deleteSandboxLiveFile(sessionId: string, relativePath: string): Promise { - const query = new URLSearchParams({ path: relativePath }) - return del(`${sessionFilesURL(sessionId)}?${query.toString()}`) -} diff --git a/frontend/src/components/chat/SandboxSidePanel.test.mjs b/frontend/src/components/chat/SandboxSidePanel.test.mjs index fd98bf8f..319cb552 100644 --- a/frontend/src/components/chat/SandboxSidePanel.test.mjs +++ b/frontend/src/components/chat/SandboxSidePanel.test.mjs @@ -7,13 +7,11 @@ const panel = readFileSync(new URL('./SandboxSidePanel.vue', import.meta.url), ' test('artifacts is the first sandbox panel tab', () => { const artifacts = panel.indexOf("id: 'artifacts' as SandboxPanelTab") const terminal = panel.indexOf("id: 'terminal' as SandboxPanelTab") - const files = panel.indexOf("id: 'files' as SandboxPanelTab") + const desktop = panel.indexOf("id: 'desktop' as SandboxPanelTab") assert.notEqual(artifacts, -1) assert.ok(artifacts < terminal) - assert.ok(terminal < files) - assert.match(panel, / - +
+ +

{{ t('chat.sandbox.desktopPlaceholder') }}

+
@@ -96,7 +93,6 @@ import { } from '@/composables/useChatSandboxPanel' import SandboxTerminal from '@/views/chat/components/SandboxTerminal.vue' import ChatArtifactsPanel from '@/views/chat/components/ChatArtifactsPanel.vue' -import SandboxFilesPanel from '@/views/chat/components/SandboxFilesPanel.vue' import type { SessionArtifactItem } from '@/utils/sessionArtifacts' const props = withDefaults( @@ -123,7 +119,7 @@ const panel = useChatSandboxPanel() const tabs = computed(() => [ { id: 'artifacts' as SandboxPanelTab, icon: 'folder', label: t('chat.sandbox.tabArtifacts') }, { id: 'terminal' as SandboxPanelTab, icon: 'terminal', label: t('chat.sandbox.tabTerminal') }, - { id: 'files' as SandboxPanelTab, icon: 'folder-open', label: t('chat.sandbox.tabFiles') }, + { id: 'desktop' as SandboxPanelTab, icon: 'desktop', label: t('chat.sandbox.tabDesktop') }, ]) // 终端实例惰性挂载(首次切到终端 tab 时),面板关闭即销毁(v-if), @@ -338,8 +334,7 @@ function startResize(event: MouseEvent) { } .chat-sandbox-panel__terminal, -.chat-sandbox-panel__artifacts, -.chat-sandbox-panel__files { +.chat-sandbox-panel__artifacts { flex: 1; min-height: 0; min-width: 0; diff --git a/frontend/src/composables/useChatSandboxPanel.ts b/frontend/src/composables/useChatSandboxPanel.ts index 8dba741b..8cc3fbc0 100644 --- a/frontend/src/composables/useChatSandboxPanel.ts +++ b/frontend/src/composables/useChatSandboxPanel.ts @@ -1,6 +1,6 @@ import { inject, provide, ref, type InjectionKey, type Ref } from 'vue' -export type SandboxPanelTab = 'artifacts' | 'terminal' | 'files' +export type SandboxPanelTab = 'artifacts' | 'terminal' | 'desktop' export type ArtifactPanelFocus = { messageId: string diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index b24ac3eb..0cc7aada 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3422,35 +3422,14 @@ export default { panelTitle: 'Sandbox', tabArtifacts: 'Files', tabTerminal: 'Terminal', - tabFiles: 'Files', + tabDesktop: 'Desktop', artifactsEmpty: 'No generated files in this conversation yet.', artifactScope: 'File scope', artifactsCurrent: 'This turn', artifactsAll: 'All files', artifactsSearch: 'Search filenames', artifactsNoMatches: 'No matching files', - filesTitle: 'Live sandbox files', - filesBreadcrumbs: 'Current folder', - filesRoot: 'output', - filesUpload: 'Upload files', - filesRefresh: 'Refresh', - filesLoading: 'Loading files…', - filesEmpty: 'This folder is empty', - filesDirectory: 'Folder', - filesDownload: 'Download', - filesRename: 'Rename', - filesDelete: 'Delete', - filesDeleteConfirm: 'Delete {name}? This cannot be undone.', - filesInvalidName: 'Enter a filename without path separators', - filesLoadFailed: 'Could not load sandbox files', - filesDownloadFailed: 'Download failed', - filesUploadComplete: 'Upload complete', - filesUploadFailed: 'Upload failed', - filesRenameFailed: 'Rename failed', - filesDeleteFailed: 'Delete failed', - filesPaused: 'The sandbox is paused. Start it from the Terminal tab before browsing files so this panel does not resume it and incur charges.', - filesTooLarge: 'File exceeds the 16 MiB limit', - filesTooMany: 'This folder has too many entries to list or delete', + desktopPlaceholder: 'Desktop visualization coming soon', notStarted: 'The terminal is not running yet. Starting it connects to this conversation\'s sandbox, creating or resuming one if none is available.', paused: 'This conversation\'s sandbox is paused. Starting the terminal resumes it.', start: 'Start terminal', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index ef38770c..bd6bc389 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -3422,35 +3422,14 @@ export default { panelTitle: 'サンドボックス', tabArtifacts: 'ファイル', tabTerminal: 'ターミナル', - tabFiles: 'ファイル', + tabDesktop: 'デスクトップ', artifactsEmpty: 'この会話で生成されたファイルはまだありません', artifactScope: 'ファイルの範囲', artifactsCurrent: 'このターン', artifactsAll: 'すべて', artifactsSearch: 'ファイル名を検索', artifactsNoMatches: '一致するファイルがありません', - filesTitle: 'サンドボックスのライブファイル', - filesBreadcrumbs: '現在のフォルダー', - filesRoot: '出力', - filesUpload: 'ファイルをアップロード', - filesRefresh: '更新', - filesLoading: 'ファイルを読み込み中…', - filesEmpty: 'このフォルダーは空です', - filesDirectory: 'フォルダー', - filesDownload: 'ダウンロード', - filesRename: '名前を変更', - filesDelete: '削除', - filesDeleteConfirm: '{name} を削除しますか?この操作は取り消せません。', - filesInvalidName: 'パス区切り文字を含まないファイル名を入力してください', - filesLoadFailed: 'サンドボックスのファイルを読み込めません', - filesDownloadFailed: 'ダウンロードに失敗しました', - filesUploadComplete: 'アップロードが完了しました', - filesUploadFailed: 'アップロードに失敗しました', - filesRenameFailed: '名前の変更に失敗しました', - filesDeleteFailed: '削除に失敗しました', - filesPaused: 'サンドボックスは一時停止中です。ファイルを閲覧する前にターミナルから起動してください。このパネルは課金を避けるため自動では再開しません。', - filesTooLarge: 'ファイルが 16 MiB の上限を超えています', - filesTooMany: 'フォルダーの項目が多すぎて一覧表示または削除できません', + desktopPlaceholder: 'デスクトップの可視化は近日対応予定です', notStarted: 'ターミナルはまだ起動していません。起動するとこの会話のサンドボックスに接続し、存在しないか一時停止中の場合は作成または再開します。', paused: 'この会話のサンドボックスは一時停止中です。ターミナルを起動すると再開します。', start: 'ターミナルを起動', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index be50598c..57920ba9 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3459,35 +3459,14 @@ export default { panelTitle: '샌드박스', tabArtifacts: '파일', tabTerminal: '터미널', - tabFiles: '파일', + tabDesktop: '데스크톱', artifactsEmpty: '이 대화에서 생성된 파일이 없습니다', artifactScope: '파일 범위', artifactsCurrent: '이번 응답', artifactsAll: '전체', artifactsSearch: '파일 이름 검색', artifactsNoMatches: '일치하는 파일이 없습니다', - filesTitle: '라이브 샌드박스 파일', - filesBreadcrumbs: '현재 폴더', - filesRoot: '출력', - filesUpload: '파일 업로드', - filesRefresh: '새로 고침', - filesLoading: '파일 불러오는 중…', - filesEmpty: '이 폴더는 비어 있습니다', - filesDirectory: '폴더', - filesDownload: '다운로드', - filesRename: '이름 바꾸기', - filesDelete: '삭제', - filesDeleteConfirm: '{name}을(를) 삭제할까요? 이 작업은 되돌릴 수 없습니다.', - filesInvalidName: '경로 구분자가 없는 파일 이름을 입력하세요', - filesLoadFailed: '샌드박스 파일을 불러오지 못했습니다', - filesDownloadFailed: '다운로드 실패', - filesUploadComplete: '업로드 완료', - filesUploadFailed: '업로드 실패', - filesRenameFailed: '이름 변경 실패', - filesDeleteFailed: '삭제 실패', - filesPaused: '샌드박스가 일시 중지되었습니다. 이 패널은 과금을 피하기 위해 자동으로 재개하지 않으니, 파일을 보기 전에 터미널에서 시작하세요.', - filesTooLarge: '파일이 16 MiB 제한을 초과합니다', - filesTooMany: '폴더 항목이 너무 많아 나열하거나 삭제할 수 없습니다', + desktopPlaceholder: '데스크톱 시각화는 곧 지원될 예정입니다', notStarted: '터미널이 아직 실행되지 않았습니다. 시작하면 이 대화의 샌드박스에 연결하며, 샌드박스가 없거나 일시 중지된 경우 생성하거나 다시 시작합니다.', paused: '이 대화의 샌드박스가 일시 중지되었습니다. 터미널을 시작하면 다시 시작됩니다.', start: '터미널 시작', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index cfa25e9c..0c90d6b0 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3459,35 +3459,14 @@ export default { panelTitle: 'Песочница', tabArtifacts: 'Файлы', tabTerminal: 'Терминал', - tabFiles: 'Файлы', + tabDesktop: 'Рабочий стол', artifactsEmpty: 'В этом диалоге пока нет созданных файлов', artifactScope: 'Область файлов', artifactsCurrent: 'Этот ответ', artifactsAll: 'Все файлы', artifactsSearch: 'Поиск по имени файла', artifactsNoMatches: 'Нет подходящих файлов', - filesTitle: 'Файлы активной песочницы', - filesBreadcrumbs: 'Текущая папка', - filesRoot: 'Вывод', - filesUpload: 'Загрузить файлы', - filesRefresh: 'Обновить', - filesLoading: 'Загрузка файлов…', - filesEmpty: 'Эта папка пуста', - filesDirectory: 'Папка', - filesDownload: 'Скачать', - filesRename: 'Переименовать', - filesDelete: 'Удалить', - filesDeleteConfirm: 'Удалить {name}? Это действие нельзя отменить.', - filesInvalidName: 'Введите имя файла без разделителей пути', - filesLoadFailed: 'Не удалось загрузить файлы песочницы', - filesDownloadFailed: 'Ошибка скачивания', - filesUploadComplete: 'Загрузка завершена', - filesUploadFailed: 'Ошибка загрузки', - filesRenameFailed: 'Ошибка переименования', - filesDeleteFailed: 'Ошибка удаления', - filesPaused: 'Песочница приостановлена. Запустите её на вкладке «Терминал», прежде чем просматривать файлы — эта панель не возобновляет её автоматически, чтобы не начислять оплату.', - filesTooLarge: 'Файл превышает ограничение 16 МиБ', - filesTooMany: 'В папке слишком много записей для списка или удаления', + desktopPlaceholder: 'Визуализация рабочего стола скоро появится', notStarted: 'Терминал ещё не запущен. Запуск подключит его к песочнице этого диалога, создав или возобновив её при необходимости.', paused: 'Песочница этого диалога приостановлена. Запуск терминала возобновит её.', start: 'Запустить терминал', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 995c5910..9a5c01af 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3461,35 +3461,14 @@ export default { panelTitle: '沙箱可视化', tabArtifacts: '产物', tabTerminal: '终端', - tabFiles: '文件', + tabDesktop: '桌面', artifactsEmpty: '本会话尚未生成可下载的文件', artifactScope: '产物范围', artifactsCurrent: '本轮', artifactsAll: '全部', artifactsSearch: '搜索文件名', artifactsNoMatches: '没有匹配的文件', - filesTitle: '实时沙箱文件', - filesBreadcrumbs: '当前文件夹', - filesRoot: '输出', - filesUpload: '上传文件', - filesRefresh: '刷新', - filesLoading: '正在加载文件…', - filesEmpty: '此文件夹为空', - filesDirectory: '文件夹', - filesDownload: '下载', - filesRename: '重命名', - filesDelete: '删除', - filesDeleteConfirm: '确定删除 {name} 吗?此操作无法撤销。', - filesInvalidName: '请输入不含路径分隔符的文件名', - filesLoadFailed: '无法加载沙箱文件', - filesDownloadFailed: '下载失败', - filesUploadComplete: '上传完成', - filesUploadFailed: '上传失败', - filesRenameFailed: '重命名失败', - filesDeleteFailed: '删除失败', - filesPaused: '沙箱已暂停。请先在终端中启动后再浏览文件,以免自动唤醒产生费用。', - filesTooLarge: '文件超过 16 MiB 限制', - filesTooMany: '目录条目过多,无法列出或删除', + desktopPlaceholder: '桌面可视化即将支持', notStarted: '终端尚未启动。启动后会连接本会话的沙箱环境;若沙箱不存在或已暂停,将为你创建或唤醒它。', paused: '本会话的沙箱已暂停。启动终端会唤醒它。', start: '启动终端', diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.ts index 8cee413a..80660245 100644 --- a/frontend/src/utils/request.ts +++ b/frontend/src/utils/request.ts @@ -177,16 +177,12 @@ instance.interceptors.response.use( // 处理 Nginx 413 Request Entity Too Large const ERR_ENTITY_TOO_LARGE = 413; if (error.response.status === ERR_ENTITY_TOO_LARGE) { - const requestUrl = String(error.config?.url || '') const skillUpload = isSkillBundleUploadUrl(error.config?.url) - const sandboxLiveFile = requestUrl.includes('/sandbox/files') return Promise.reject(withHttpStatus({ status: ERR_ENTITY_TOO_LARGE, message: skillUpload ? i18n.global.t('settings.sandbox.skillBundleTooLarge', { size: MAX_SKILL_BUNDLE_SIZE_MB }) - : sandboxLiveFile - ? i18n.global.t('chat.sandbox.filesTooLarge') - : i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }), + : i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }), success: false }, ERR_ENTITY_TOO_LARGE)); } diff --git a/frontend/src/views/chat/components/SandboxFilesPanel.test.mjs b/frontend/src/views/chat/components/SandboxFilesPanel.test.mjs deleted file mode 100644 index e77bb14d..00000000 --- a/frontend/src/views/chat/components/SandboxFilesPanel.test.mjs +++ /dev/null @@ -1,33 +0,0 @@ -import assert from 'node:assert/strict' -import test from 'node:test' -import { readFileSync } from 'node:fs' - -const panel = readFileSync(new URL('./SandboxFilesPanel.vue', import.meta.url), 'utf8') -const api = readFileSync(new URL('../../../api/chat/sandbox-files.ts', import.meta.url), 'utf8') - -test('live files use one relative-path API for every operation', () => { - assert.match(api, /encodeURIComponent\(sessionId\)/) - assert.match(api, /new URLSearchParams\(\{ path: relativePath \}\)/) - assert.match(api, /form\.append\('path', relativePath\)/) - assert.match(api, /\{ source, target \}/) - assert.doesNotMatch(api, /\/workspace\/output/) -}) - -test('file panel exposes only the scoped browse workflow', () => { - for (const operation of [ - 'listSandboxLiveFiles', - 'downloadSandboxLiveFile', - 'uploadSandboxLiveFile', - 'renameSandboxLiveFile', - 'deleteSandboxLiveFile', - ]) { - assert.match(panel, new RegExp(operation)) - } - assert.match(panel, /entry\.type !== 'other'/) - assert.match(panel, /nextName\.includes\('\/'\)/) - assert.match(panel, /isDirectory\(/) - assert.match(panel, /type === 'dir'/) - assert.match(panel, /MAX_SANDBOX_LIVE_FILE_BYTES/) - assert.match(api, /MAX_SANDBOX_LIVE_FILE_BYTES/) - assert.doesNotMatch(panel, /v-html|\/workspace\/output|desktop|editor/i) -}) diff --git a/frontend/src/views/chat/components/SandboxFilesPanel.vue b/frontend/src/views/chat/components/SandboxFilesPanel.vue deleted file mode 100644 index 78cc6eb0..00000000 --- a/frontend/src/views/chat/components/SandboxFilesPanel.vue +++ /dev/null @@ -1,383 +0,0 @@ - - - - - diff --git a/internal/application/service/sandbox_live_files_service.go b/internal/application/service/sandbox_live_files_service.go deleted file mode 100644 index 187bd488..00000000 --- a/internal/application/service/sandbox_live_files_service.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package service provides browser-safe access to a session sandbox's live output files. -package service - -import ( - "context" - "errors" - - "github.com/Tencent/WeKnora/internal/sandbox" - "github.com/Tencent/WeKnora/internal/types" -) - -// SandboxLiveFilesService resolves the sandbox configuration pinned to a -// session and delegates to its provider-neutral live-file capability. It is -// lookup-only: opening the Files tab never provisions or resumes a sandbox. -type SandboxLiveFilesService struct { - pinner *SessionSandboxPinner - resolver sandbox.TenantSandboxResolver - fallback sandbox.Manager - policy WorkspaceSandboxPolicy -} - -// NewSandboxLiveFilesService wires lookup-only access to pinned session sandboxes. -func NewSandboxLiveFilesService( - pinner *SessionSandboxPinner, - resolver sandbox.TenantSandboxResolver, - fallback sandbox.Manager, - policy WorkspaceSandboxPolicy, -) *SandboxLiveFilesService { - return &SandboxLiveFilesService{ - pinner: pinner, resolver: resolver, fallback: fallback, policy: policy, - } -} - -// List returns one directory level below the fixed output root. -func (s *SandboxLiveFilesService) List( - ctx context.Context, sessionID, relativeDir string, -) ([]sandbox.SessionLiveFileEntry, error) { - manager, err := s.manager(ctx, sessionID) - if err != nil { - return nil, err - } - return manager.ListSessionLiveFiles(ctx, sessionID, relativeDir) -} - -// Read downloads one regular file below the fixed output root. -func (s *SandboxLiveFilesService) Read( - ctx context.Context, sessionID, relativePath string, -) ([]byte, error) { - manager, err := s.manager(ctx, sessionID) - if err != nil { - return nil, err - } - return manager.ReadSessionLiveFile(ctx, sessionID, relativePath) -} - -// Write uploads one new regular file without overwriting an existing entry. -func (s *SandboxLiveFilesService) Write( - ctx context.Context, sessionID, relativePath string, content []byte, -) error { - manager, err := s.manager(ctx, sessionID) - if err != nil { - return err - } - return manager.WriteSessionLiveFile(ctx, sessionID, relativePath, content) -} - -// Rename atomically renames one safe entry without overwriting its target. -func (s *SandboxLiveFilesService) Rename( - ctx context.Context, sessionID, source, target string, -) error { - manager, err := s.manager(ctx, sessionID) - if err != nil { - return err - } - return manager.RenameSessionLiveFile(ctx, sessionID, source, target) -} - -// Remove deletes one safe file or directory tree. -func (s *SandboxLiveFilesService) Remove( - ctx context.Context, sessionID, relativePath string, -) error { - manager, err := s.manager(ctx, sessionID) - if err != nil { - return err - } - return manager.RemoveSessionLiveFile(ctx, sessionID, relativePath) -} - -func (s *SandboxLiveFilesService) manager( - ctx context.Context, sessionID string, -) (sandbox.SessionLiveFileManager, error) { - if s == nil || s.pinner == nil { - return nil, sandbox.ErrNoLiveSessionSandbox - } - configID, err := s.pinner.Read(ctx, sessionID) - if err != nil { - return nil, err - } - if configID == "" { - return nil, sandbox.ErrNoLiveSessionSandbox - } - tenantID, _ := types.TenantIDFromContext(ctx) - mgr, err := resolveTenantSandboxForConfig( - ctx, s.resolver, s.fallback, tenantID, configID, s.policy, - ) - if err != nil { - return nil, err - } - provider, ok := mgr.(sandbox.SessionLiveFileProvider) - if !ok { - return nil, ErrLiveFilesUnsupported - } - files := provider.SessionLiveFileManager() - if files == nil { - return nil, ErrLiveFilesUnsupported - } - return files, nil -} - -// ErrLiveFilesUnsupported means the resolved backend cannot offer safe live-file access. -var ErrLiveFilesUnsupported = errors.New("sandbox live files are unsupported") diff --git a/internal/application/service/sandbox_live_files_service_test.go b/internal/application/service/sandbox_live_files_service_test.go deleted file mode 100644 index 92259799..00000000 --- a/internal/application/service/sandbox_live_files_service_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package service - -import ( - "context" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/Tencent/WeKnora/internal/sandbox" - "github.com/Tencent/WeKnora/internal/types" -) - -type liveFilesManagerStub struct { - pinTestManager - listSession string - listPath string -} - -func (m *liveFilesManagerStub) SessionLiveFileManager() sandbox.SessionLiveFileManager { return m } -func (m *liveFilesManagerStub) ListSessionLiveFiles( - _ context.Context, sessionID, relativeDir string, -) ([]sandbox.SessionLiveFileEntry, error) { - m.listSession, m.listPath = sessionID, relativeDir - return []sandbox.SessionLiveFileEntry{{Name: "result.txt", Path: "result.txt"}}, nil -} - -func (*liveFilesManagerStub) ReadSessionLiveFile(context.Context, string, string) ([]byte, error) { - return nil, nil -} - -func (*liveFilesManagerStub) WriteSessionLiveFile(context.Context, string, string, []byte) error { - return nil -} - -func (*liveFilesManagerStub) RenameSessionLiveFile(context.Context, string, string, string) error { - return nil -} - -func (*liveFilesManagerStub) RemoveSessionLiveFile(context.Context, string, string) error { - return nil -} - -func TestSandboxLiveFilesServiceIsLookupOnlyWhenSessionIsUnpinned(t *testing.T) { - svc := NewSandboxLiveFilesService(NewSessionSandboxPinner(newPinTestDB(t)), nil, nil, nil) - ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) - - _, err := svc.List(ctx, "s-1", "") - require.ErrorIs(t, err, sandbox.ErrNoLiveSessionSandbox) -} - -func TestSandboxLiveFilesServiceFollowsPinnedConfig(t *testing.T) { - pinner := NewSessionSandboxPinner(newPinTestDB(t)) - _, err := pinner.Pin(context.Background(), "s-1", "cfg-docker") - require.NoError(t, err) - - manager := &liveFilesManagerStub{pinTestManager: pinTestManager{typ: sandbox.SandboxTypeDocker}} - svc := NewSandboxLiveFilesService( - pinner, - stubSandboxResolver{mgr: manager}, - nil, - nil, - ) - ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) - - entries, err := svc.List(ctx, "s-1", "reports") - require.NoError(t, err) - require.Len(t, entries, 1) - require.Equal(t, "s-1", manager.listSession) - require.Equal(t, "reports", manager.listPath) -} - -func TestSandboxLiveFilesServiceRejectsManagerWithoutCapability(t *testing.T) { - pinner := NewSessionSandboxPinner(newPinTestDB(t)) - _, err := pinner.Pin(context.Background(), "s-1", "cfg-cube") - require.NoError(t, err) - svc := NewSandboxLiveFilesService( - pinner, - stubSandboxResolver{mgr: &pinTestManager{typ: sandbox.SandboxTypeCube}}, - nil, - nil, - ) - ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) - - _, err = svc.List(ctx, "s-1", "") - require.ErrorIs(t, err, ErrLiveFilesUnsupported) -} diff --git a/internal/container/container.go b/internal/container/container.go index 7dcf30be..dd6e7eee 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -315,9 +315,6 @@ func BuildContainer(container *dig.Container) *dig.Container { // the frontend terminal panel. First-use provisioning takes a sandbox // config ID already resolved by the WebSocket handler (own or shared agent). must(container.Provide(service.NewSandboxTerminalService)) - // SandboxLiveFilesService exposes a symlink-safe browser view rooted at - // /workspace/output on the sandbox already pinned to a session. - must(container.Provide(service.NewSandboxLiveFilesService)) logger.Debugf(ctx, "[Container] Registering task enqueuer...") redisAvailable := os.Getenv("REDIS_ADDR") != "" diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 016f2344..10a13e4a 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -47,10 +47,6 @@ type Handler struct { // selected agent so the sandbox is created with the same config a // conversation turn would use. terminalService *service.SandboxTerminalService - // liveFilesService browses the current session sandbox's fixed - // /workspace/output root. The interface keeps handler authorization tests - // independent from provider setup. - liveFilesService sandboxLiveFilesService } // NewHandler creates a new instance of Handler with all necessary dependencies @@ -77,7 +73,6 @@ func NewHandler( userService interfaces.UserService, memberService interfaces.TenantMemberService, terminalService *service.SandboxTerminalService, - liveFilesService *service.SandboxLiveFilesService, ) *Handler { return &Handler{ sessionService: sessionService, @@ -100,7 +95,6 @@ func NewHandler( userService: userService, memberService: memberService, terminalService: terminalService, - liveFilesService: liveFilesService, attachmentProcessor: NewAttachmentProcessor( fileService, documentReader, diff --git a/internal/handler/session/sandbox_live_files.go b/internal/handler/session/sandbox_live_files.go deleted file mode 100644 index c3a36bf8..00000000 --- a/internal/handler/session/sandbox_live_files.go +++ /dev/null @@ -1,280 +0,0 @@ -package session - -import ( - "context" - stderrors "errors" - "io" - "net/http" - "path" - - "github.com/gin-gonic/gin" - - "github.com/Tencent/WeKnora/internal/application/service" - apperrors "github.com/Tencent/WeKnora/internal/errors" - "github.com/Tencent/WeKnora/internal/logger" - "github.com/Tencent/WeKnora/internal/sandbox" - secutils "github.com/Tencent/WeKnora/internal/utils" -) - -const maxLiveFileUploadRequestBytes = sandbox.MaxSessionLiveFileBytes + (1 << 20) - -type sandboxLiveFilesService interface { - List(context.Context, string, string) ([]sandbox.SessionLiveFileEntry, error) - Read(context.Context, string, string) ([]byte, error) - Write(context.Context, string, string, []byte) error - Rename(context.Context, string, string, string) error - Remove(context.Context, string, string) error -} - -type renameLiveFileRequest struct { - Source string `json:"source" binding:"required"` - Target string `json:"target" binding:"required"` -} - -// ListSandboxLiveFiles godoc -// @Summary 列出会话沙箱 /workspace/output 下一层文件 -// @Description 返回固定输出根下的一层目录条目。路径为相对 POSIX 路径,空路径表示根。不会创建或唤醒已暂停的沙箱。 -// @Tags 会话 -// @Produce json -// @Param id path string true "会话ID" -// @Param path query string false "相对目录,空为输出根" -// @Success 200 {object} map[string]interface{} -// @Failure 400 {object} apperrors.AppError -// @Failure 404 {object} apperrors.AppError -// @Failure 409 {object} apperrors.AppError -// @Security Bearer -// @Router /sessions/{id}/sandbox/files [get] -func (h *Handler) ListSandboxLiveFiles(c *gin.Context) { - sessionID, ok := h.authorizeLiveFilesSession(c, false) - if !ok { - return - } - entries, err := h.liveFilesService.List(c.Request.Context(), sessionID, c.Query("path")) - if err != nil { - h.handleLiveFileError(c, sessionID, err) - return - } - c.JSON(http.StatusOK, gin.H{"success": true, "data": entries}) -} - -// DownloadSandboxLiveFile godoc -// @Summary 下载会话沙箱中的一个输出文件 -// @Description 以附件形式下载 /workspace/output 下的单个常规文件,上限 16 MiB。不会唤醒已暂停的沙箱。 -// @Tags 会话 -// @Produce application/octet-stream -// @Param id path string true "会话ID" -// @Param path query string true "相对文件路径" -// @Success 200 {file} file -// @Failure 400 {object} apperrors.AppError -// @Failure 404 {object} apperrors.AppError -// @Failure 409 {object} apperrors.AppError -// @Failure 413 {object} map[string]interface{} -// @Security Bearer -// @Router /sessions/{id}/sandbox/files/content [get] -func (h *Handler) DownloadSandboxLiveFile(c *gin.Context) { - sessionID, ok := h.authorizeLiveFilesSession(c, false) - if !ok { - return - } - relativePath := c.Query("path") - content, err := h.liveFilesService.Read(c.Request.Context(), sessionID, relativePath) - if err != nil { - h.handleLiveFileError(c, sessionID, err) - return - } - name := path.Base(relativePath) - c.Header("Cache-Control", "private, no-store") - c.Header("X-Content-Type-Options", "nosniff") - c.Header("Content-Disposition", buildAttachmentHeader(name)) - c.Data(http.StatusOK, mimeTypeFor(name), content) -} - -// UploadSandboxLiveFile godoc -// @Summary 上传文件到会话沙箱输出目录 -// @Description 以 multipart 写入一个新文件,不覆盖已有条目。字段 path 为相对路径,file 为文件本体,上限 16 MiB。 -// @Tags 会话 -// @Accept multipart/form-data -// @Produce json -// @Param session_id path string true "会话ID" -// @Param path formData string true "相对目标路径" -// @Param file formData file true "文件内容" -// @Success 201 {object} map[string]interface{} -// @Failure 400 {object} apperrors.AppError -// @Failure 404 {object} apperrors.AppError -// @Failure 409 {object} apperrors.AppError -// @Failure 413 {object} map[string]interface{} -// @Security Bearer -// @Router /sessions/{session_id}/sandbox/files [post] -func (h *Handler) UploadSandboxLiveFile(c *gin.Context) { - sessionID, ok := h.authorizeLiveFilesSession(c, true) - if !ok { - return - } - c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxLiveFileUploadRequestBytes) - if err := c.Request.ParseMultipartForm(maxLiveFileUploadRequestBytes); err != nil { - var maxBytesError *http.MaxBytesError - if stderrors.As(err, &maxBytesError) { - handleLiveFileTooLarge(c) - } else { - _ = c.Error(apperrors.NewBadRequestError("invalid multipart upload")) - } - return - } - if c.Request.MultipartForm != nil { - defer func() { - if err := c.Request.MultipartForm.RemoveAll(); err != nil { - logger.Warnf(c.Request.Context(), - "clean sandbox upload form failed: session=%s err=%v", sessionID, err) - } - }() - } - relativePath := c.PostForm("path") - header, err := c.FormFile("file") - if err != nil { - _ = c.Error(apperrors.NewBadRequestError("file is required")) - return - } - file, err := header.Open() - if err != nil { - _ = c.Error(apperrors.NewBadRequestError("invalid upload")) - return - } - defer func() { - if err := file.Close(); err != nil { - logger.Warnf(c.Request.Context(), - "close sandbox upload failed: session=%s err=%v", sessionID, err) - } - }() - content, err := io.ReadAll(io.LimitReader(file, sandbox.MaxSessionLiveFileBytes+1)) - if err != nil { - _ = c.Error(apperrors.NewBadRequestError("invalid upload")) - return - } - if len(content) > sandbox.MaxSessionLiveFileBytes { - handleLiveFileTooLarge(c) - return - } - if err := h.liveFilesService.Write(c.Request.Context(), sessionID, relativePath, content); err != nil { - h.handleLiveFileError(c, sessionID, err) - return - } - c.JSON(http.StatusCreated, gin.H{"success": true}) -} - -// RenameSandboxLiveFile godoc -// @Summary 重命名会话沙箱输出条目 -// @Description 在 /workspace/output 内原子重命名,目标已存在则冲突。不会覆盖。 -// @Tags 会话 -// @Accept json -// @Produce json -// @Param id path string true "会话ID" -// @Param request body renameLiveFileRequest true "源路径与目标路径" -// @Success 200 {object} map[string]interface{} -// @Failure 400 {object} apperrors.AppError -// @Failure 404 {object} apperrors.AppError -// @Failure 409 {object} apperrors.AppError -// @Security Bearer -// @Router /sessions/{id}/sandbox/files [patch] -func (h *Handler) RenameSandboxLiveFile(c *gin.Context) { - sessionID, ok := h.authorizeLiveFilesSession(c, true) - if !ok { - return - } - var request renameLiveFileRequest - if err := c.ShouldBindJSON(&request); err != nil { - _ = c.Error(apperrors.NewBadRequestError("source and target are required")) - return - } - if err := h.liveFilesService.Rename( - c.Request.Context(), sessionID, request.Source, request.Target, - ); err != nil { - h.handleLiveFileError(c, sessionID, err) - return - } - c.JSON(http.StatusOK, gin.H{"success": true}) -} - -// DeleteSandboxLiveFile godoc -// @Summary 删除会话沙箱输出条目 -// @Description 删除 /workspace/output 下的安全文件或已预校验的目录树。 -// @Tags 会话 -// @Param id path string true "会话ID" -// @Param path query string true "相对路径" -// @Success 204 "No Content" -// @Failure 400 {object} apperrors.AppError -// @Failure 404 {object} apperrors.AppError -// @Failure 409 {object} apperrors.AppError -// @Security Bearer -// @Router /sessions/{id}/sandbox/files [delete] -func (h *Handler) DeleteSandboxLiveFile(c *gin.Context) { - sessionID, ok := h.authorizeLiveFilesSession(c, true) - if !ok { - return - } - if err := h.liveFilesService.Remove(c.Request.Context(), sessionID, c.Query("path")); err != nil { - h.handleLiveFileError(c, sessionID, err) - return - } - c.Status(http.StatusNoContent) -} - -func (h *Handler) authorizeLiveFilesSession(c *gin.Context, mutation bool) (string, bool) { - sessionID := secutils.SanitizeForLog(paramSessionID(c)) - if sessionID == "" { - _ = c.Error(apperrors.NewBadRequestError(apperrors.ErrInvalidSessionID.Error())) - return "", false - } - if h.liveFilesService == nil { - _ = c.Error(apperrors.NewServiceUnavailableError("sandbox files are unavailable")) - return "", false - } - var err error - if mutation { - _, err = h.sessionService.GetOwnedSession(c.Request.Context(), sessionID) - } else { - _, err = h.sessionService.GetSession(c.Request.Context(), sessionID) - } - if err == nil { - return sessionID, true - } - if stderrors.Is(err, apperrors.ErrSessionNotFound) { - _ = c.Error(apperrors.NewNotFoundError("session not found")) - return "", false - } - logger.Errorf(c.Request.Context(), "authorize sandbox files failed: session=%s err=%v", sessionID, err) - _ = c.Error(apperrors.NewInternalServerError("failed to authorize session")) - return "", false -} - -func (h *Handler) handleLiveFileError(c *gin.Context, sessionID string, err error) { - switch { - case stderrors.Is(err, sandbox.ErrLiveFileInvalidPath), stderrors.Is(err, sandbox.ErrLiveFileUnsafe): - _ = c.Error(apperrors.NewBadRequestError("invalid or unsafe file path")) - case stderrors.Is(err, sandbox.ErrLiveFileTooMany): - _ = c.Error(apperrors.NewBadRequestError("directory is too large to list or delete")) - case stderrors.Is(err, sandbox.ErrLiveFileNotFound): - _ = c.Error(apperrors.NewNotFoundError("file not found")) - case stderrors.Is(err, sandbox.ErrLiveFileConflict): - _ = c.Error(apperrors.NewConflictError("destination already exists")) - case stderrors.Is(err, sandbox.ErrLiveFileTooLarge): - handleLiveFileTooLarge(c) - case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox): - _ = c.Error(apperrors.NewConflictError("session has no live sandbox")) - case stderrors.Is(err, sandbox.ErrSandboxPaused): - _ = c.Error(apperrors.NewConflictError("session sandbox is paused")) - case stderrors.Is(err, service.ErrLiveFilesUnsupported): - _ = c.Error(apperrors.NewServiceUnavailableError("sandbox files are unsupported")) - default: - logger.Errorf(c.Request.Context(), "sandbox live-file operation failed: session=%s err=%v", sessionID, err) - _ = c.Error(apperrors.NewInternalServerError("sandbox file operation failed")) - } -} - -func handleLiveFileTooLarge(c *gin.Context) { - c.JSON(http.StatusRequestEntityTooLarge, gin.H{ - "success": false, - "message": "file exceeds the 16 MiB limit", - }) -} - -var _ sandboxLiveFilesService = (*service.SandboxLiveFilesService)(nil) diff --git a/internal/handler/session/sandbox_live_files_test.go b/internal/handler/session/sandbox_live_files_test.go deleted file mode 100644 index 1ac55b0f..00000000 --- a/internal/handler/session/sandbox_live_files_test.go +++ /dev/null @@ -1,339 +0,0 @@ -package session - -import ( - "bytes" - "context" - stderrors "errors" - "io" - "mime/multipart" - "net/http" - "net/http/httptest" - "strings" - "testing" - - apperrors "github.com/Tencent/WeKnora/internal/errors" - "github.com/Tencent/WeKnora/internal/sandbox" - "github.com/Tencent/WeKnora/internal/types" - "github.com/Tencent/WeKnora/internal/types/interfaces" - "github.com/gin-gonic/gin" -) - -type liveFileSessionServiceStub struct { - interfaces.SessionService - getCalls int - getOwnedCalls int - readErr error - writeErr error -} - -func (s *liveFileSessionServiceStub) GetSession(context.Context, string) (*types.Session, error) { - s.getCalls++ - if s.readErr != nil { - return nil, s.readErr - } - return &types.Session{ID: "session-owned"}, nil -} - -func (s *liveFileSessionServiceStub) GetOwnedSession(context.Context, string) (*types.Session, error) { - s.getOwnedCalls++ - if s.writeErr != nil { - return nil, s.writeErr - } - return &types.Session{ID: "session-owned"}, nil -} - -type liveFilesServiceStub struct { - list func(context.Context, string, string) ([]sandbox.SessionLiveFileEntry, error) - read func(context.Context, string, string) ([]byte, error) - write func(context.Context, string, string, []byte) error - rename func(context.Context, string, string, string) error - remove func(context.Context, string, string) error - called bool - session string - path string -} - -func (s *liveFilesServiceStub) List( - ctx context.Context, - sessionID, relativeDir string, -) ([]sandbox.SessionLiveFileEntry, error) { - s.called, s.session, s.path = true, sessionID, relativeDir - if s.list != nil { - return s.list(ctx, sessionID, relativeDir) - } - return nil, nil -} - -func (s *liveFilesServiceStub) Read(ctx context.Context, sessionID, relativePath string) ([]byte, error) { - s.called, s.session, s.path = true, sessionID, relativePath - if s.read != nil { - return s.read(ctx, sessionID, relativePath) - } - return nil, nil -} - -func (s *liveFilesServiceStub) Write(ctx context.Context, sessionID, relativePath string, content []byte) error { - s.called, s.session, s.path = true, sessionID, relativePath - if s.write != nil { - return s.write(ctx, sessionID, relativePath, content) - } - return nil -} - -func (s *liveFilesServiceStub) Rename(ctx context.Context, sessionID, source, target string) error { - s.called, s.session, s.path = true, sessionID, source+"->"+target - if s.rename != nil { - return s.rename(ctx, sessionID, source, target) - } - return nil -} - -func (s *liveFilesServiceStub) Remove(ctx context.Context, sessionID, relativePath string) error { - s.called, s.session, s.path = true, sessionID, relativePath - if s.remove != nil { - return s.remove(ctx, sessionID, relativePath) - } - return nil -} - -func liveFileTestContext( - method, target, sessionID string, - body *bytes.Reader, -) (*gin.Context, *httptest.ResponseRecorder) { - recorder := httptest.NewRecorder() - c, _ := gin.CreateTestContext(recorder) - var requestBody io.Reader - if body != nil { - requestBody = body - } - c.Request = httptest.NewRequest(method, target, requestBody) - c.Params = gin.Params{{Key: "id", Value: sessionID}, {Key: "session_id", Value: sessionID}} - return c, recorder -} - -func TestListSandboxLiveFilesAuthorizesBeforeAccess(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{ - list: func(_ context.Context, _, _ string) ([]sandbox.SessionLiveFileEntry, error) { - return []sandbox.SessionLiveFileEntry{{ - Name: "result.txt", Path: "reports/result.txt", Type: sandbox.SessionLiveFileTypeFile, - }}, nil - }, - } - h := &Handler{sessionService: sessions, liveFilesService: files} - c, recorder := liveFileTestContext(http.MethodGet, "/?path=reports", "session-owned", nil) - - h.ListSandboxLiveFiles(c) - - if len(c.Errors) != 0 || recorder.Code != http.StatusOK { - t.Fatalf("status=%d errors=%v", recorder.Code, c.Errors) - } - if sessions.getCalls != 1 || sessions.getOwnedCalls != 0 || !files.called || files.path != "reports" { - t.Fatalf("unexpected calls: sessions=%+v files=%+v", sessions, files) - } - body := recorder.Body.String() - if !strings.Contains(body, `"path":"reports/result.txt"`) || strings.Contains(body, `"Path"`) { - t.Fatalf("unexpected JSON shape: %s", body) - } -} - -func TestListSandboxLiveFilesSerializesDirectoryType(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{ - list: func(_ context.Context, _, _ string) ([]sandbox.SessionLiveFileEntry, error) { - return []sandbox.SessionLiveFileEntry{{ - Name: "reports", Path: "reports", Type: sandbox.SessionLiveFileTypeDirectory, - }}, nil - }, - } - h := &Handler{sessionService: sessions, liveFilesService: files} - c, recorder := liveFileTestContext(http.MethodGet, "/", "session-owned", nil) - - h.ListSandboxLiveFiles(c) - - if len(c.Errors) != 0 || recorder.Code != http.StatusOK { - t.Fatalf("status=%d errors=%v", recorder.Code, c.Errors) - } - body := recorder.Body.String() - if !strings.Contains(body, `"type":"directory"`) { - t.Fatalf("directory type missing: %s", body) - } - if strings.Contains(body, `"type":"dir"`) { - t.Fatalf("internal dir alias leaked to browser JSON: %s", body) - } -} - -func TestSandboxLiveFilesRejectsNonOwnedSessionBeforeProvider(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{readErr: apperrors.ErrSessionNotFound} - files := &liveFilesServiceStub{} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, _ := liveFileTestContext(http.MethodGet, "/?path=secret.txt", "other-session", nil) - - h.DownloadSandboxLiveFile(c) - - if files.called { - t.Fatal("provider was called before session authorization") - } - if len(c.Errors) != 1 { - t.Fatalf("errors=%v want one authorization error", c.Errors) - } - appErr, ok := c.Errors[0].Err.(*apperrors.AppError) - if !ok || appErr.HTTPCode != http.StatusNotFound { - t.Fatalf("error=%T %v want 404 AppError", c.Errors[0].Err, c.Errors[0].Err) - } -} - -func TestDownloadSandboxLiveFileSetsSafeAttachmentHeaders(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{read: func(context.Context, string, string) ([]byte, error) { - return []byte(""), nil - }} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, recorder := liveFileTestContext( - http.MethodGet, - "/?path=reports/%E7%BB%93%E6%9E%9C.svg", - "session-owned", - nil, - ) - - h.DownloadSandboxLiveFile(c) - - if len(c.Errors) != 0 || recorder.Code != http.StatusOK { - t.Fatalf("status=%d errors=%v", recorder.Code, c.Errors) - } - if got := recorder.Header().Get("Cache-Control"); got != "private, no-store" { - t.Fatalf("Cache-Control=%q", got) - } - if got := recorder.Header().Get("X-Content-Type-Options"); got != "nosniff" { - t.Fatalf("X-Content-Type-Options=%q", got) - } - got := recorder.Header().Get("Content-Disposition") - if !strings.HasPrefix(got, "attachment;") || !strings.Contains(got, "filename*=") { - t.Fatalf("Content-Disposition=%q", got) - } -} - -func TestSandboxLiveFileMutationRejectsReadOnlyAdminFallback(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{writeErr: apperrors.ErrSessionNotFound} - files := &liveFilesServiceStub{} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, _ := liveFileTestContext(http.MethodDelete, "/?path=report.txt", "other-session", nil) - - h.DeleteSandboxLiveFile(c) - - if sessions.getOwnedCalls != 1 || sessions.getCalls != 0 { - t.Fatalf("mutation did not use strict owner lookup: %+v", sessions) - } - if files.called { - t.Fatal("provider was called for a non-owned mutation") - } - if len(c.Errors) != 1 { - t.Fatalf("errors=%v want one authorization error", c.Errors) - } -} - -func TestUploadSandboxLiveFileUsesStrictOwnerCheck(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - var uploaded []byte - files := &liveFilesServiceStub{write: func(_ context.Context, _, _ string, content []byte) error { - uploaded = append([]byte(nil), content...) - return nil - }} - h := &Handler{sessionService: sessions, liveFilesService: files} - - var body bytes.Buffer - writer := multipart.NewWriter(&body) - if err := writer.WriteField("path", "reports/new.txt"); err != nil { - t.Fatal(err) - } - part, err := writer.CreateFormFile("file", "new.txt") - if err != nil { - t.Fatal(err) - } - if _, err := part.Write([]byte("new body")); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - c, recorder := liveFileTestContext(http.MethodPost, "/", "session-owned", bytes.NewReader(body.Bytes())) - c.Request.Header.Set("Content-Type", writer.FormDataContentType()) - - h.UploadSandboxLiveFile(c) - - if len(c.Errors) != 0 || recorder.Code != http.StatusCreated { - t.Fatalf("status=%d errors=%v body=%s", recorder.Code, c.Errors, recorder.Body.String()) - } - if sessions.getOwnedCalls != 1 || sessions.getCalls != 0 { - t.Fatalf("mutation did not use strict ownership: %+v", sessions) - } - if files.path != "reports/new.txt" || string(uploaded) != "new body" { - t.Fatalf("unexpected upload path=%q body=%q", files.path, uploaded) - } -} - -func TestSandboxLiveFilesMapsUnsafePathsWithoutLeakingDetail(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{read: func(context.Context, string, string) ([]byte, error) { - return nil, stderrors.Join(sandbox.ErrLiveFileUnsafe, stderrors.New("/etc/passwd")) - }} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, _ := liveFileTestContext(http.MethodGet, "/?path=link", "session-owned", nil) - - h.DownloadSandboxLiveFile(c) - - if len(c.Errors) != 1 { - t.Fatalf("errors=%v want one path error", c.Errors) - } - appErr, ok := c.Errors[0].Err.(*apperrors.AppError) - if !ok || appErr.HTTPCode != http.StatusBadRequest || strings.Contains(appErr.Message, "/etc") { - t.Fatalf("unsafe error leaked detail: %#v", appErr) - } -} - -func TestSandboxLiveFilesMapsPausedWithoutConnecting(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{list: func(context.Context, string, string) ([]sandbox.SessionLiveFileEntry, error) { - return nil, sandbox.ErrSandboxPaused - }} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, _ := liveFileTestContext(http.MethodGet, "/", "session-owned", nil) - - h.ListSandboxLiveFiles(c) - - if len(c.Errors) != 1 { - t.Fatalf("errors=%v want one paused error", c.Errors) - } - appErr, ok := c.Errors[0].Err.(*apperrors.AppError) - if !ok || appErr.HTTPCode != http.StatusConflict || appErr.Message != "session sandbox is paused" { - t.Fatalf("paused error=%#v", appErr) - } -} - -func TestSandboxLiveFilesMapsTooManyEntries(t *testing.T) { - gin.SetMode(gin.TestMode) - sessions := &liveFileSessionServiceStub{} - files := &liveFilesServiceStub{list: func(context.Context, string, string) ([]sandbox.SessionLiveFileEntry, error) { - return nil, sandbox.ErrLiveFileTooMany - }} - h := &Handler{sessionService: sessions, liveFilesService: files} - c, _ := liveFileTestContext(http.MethodGet, "/", "session-owned", nil) - - h.ListSandboxLiveFiles(c) - - if len(c.Errors) != 1 { - t.Fatalf("errors=%v want one too-many error", c.Errors) - } - appErr, ok := c.Errors[0].Err.(*apperrors.AppError) - if !ok || appErr.HTTPCode != http.StatusBadRequest { - t.Fatalf("too-many error=%#v", appErr) - } -} diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go index 1a907f36..5c604c79 100644 --- a/internal/router/router_api_key_capabilities_test.go +++ b/internal/router/router_api_key_capabilities_test.go @@ -28,11 +28,6 @@ func TestConversationRoutesDeclareChatCapability(t *testing.T) { {http.MethodGet, "/api/v1/sessions/:id/messages/:message_id/suggestions"}, {http.MethodPost, "/api/v1/sessions/:session_id/messages/:message_id/suggestions"}, {http.MethodPost, "/api/v1/sessions/:session_id/suggestion-events"}, - {http.MethodGet, "/api/v1/sessions/:id/sandbox/files"}, - {http.MethodGet, "/api/v1/sessions/:id/sandbox/files/content"}, - {http.MethodPost, "/api/v1/sessions/:session_id/sandbox/files"}, - {http.MethodPatch, "/api/v1/sessions/:id/sandbox/files"}, - {http.MethodDelete, "/api/v1/sessions/:id/sandbox/files"}, {http.MethodPost, "/api/v1/knowledge-chat/:session_id"}, {http.MethodPost, "/api/v1/agent-chat/:session_id"}, {http.MethodGet, "/api/v1/messages/:session_id/load"}, diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.go index 821e85cc..6dbb85ff 100644 --- a/internal/router/routes_chat.go +++ b/internal/router/routes_chat.go @@ -65,11 +65,6 @@ func RegisterSessionRoutes( sessions.DELETE("/:id/attachments/:attachment_id", handler.DeleteTemporaryDocument) sessions.POST("/:session_id/stop", handler.StopSession) sessions.POST("/:session_id/sandbox/terminal-ticket", handler.IssueSandboxTerminalTicket) - sessions.GET("/:id/sandbox/files", handler.ListSandboxLiveFiles) - sessions.GET("/:id/sandbox/files/content", handler.DownloadSandboxLiveFile) - sessions.POST("/:session_id/sandbox/files", handler.UploadSandboxLiveFile) - sessions.PATCH("/:id/sandbox/files", handler.RenameSandboxLiveFile) - sessions.DELETE("/:id/sandbox/files", handler.DeleteSandboxLiveFile) // Mid-run message injection: append a user message to the turn that is // currently generating. Accepts even when no run is live (the client // then falls back to a normal send), mirroring StopSession's ownership diff --git a/internal/sandbox/capabilities.go b/internal/sandbox/capabilities.go index c7415f03..a3aee080 100644 --- a/internal/sandbox/capabilities.go +++ b/internal/sandbox/capabilities.go @@ -91,50 +91,6 @@ type SessionCapabilityProvider interface { SessionFileStore() SessionFileStore } -// SessionLiveFileType is the browser-facing entry kind under /workspace/output. -// It is intentionally distinct from RemoteDirEntryType: the internal remote -// listing uses "dir", while the live-files HTTP/JSON contract uses "directory". -type SessionLiveFileType string - -const ( - // SessionLiveFileTypeFile is a regular file under /workspace/output. - SessionLiveFileTypeFile SessionLiveFileType = "file" - // SessionLiveFileTypeDirectory is a folder the Files tab may open. - SessionLiveFileTypeDirectory SessionLiveFileType = "directory" - // SessionLiveFileTypeOther is a symlink or special node the UI cannot open. - SessionLiveFileTypeOther SessionLiveFileType = "other" -) - -// SessionLiveFileEntry is one browser-safe entry under /workspace/output. -// Path is always relative to that fixed root; provider absolute paths never -// cross the application boundary. -type SessionLiveFileEntry struct { - Name string `json:"name"` - Path string `json:"path"` - Type SessionLiveFileType `json:"type"` - Size int64 `json:"size"` - ModTime time.Time `json:"mod_time"` -} - -// SessionLiveFileManager exposes the small, security-hardened live-files -// surface used by the browser. It is separate from SessionFileStore because -// agent/attachment staging accepts broader absolute workspace paths, whereas -// browser paths are relative to the fixed output root and must never follow a -// symlink. SessionBoundManager implements this once for every remote provider. -type SessionLiveFileManager interface { - ListSessionLiveFiles(ctx context.Context, sessionID, relativeDir string) ([]SessionLiveFileEntry, error) - ReadSessionLiveFile(ctx context.Context, sessionID, relativePath string) ([]byte, error) - WriteSessionLiveFile(ctx context.Context, sessionID, relativePath string, content []byte) error - RenameSessionLiveFile(ctx context.Context, sessionID, source, target string) error - RemoveSessionLiveFile(ctx context.Context, sessionID, relativePath string) error -} - -// SessionLiveFileProvider advertises live-file support without widening the -// long-standing Manager interface or forcing stateless backends to fake it. -type SessionLiveFileProvider interface { - SessionLiveFileManager() SessionLiveFileManager -} - // SessionInstallShellExecutor runs install/maintenance shell commands, which // need the skills image root. It is a separate interface from // SessionShellExecutor so reaching outside /workspace is something a caller diff --git a/internal/sandbox/docker_integration_test.go b/internal/sandbox/docker_integration_test.go index c14a16bf..4fe24bba 100644 --- a/internal/sandbox/docker_integration_test.go +++ b/internal/sandbox/docker_integration_test.go @@ -20,7 +20,6 @@ package sandbox import ( "bytes" "context" - "errors" "fmt" "os" "path" @@ -522,191 +521,6 @@ func TestDockerBackendArtifactBootstrapDoesNotFollowSymlinkIntegration(t *testin } } -func TestDockerSessionLiveFilesIntegration(t *testing.T) { - cfg := dockerIntegrationConfig(t) - manager := newDockerIntegrationManager(t, cfg) - files := manager.SessionLiveFileManager() - if files == nil { - t.Fatal("live-file manager is unavailable on a healthy Docker backend") - } - - ctx, cancel := context.WithTimeout( - types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), - 5*time.Minute, - ) - defer cancel() - - sessionID := fmt.Sprintf("docker-live-files-%d", time.Now().UnixNano()) - t.Cleanup(func() { - cleanupCtx, cleanupCancel := context.WithTimeout( - types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), - time.Minute, - ) - defer cleanupCancel() - _ = manager.DestroySession(cleanupCtx, sessionID) - }) - - if seed := runDockerScript(t, ctx, manager, sessionID, ` -import os -os.makedirs('/workspace/output/reports', exist_ok=True) -print('ready') -`); !seed.IsSuccess() { - t.Fatalf("seed execution failed: %#v", seed) - } - - payload := []byte("Unicode: 你好, WeKnora\n\x00binary\xff") - if err := files.WriteSessionLiveFile(ctx, sessionID, "reports/result.txt", payload); err != nil { - t.Fatalf("WriteSessionLiveFile: %v", err) - } - if err := files.WriteSessionLiveFile(ctx, sessionID, "reports/result.txt", []byte("overwrite")); !errors.Is(err, ErrLiveFileConflict) { - t.Fatalf("upload collision error=%v want ErrLiveFileConflict", err) - } - entries, err := files.ListSessionLiveFiles(ctx, sessionID, "reports") - if err != nil { - t.Fatalf("ListSessionLiveFiles: %v", err) - } - if len(entries) != 1 || entries[0].Path != "reports/result.txt" || entries[0].Type != SessionLiveFileTypeFile { - t.Fatalf("unexpected live-file entries: %#v", entries) - } - rootEntries, err := files.ListSessionLiveFiles(ctx, sessionID, "") - if err != nil { - t.Fatalf("ListSessionLiveFiles root: %v", err) - } - foundDir := false - for _, entry := range rootEntries { - if entry.Path == "reports" && entry.Type == SessionLiveFileTypeDirectory { - foundDir = true - break - } - } - if !foundDir { - t.Fatalf("root listing missing reports directory: %#v", rootEntries) - } - content, err := files.ReadSessionLiveFile(ctx, sessionID, "reports/result.txt") - if err != nil { - t.Fatalf("ReadSessionLiveFile: %v", err) - } - if !bytes.Equal(content, payload) { - t.Fatalf("downloaded content mismatch: got=%q want=%q", content, payload) - } - if err := files.RenameSessionLiveFile(ctx, sessionID, "reports/result.txt", "reports/final.txt"); err != nil { - t.Fatalf("RenameSessionLiveFile: %v", err) - } - if err := files.WriteSessionLiveFile(ctx, sessionID, "reports/existing.txt", []byte("keep")); err != nil { - t.Fatalf("seed rename collision: %v", err) - } - if err := files.RenameSessionLiveFile(ctx, sessionID, "reports/final.txt", "reports/existing.txt"); !errors.Is(err, ErrLiveFileConflict) { - t.Fatalf("rename collision error=%v want ErrLiveFileConflict", err) - } - if _, err := files.ReadSessionLiveFile(ctx, sessionID, "reports/result.txt"); !errors.Is(err, ErrLiveFileNotFound) { - t.Fatalf("renamed source error=%v want ErrLiveFileNotFound", err) - } - if err := files.RemoveSessionLiveFile(ctx, sessionID, "reports/final.txt"); err != nil { - t.Fatalf("RemoveSessionLiveFile: %v", err) - } - if err := files.RemoveSessionLiveFile(ctx, sessionID, "reports/existing.txt"); err != nil { - t.Fatalf("remove existing collision target: %v", err) - } - if err := files.RemoveSessionLiveFile(ctx, sessionID, "reports/missing.txt"); !errors.Is(err, ErrLiveFileNotFound) { - t.Fatalf("remove missing error=%v want ErrLiveFileNotFound", err) - } - if entries, err := files.ListSessionLiveFiles(ctx, sessionID, "reports"); err != nil || len(entries) != 0 { - t.Fatalf("directory after deletes: entries=%#v err=%v", entries, err) - } - - maximum := bytes.Repeat([]byte{0xa5}, MaxSessionLiveFileBytes) - if err := files.WriteSessionLiveFile(ctx, sessionID, "reports/maximum.bin", maximum); err != nil { - t.Fatalf("write maximum-size file: %v", err) - } - maximumRead, err := files.ReadSessionLiveFile(ctx, sessionID, "reports/maximum.bin") - if err != nil || !bytes.Equal(maximumRead, maximum) { - t.Fatalf("maximum-size round trip: bytes=%d err=%v", len(maximumRead), err) - } - if err := files.RemoveSessionLiveFile(ctx, sessionID, "reports/maximum.bin"); err != nil { - t.Fatalf("remove maximum-size file: %v", err) - } - if err := files.WriteSessionLiveFile(ctx, sessionID, "reports/too-large.bin", make([]byte, MaxSessionLiveFileBytes+1)); !errors.Is(err, ErrLiveFileTooLarge) { - t.Fatalf("oversize upload error=%v want ErrLiveFileTooLarge", err) - } - - executor := manager.SessionShellExecutor() - plant, err := executor.ExecShellCommand(ctx, sessionID, ` -ln -s /etc /workspace/output/etc-link -ln -s /etc/passwd /workspace/output/passwd-link -ln /etc/passwd /workspace/output/passwd-hardlink -mkfifo /workspace/output/pipe -mkdir -p /workspace/output/tree -ln -s /etc/passwd /workspace/output/tree/link -`, SessionWorkspaceRoot, 30*time.Second, nil) - if err != nil || !plant.IsSuccess() { - t.Fatalf("plant unsafe nodes: err=%v result=%#v", err, plant) - } - socketPlant, err := executor.ExecShellCommand(ctx, sessionID, - `python3 -c 'import socket; s=socket.socket(socket.AF_UNIX); s.bind("/workspace/output/socket"); s.close()'`, - SessionWorkspaceRoot, 30*time.Second, nil) - if err != nil || !socketPlant.IsSuccess() { - t.Fatalf("plant Unix socket: err=%v result=%#v", err, socketPlant) - } - - unsafeOperations := []struct { - name string - run func() error - }{ - {name: "read final symlink", run: func() error { - _, err := files.ReadSessionLiveFile(ctx, sessionID, "passwd-link") - return err - }}, - {name: "read through intermediate symlink", run: func() error { - _, err := files.ReadSessionLiveFile(ctx, sessionID, "etc-link/passwd") - return err - }}, - {name: "read hardlink outside root", run: func() error { - _, err := files.ReadSessionLiveFile(ctx, sessionID, "passwd-hardlink") - return err - }}, - {name: "write through intermediate symlink", run: func() error { - return files.WriteSessionLiveFile(ctx, sessionID, "etc-link/weknora-escape", []byte("blocked")) - }}, - {name: "rename symlink", run: func() error { - return files.RenameSessionLiveFile(ctx, sessionID, "passwd-link", "moved-link") - }}, - {name: "rename target through symlink", run: func() error { - return files.RenameSessionLiveFile(ctx, sessionID, "pipe", "etc-link/moved") - }}, - {name: "delete special node", run: func() error { - return files.RemoveSessionLiveFile(ctx, sessionID, "pipe") - }}, - {name: "delete socket", run: func() error { - return files.RemoveSessionLiveFile(ctx, sessionID, "socket") - }}, - {name: "delete tree containing symlink", run: func() error { - return files.RemoveSessionLiveFile(ctx, sessionID, "tree") - }}, - } - for _, operation := range unsafeOperations { - t.Run(operation.name, func(t *testing.T) { - if err := operation.run(); !errors.Is(err, ErrLiveFileUnsafe) { - t.Fatalf("error=%v want ErrLiveFileUnsafe", err) - } - }) - } - - otherTenant := types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID+1) - if _, err := files.ListSessionLiveFiles(otherTenant, sessionID, ""); !errors.Is(err, ErrNoLiveSessionSandbox) { - t.Fatalf("cross-tenant lookup error=%v want ErrNoLiveSessionSandbox", err) - } - - rootPlant, err := executor.ExecShellCommand(ctx, sessionID, - "rm -rf /workspace/output && ln -s /etc /workspace/output", - SessionWorkspaceRoot, 30*time.Second, nil) - if err != nil || !rootPlant.IsSuccess() { - t.Fatalf("plant unsafe root: err=%v result=%#v", err, rootPlant) - } - if _, err := files.ListSessionLiveFiles(ctx, sessionID, ""); !errors.Is(err, ErrLiveFileUnsafe) { - t.Fatalf("root symlink lookup error=%v want ErrLiveFileUnsafe", err) - } -} - // stopDockerContainerForTest stops a container behind the adapter's back, the // way a host reboot or an operator with a shell would. func stopDockerContainerForTest(ctx context.Context, id string) error { diff --git a/internal/sandbox/session_live_files.go b/internal/sandbox/session_live_files.go deleted file mode 100644 index 61790fbb..00000000 --- a/internal/sandbox/session_live_files.go +++ /dev/null @@ -1,630 +0,0 @@ -package sandbox - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "path" - "strings" - "time" - "unicode/utf8" -) - -const ( - // MaxSessionLiveFileBytes bounds the decoded file body. The fixed helper - // transports bytes as base64 over the existing exec surface, so an explicit - // cap protects both the Go process and the sandbox helper. - MaxSessionLiveFileBytes = 16 << 20 - maxSessionLivePathBytes = 1024 - // maxSessionLiveListEntries caps one directory listing so a huge output - // tree cannot inflate helper stdout into the API process. - maxSessionLiveListEntries = 1024 - maxSessionLiveTreeDepth = 64 - maxSessionLiveTreeEntries = 8192 - sessionLiveFileTimeout = 45 * time.Second -) - -var ( - // ErrLiveFileInvalidPath means a browser path is not a relative POSIX path. - ErrLiveFileInvalidPath = errors.New("sandbox: invalid live file path") - // ErrLiveFileNotFound means the requested output entry does not exist. - ErrLiveFileNotFound = errors.New("sandbox: live file not found") - // ErrLiveFileConflict means a no-overwrite upload or rename target exists. - ErrLiveFileConflict = errors.New("sandbox: live file already exists") - // ErrLiveFileUnsafe means a path resolves through or names an unsafe node. - ErrLiveFileUnsafe = errors.New("sandbox: unsafe live file node") - // ErrLiveFileTooLarge means a transfer exceeds MaxSessionLiveFileBytes. - ErrLiveFileTooLarge = errors.New("sandbox: live file is too large") - // ErrLiveFileTooMany means a listing or delete tree exceeds the entry/depth cap. - ErrLiveFileTooMany = errors.New("sandbox: live file tree is too large") -) - -type liveFileRequest struct { - Operation string `json:"operation"` - Path string `json:"path,omitempty"` - Source string `json:"source,omitempty"` - Target string `json:"target,omitempty"` - Data string `json:"data,omitempty"` - MaxBytes int `json:"max_bytes"` -} - -type liveFileResponse struct { - OK bool `json:"ok"` - Code string `json:"code,omitempty"` - Message string `json:"message,omitempty"` - Data string `json:"data,omitempty"` - Entries []liveFileResponseEntry `json:"entries,omitempty"` -} - -type liveFileResponseEntry struct { - Name string `json:"name"` - Path string `json:"path"` - Type string `json:"type"` - Size int64 `json:"size"` - ModTimeNS int64 `json:"mod_time_ns"` -} - -// SessionLiveFileManager advertises the shared safe helper on filesystem-capable backends. -func (m *SessionBoundManager) SessionLiveFileManager() SessionLiveFileManager { - if m == nil || m.remoteDisabled() || !m.client.Capabilities().SupportsFilesystemEnumeration { - return nil - } - return m -} - -// ListSessionLiveFiles lists one safe directory level below /workspace/output. -func (m *SessionBoundManager) ListSessionLiveFiles( - ctx context.Context, sessionID, relativeDir string, -) ([]SessionLiveFileEntry, error) { - clean, err := cleanSessionLivePath(relativeDir, true) - if err != nil { - return nil, err - } - response, err := m.runSessionLiveFileOperation(ctx, sessionID, liveFileRequest{ - Operation: "list", - Path: clean, - MaxBytes: MaxSessionLiveFileBytes, - }) - if err != nil { - return nil, err - } - if len(response.Entries) > maxSessionLiveListEntries { - return nil, ErrLiveFileTooMany - } - entries := make([]SessionLiveFileEntry, 0, len(response.Entries)) - for _, entry := range response.Entries { - cleanPath, err := cleanSessionLivePath(entry.Path, false) - if err != nil || cleanPath != entry.Path || entry.Name == "" || - strings.Contains(entry.Name, "/") || path.Base(entry.Path) != entry.Name { - return nil, ErrLiveFileUnsafe - } - entries = append(entries, SessionLiveFileEntry{ - Name: entry.Name, - Path: cleanPath, - Type: liveFileEntryType(entry.Type), - Size: entry.Size, - ModTime: time.Unix(0, entry.ModTimeNS).UTC(), - }) - } - return entries, nil -} - -// ReadSessionLiveFile reads one single-link regular file below /workspace/output. -func (m *SessionBoundManager) ReadSessionLiveFile( - ctx context.Context, sessionID, relativePath string, -) ([]byte, error) { - clean, err := cleanSessionLivePath(relativePath, false) - if err != nil { - return nil, err - } - response, err := m.runSessionLiveFileOperation(ctx, sessionID, liveFileRequest{ - Operation: "read", - Path: clean, - MaxBytes: MaxSessionLiveFileBytes, - }) - if err != nil { - return nil, err - } - content, err := base64.StdEncoding.DecodeString(response.Data) - if err != nil { - return nil, fmt.Errorf("sandbox: decode live file response: %w", err) - } - if len(content) > MaxSessionLiveFileBytes { - return nil, ErrLiveFileTooLarge - } - return content, nil -} - -// WriteSessionLiveFile publishes one new file without replacing an existing entry. -func (m *SessionBoundManager) WriteSessionLiveFile( - ctx context.Context, sessionID, relativePath string, content []byte, -) error { - if len(content) > MaxSessionLiveFileBytes { - return ErrLiveFileTooLarge - } - clean, err := cleanSessionLivePath(relativePath, false) - if err != nil { - return err - } - _, err = m.runSessionLiveFileOperation(ctx, sessionID, liveFileRequest{ - Operation: "write", - Path: clean, - Data: base64.StdEncoding.EncodeToString(content), - MaxBytes: MaxSessionLiveFileBytes, - }) - return err -} - -// RenameSessionLiveFile atomically renames a safe entry without replacement. -func (m *SessionBoundManager) RenameSessionLiveFile( - ctx context.Context, sessionID, source, target string, -) error { - cleanSource, err := cleanSessionLivePath(source, false) - if err != nil { - return err - } - cleanTarget, err := cleanSessionLivePath(target, false) - if err != nil { - return err - } - if cleanSource == cleanTarget { - return nil - } - _, err = m.runSessionLiveFileOperation(ctx, sessionID, liveFileRequest{ - Operation: "rename", - Source: cleanSource, - Target: cleanTarget, - MaxBytes: MaxSessionLiveFileBytes, - }) - return err -} - -// RemoveSessionLiveFile removes a safe entry or prevalidated directory tree. -func (m *SessionBoundManager) RemoveSessionLiveFile( - ctx context.Context, sessionID, relativePath string, -) error { - clean, err := cleanSessionLivePath(relativePath, false) - if err != nil { - return err - } - _, err = m.runSessionLiveFileOperation(ctx, sessionID, liveFileRequest{ - Operation: "remove", - Path: clean, - MaxBytes: MaxSessionLiveFileBytes, - }) - return err -} - -func (m *SessionBoundManager) runSessionLiveFileOperation( - ctx context.Context, sessionID string, request liveFileRequest, -) (*liveFileResponse, error) { - if err := m.requireRemoteBackend(); err != nil { - return nil, err - } - if strings.TrimSpace(sessionID) == "" { - return nil, errors.New("sandbox: session ID is required for live files") - } - // Peek before Connect: Docker/E2B/Cube Connect resumes a paused instance - // and can re-bill. Opening the Files tab is a GET and must not wake it. - state, bound, err := m.peekBoundSandboxState(ctx, sessionID) - if err != nil { - return nil, err - } - if !bound { - return nil, ErrNoLiveSessionSandbox - } - if state != RemoteStateRunning { - return nil, ErrSandboxPaused - } - handle, ok, err := m.lookupSessionHandle(ctx, sessionID) - if err != nil { - return nil, err - } - if !ok { - return nil, ErrNoLiveSessionSandbox - } - payload, err := json.Marshal(request) - if err != nil { - return nil, fmt.Errorf("sandbox: encode live file request: %w", err) - } - result, err := m.client.Exec(ctx, handle, RemoteExecRequest{ - Command: "python3", - Args: []string{"-c", sessionLiveFileHelper}, - Stdin: string(payload), - WorkDir: SessionOutputRoot, - User: DefaultSandboxExecUser, - Timeout: sessionLiveFileTimeout, - }) - if err != nil { - return nil, fmt.Errorf("sandbox: live file operation: %w", err) - } - if result == nil || result.Killed || result.ExitCode != 0 { - message := "helper failed" - if result != nil && strings.TrimSpace(result.Stderr) != "" { - message = strings.TrimSpace(result.Stderr) - } - return nil, fmt.Errorf("sandbox: live file operation: %s", message) - } - response, err := decodeLiveFileResponse(result.Stdout) - if err != nil { - return nil, err - } - if !response.OK { - return nil, liveFileResponseError(response.Code, response.Message) - } - return response, nil -} - -func cleanSessionLivePath(raw string, allowRoot bool) (string, error) { - if !utf8.ValidString(raw) || len(raw) > maxSessionLivePathBytes || strings.ContainsRune(raw, 0) { - return "", ErrLiveFileInvalidPath - } - if raw == "" { - if allowRoot { - return "", nil - } - return "", ErrLiveFileInvalidPath - } - if strings.HasPrefix(raw, "/") || strings.Contains(raw, "\\") { - return "", ErrLiveFileInvalidPath - } - components := strings.Split(raw, "/") - for _, component := range components { - if component == "" || component == "." || component == ".." || strings.TrimSpace(component) == "" { - return "", ErrLiveFileInvalidPath - } - for _, r := range component { - if r < 0x20 || r == 0x7f { - return "", ErrLiveFileInvalidPath - } - } - } - return strings.Join(components, "/"), nil -} - -func decodeLiveFileResponse(stdout string) (*liveFileResponse, error) { - lines := strings.Split(strings.TrimSpace(stdout), "\n") - for i := len(lines) - 1; i >= 0; i-- { - line := strings.TrimSpace(lines[i]) - if !strings.HasPrefix(line, "{") { - continue - } - var response liveFileResponse - if err := json.Unmarshal([]byte(line), &response); err == nil { - return &response, nil - } - } - return nil, errors.New("sandbox: live file helper returned an invalid response") -} - -func liveFileResponseError(code, message string) error { - var sentinel error - switch code { - case "not_found": - sentinel = ErrLiveFileNotFound - case "conflict": - sentinel = ErrLiveFileConflict - case "unsafe": - sentinel = ErrLiveFileUnsafe - case "too_large": - sentinel = ErrLiveFileTooLarge - case "too_many": - sentinel = ErrLiveFileTooMany - case "invalid": - sentinel = ErrLiveFileInvalidPath - default: - return errors.New("sandbox: live file helper failed") - } - if strings.TrimSpace(message) == "" { - return sentinel - } - return fmt.Errorf("%w: %s", sentinel, strings.TrimSpace(message)) -} - -func liveFileEntryType(raw string) SessionLiveFileType { - switch raw { - case "file": - return SessionLiveFileTypeFile - case "directory": - return SessionLiveFileTypeDirectory - default: - return SessionLiveFileTypeOther - } -} - -const sessionLiveFileHelper = ` -import base64 -import ctypes -import errno -import json -import os -import secrets -import stat -import sys - -ROOT = "/workspace/output" -NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) -DIRECTORY = getattr(os, "O_DIRECTORY", 0) -MAX_LIST_ENTRIES = 1024 -MAX_TREE_DEPTH = 64 -MAX_TREE_ENTRIES = 8192 - -class LiveFileError(Exception): - def __init__(self, code, message): - self.code = code - self.message = message - -def fail(code, message): - raise LiveFileError(code, message) - -def parts(relative): - if not isinstance(relative, str): - fail("invalid", "path must be a string") - if relative == "": - return [] - result = relative.split("/") - if any((not part) or part in (".", "..") for part in result): - fail("invalid", "path must be relative POSIX components") - return result - -def open_root(): - if not NOFOLLOW or not DIRECTORY: - fail("unsafe", "sandbox runtime lacks no-follow directory support") - try: - return os.open(ROOT, os.O_RDONLY | DIRECTORY | NOFOLLOW) - except OSError: - fail("unsafe", "output root is unavailable or unsafe") - -def open_parent(root_fd, relative): - components = parts(relative) - if not components: - fail("invalid", "operation requires a non-root path") - current = os.dup(root_fd) - try: - for component in components[:-1]: - next_fd = os.open(component, os.O_RDONLY | DIRECTORY | NOFOLLOW, dir_fd=current) - os.close(current) - current = next_fd - return current, components[-1] - except Exception: - os.close(current) - raise - -def open_directory(root_fd, relative): - components = parts(relative) - current = os.dup(root_fd) - try: - for component in components: - next_fd = os.open(component, os.O_RDONLY | DIRECTORY | NOFOLLOW, dir_fd=current) - os.close(current) - current = next_fd - return current - except Exception: - os.close(current) - raise - -def entry_kind(mode): - if stat.S_ISREG(mode): - return "file" - if stat.S_ISDIR(mode): - return "directory" - return "other" - -def safe_kind(info): - kind = entry_kind(info.st_mode) - if kind == "file" and info.st_nlink != 1: - return "other" - return kind - -def require_safe_entry(parent_fd, name, allow_directory=True): - info = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) - kind = safe_kind(info) - if kind == "other" or (kind == "directory" and not allow_directory): - fail("unsafe", "symlink or special node is not allowed") - return info, kind - -def list_entries(root_fd, relative): - directory_fd = open_directory(root_fd, relative) - try: - result = [] - for name in sorted(os.listdir(directory_fd)): - if len(result) >= MAX_LIST_ENTRIES: - fail("too_many", "directory listing exceeds the live-file entry limit") - info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - rel = name if not relative else relative + "/" + name - result.append({ - "name": name, - "path": rel, - "type": safe_kind(info), - "size": info.st_size, - "mod_time_ns": info.st_mtime_ns, - }) - return result - finally: - os.close(directory_fd) - -def read_file(root_fd, relative, maximum): - parent_fd, name = open_parent(root_fd, relative) - try: - file_fd = os.open(name, os.O_RDONLY | NOFOLLOW, dir_fd=parent_fd) - try: - info = os.fstat(file_fd) - if safe_kind(info) != "file": - fail("unsafe", "only single-link regular files can be downloaded") - if info.st_size > maximum: - fail("too_large", "file exceeds the live-file size limit") - chunks = [] - total = 0 - while True: - chunk = os.read(file_fd, min(65536, maximum + 1 - total)) - if not chunk: - break - chunks.append(chunk) - total += len(chunk) - if total > maximum: - fail("too_large", "file exceeds the live-file size limit") - return base64.b64encode(b"".join(chunks)).decode("ascii") - finally: - os.close(file_fd) - finally: - os.close(parent_fd) - -def write_file(root_fd, relative, encoded, maximum): - try: - content = base64.b64decode(encoded, validate=True) - except Exception: - fail("invalid", "upload body is not valid base64") - if len(content) > maximum: - fail("too_large", "file exceeds the live-file size limit") - parent_fd, name = open_parent(root_fd, relative) - temp_name = ".weknora-upload-" + secrets.token_hex(16) - temp_fd = None - try: - try: - os.stat(name, dir_fd=parent_fd, follow_symlinks=False) - fail("conflict", "destination already exists") - except FileNotFoundError: - pass - temp_fd = os.open(temp_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | NOFOLLOW, 0o600, dir_fd=parent_fd) - view = memoryview(content) - while view: - written = os.write(temp_fd, view) - if written <= 0: - fail("unsafe", "short upload write") - view = view[written:] - os.fsync(temp_fd) - os.close(temp_fd) - temp_fd = None - try: - os.link(temp_name, name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd, follow_symlinks=False) - except FileExistsError: - fail("conflict", "destination already exists") - os.unlink(temp_name, dir_fd=parent_fd) - finally: - if temp_fd is not None: - os.close(temp_fd) - try: - os.unlink(temp_name, dir_fd=parent_fd) - except FileNotFoundError: - pass - os.close(parent_fd) - -def rename_noreplace(root_fd, source, target): - source_fd, source_name = open_parent(root_fd, source) - target_fd, target_name = open_parent(root_fd, target) - try: - require_safe_entry(source_fd, source_name) - try: - os.stat(target_name, dir_fd=target_fd, follow_symlinks=False) - fail("conflict", "destination already exists") - except FileNotFoundError: - pass - libc = ctypes.CDLL(None, use_errno=True) - renameat2 = getattr(libc, "renameat2", None) - if renameat2 is None: - fail("unsafe", "runtime lacks atomic no-replace rename") - renameat2.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] - renameat2.restype = ctypes.c_int - result = renameat2(source_fd, os.fsencode(source_name), target_fd, os.fsencode(target_name), 1) - if result != 0: - value = ctypes.get_errno() - if value == errno.EEXIST: - fail("conflict", "destination already exists") - raise OSError(value, os.strerror(value)) - finally: - os.close(source_fd) - os.close(target_fd) - -def validate_tree(directory_fd, depth=0, remaining=None): - if remaining is None: - remaining = [MAX_TREE_ENTRIES] - if depth > MAX_TREE_DEPTH: - fail("too_many", "directory tree exceeds the live-file depth limit") - for name in os.listdir(directory_fd): - remaining[0] -= 1 - if remaining[0] < 0: - fail("too_many", "directory tree exceeds the live-file entry limit") - info = os.stat(name, dir_fd=directory_fd, follow_symlinks=False) - kind = safe_kind(info) - if kind == "other": - fail("unsafe", "directory contains a symlink or special node") - if kind == "directory": - child_fd = os.open(name, os.O_RDONLY | DIRECTORY | NOFOLLOW, dir_fd=directory_fd) - try: - validate_tree(child_fd, depth + 1, remaining) - finally: - os.close(child_fd) - -def remove_tree(parent_fd, name): - info, kind = require_safe_entry(parent_fd, name) - if kind == "file": - os.unlink(name, dir_fd=parent_fd) - return - directory_fd = os.open(name, os.O_RDONLY | DIRECTORY | NOFOLLOW, dir_fd=parent_fd) - try: - for child in os.listdir(directory_fd): - remove_tree(directory_fd, child) - finally: - os.close(directory_fd) - os.rmdir(name, dir_fd=parent_fd) - -def remove_entry(root_fd, relative): - parent_fd, name = open_parent(root_fd, relative) - try: - info, kind = require_safe_entry(parent_fd, name) - if kind == "directory": - directory_fd = os.open(name, os.O_RDONLY | DIRECTORY | NOFOLLOW, dir_fd=parent_fd) - try: - validate_tree(directory_fd) - finally: - os.close(directory_fd) - remove_tree(parent_fd, name) - finally: - os.close(parent_fd) - -def main(): - request = json.load(sys.stdin) - maximum = int(request.get("max_bytes", 0)) - root_fd = open_root() - try: - operation = request.get("operation") - if operation == "list": - return {"ok": True, "entries": list_entries(root_fd, request.get("path", ""))} - if operation == "read": - return {"ok": True, "data": read_file(root_fd, request.get("path", ""), maximum)} - if operation == "write": - write_file(root_fd, request.get("path", ""), request.get("data", ""), maximum) - return {"ok": True} - if operation == "rename": - rename_noreplace(root_fd, request.get("source", ""), request.get("target", "")) - return {"ok": True} - if operation == "remove": - remove_entry(root_fd, request.get("path", "")) - return {"ok": True} - fail("invalid", "unknown live-file operation") - finally: - os.close(root_fd) - -try: - print(json.dumps(main(), ensure_ascii=False, separators=(",", ":"))) -except LiveFileError as exc: - print(json.dumps({"ok": False, "code": exc.code, "message": exc.message}, separators=(",", ":"))) -except FileNotFoundError: - print(json.dumps({"ok": False, "code": "not_found", "message": "path not found"}, separators=(",", ":"))) -except FileExistsError: - print(json.dumps({"ok": False, "code": "conflict", "message": "destination already exists"}, separators=(",", ":"))) -except (NotADirectoryError, IsADirectoryError): - print(json.dumps({"ok": False, "code": "unsafe", "message": "path type is not allowed"}, separators=(",", ":"))) -except RecursionError: - print(json.dumps( - {"ok": False, "code": "too_many", "message": "directory tree exceeds the live-file depth limit"}, - separators=(",", ":"), - )) -except OSError as exc: - code = "unsafe" if exc.errno in (errno.ELOOP, errno.ENOTDIR, errno.EXDEV) else "internal" - print(json.dumps({"ok": False, "code": code, "message": "filesystem operation failed"}, separators=(",", ":"))) -` - -var _ SessionLiveFileManager = (*SessionBoundManager)(nil) diff --git a/internal/sandbox/session_live_files_test.go b/internal/sandbox/session_live_files_test.go deleted file mode 100644 index 87782d5b..00000000 --- a/internal/sandbox/session_live_files_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package sandbox - -import ( - "errors" - "fmt" - "strings" - "testing" - "time" -) - -func TestCleanSessionLivePath(t *testing.T) { - t.Parallel() - - tests := []struct { - name string - path string - allowRoot bool - want string - wantErr error - }{ - {name: "root", allowRoot: true}, - {name: "file", path: "report.txt", want: "report.txt"}, - {name: "nested", path: "charts/final.png", want: "charts/final.png"}, - {name: "unicode", path: "results/结果.txt", want: "results/结果.txt"}, - {name: "root not allowed", wantErr: ErrLiveFileInvalidPath}, - {name: "absolute", path: "/etc/passwd", wantErr: ErrLiveFileInvalidPath}, - {name: "backslash", path: `charts\final.png`, wantErr: ErrLiveFileInvalidPath}, - {name: "traversal", path: "../secret", wantErr: ErrLiveFileInvalidPath}, - {name: "nested traversal", path: "charts/../../secret", wantErr: ErrLiveFileInvalidPath}, - {name: "dot component", path: "charts/./final.png", wantErr: ErrLiveFileInvalidPath}, - {name: "empty component", path: "charts//final.png", wantErr: ErrLiveFileInvalidPath}, - {name: "trailing slash", path: "charts/", wantErr: ErrLiveFileInvalidPath}, - {name: "blank component", path: "charts/ /final.png", wantErr: ErrLiveFileInvalidPath}, - {name: "control", path: "charts/\nfinal.png", wantErr: ErrLiveFileInvalidPath}, - {name: "nul", path: "charts/\x00final.png", wantErr: ErrLiveFileInvalidPath}, - {name: "invalid utf8", path: string([]byte{0xff}), wantErr: ErrLiveFileInvalidPath}, - {name: "too long", path: strings.Repeat("a", maxSessionLivePathBytes+1), wantErr: ErrLiveFileInvalidPath}, - } - - for _, test := range tests { - test := test - t.Run(test.name, func(t *testing.T) { - t.Parallel() - got, err := cleanSessionLivePath(test.path, test.allowRoot) - if !errors.Is(err, test.wantErr) { - t.Fatalf("cleanSessionLivePath(%q): error=%v want=%v", test.path, err, test.wantErr) - } - if got != test.want { - t.Fatalf("cleanSessionLivePath(%q)=%q want=%q", test.path, got, test.want) - } - }) - } -} - -func TestDecodeLiveFileResponseUsesFinalJSONLine(t *testing.T) { - t.Parallel() - - response, err := decodeLiveFileResponse("shell profile noise\n{\"ok\":true,\"data\":\"YQ==\"}\n") - if err != nil { - t.Fatalf("decodeLiveFileResponse: %v", err) - } - if !response.OK || response.Data != "YQ==" { - t.Fatalf("unexpected response: %#v", response) - } -} - -func TestLiveFileResponseErrorPreservesSentinel(t *testing.T) { - t.Parallel() - - for code, want := range map[string]error{ - "not_found": ErrLiveFileNotFound, - "conflict": ErrLiveFileConflict, - "unsafe": ErrLiveFileUnsafe, - "too_large": ErrLiveFileTooLarge, - "too_many": ErrLiveFileTooMany, - "invalid": ErrLiveFileInvalidPath, - } { - if err := liveFileResponseError(code, "safe detail"); !errors.Is(err, want) { - t.Fatalf("code %q: error=%v want sentinel %v", code, err, want) - } - } -} - -func TestLiveFileEntryTypeUsesBrowserDirectoryContract(t *testing.T) { - t.Parallel() - if liveFileEntryType("directory") != SessionLiveFileTypeDirectory { - t.Fatalf("directory mapped to %q", liveFileEntryType("directory")) - } - if liveFileEntryType("file") != SessionLiveFileTypeFile { - t.Fatalf("file mapped to %q", liveFileEntryType("file")) - } -} - -func TestLiveFileHelperLimitsMatchGoConstants(t *testing.T) { - t.Parallel() - if maxSessionLiveListEntries != 1024 || maxSessionLiveTreeDepth != 64 || maxSessionLiveTreeEntries != 8192 { - t.Fatalf("update helper strings when changing live-file caps") - } - checks := []string{ - fmt.Sprintf("MAX_LIST_ENTRIES = %d", maxSessionLiveListEntries), - fmt.Sprintf("MAX_TREE_DEPTH = %d", maxSessionLiveTreeDepth), - fmt.Sprintf("MAX_TREE_ENTRIES = %d", maxSessionLiveTreeEntries), - } - for _, check := range checks { - if !strings.Contains(sessionLiveFileHelper, check) { - t.Fatalf("helper missing %q", check) - } - } -} - -func TestListSessionLiveFilesRefusesPausedSandboxWithoutConnect(t *testing.T) { - ctx := terminalTestContext() - mgr, client := newSessionManagerTerminalTestHarness(t) - - _, err := mgr.ExecShellCommand(ctx, "sess-1", "true", "", time.Second, nil) - if err != nil { - t.Fatalf("seed sandbox: %v", err) - } - pauseAllFakeSandboxes(t, client.fakeRemoteClient) - connectsBefore := fakeConnectCount(t, client.fakeRemoteClient) - - _, err = mgr.ListSessionLiveFiles(ctx, "sess-1", "") - if !errors.Is(err, ErrSandboxPaused) { - t.Fatalf("error=%v want ErrSandboxPaused", err) - } - if got := fakeConnectCount(t, client.fakeRemoteClient); got != connectsBefore { - t.Fatalf("Connect count %d -> %d; listing must not resume a paused sandbox", connectsBefore, got) - } -}