-
+
+
+
{{ 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 @@
-
-
-
-
-
-
- {{ t('chat.sandbox.filesLoading') }}
-
-
-
- {{ errorMessage }}
-
- {{ t('chat.sandbox.retry') }}
-
-
-
-
- {{ t('chat.sandbox.filesEmpty') }}
-
-
-
-
-
-
-
-
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)
- }
-}