diff --git a/desktop/src/__tests__/skillsSettings.test.tsx b/desktop/src/__tests__/skillsSettings.test.tsx index b927e1f6..631b66af 100644 --- a/desktop/src/__tests__/skillsSettings.test.tsx +++ b/desktop/src/__tests__/skillsSettings.test.tsx @@ -211,7 +211,7 @@ describe('Settings > Skills tab', () => { selectedSkill: { meta: useSkillStore.getState().skills[0]!, tree: [{ name: 'SKILL.md', path: 'SKILL.md', type: 'file' }], - files: [{ path: 'SKILL.md', kind: 'text', content: '# Alpha', body: '# Alpha', language: 'markdown', isEntry: true }], + files: [{ path: 'SKILL.md', state: 'text', content: '# Alpha', body: '# Alpha', language: 'markdown', isEntry: true }], skillRoot: '/tmp/alpha', }, }) @@ -278,7 +278,7 @@ describe('Settings > Skills tab', () => { files: [ { path: 'SKILL.md', - kind: 'text', + state: 'text', content: '# Hello\n\nBody content', body: '# Hello\n\nBody content', language: 'markdown', @@ -291,7 +291,7 @@ describe('Settings > Skills tab', () => { }, { path: 'run.ts', - kind: 'text', + state: 'text', content: 'console.log("hello")', language: 'typescript', isEntry: false, @@ -332,7 +332,7 @@ describe('Settings > Skills tab', () => { files: [ { path: 'SKILL.md', - kind: 'text', + state: 'text', content: '# Access', body: '# Access', language: 'markdown', diff --git a/desktop/src/api/sessions.ts b/desktop/src/api/sessions.ts index aa782f57..6492e540 100644 --- a/desktop/src/api/sessions.ts +++ b/desktop/src/api/sessions.ts @@ -242,10 +242,11 @@ export type WorkspaceStatusResult = { error?: string } +export type FilePreviewState = 'text' | 'image' | 'binary' | 'too_large' | 'missing' | 'error' + export type WorkspaceReadFileResult = { - state: 'ok' | 'binary' | 'too_large' | 'missing' | 'error' + state: FilePreviewState path: string - previewType?: 'text' | 'image' content?: string dataUrl?: string mimeType?: string diff --git a/desktop/src/components/skills/SkillDetail.test.tsx b/desktop/src/components/skills/SkillDetail.test.tsx index 517ef205..18cc4edd 100644 --- a/desktop/src/components/skills/SkillDetail.test.tsx +++ b/desktop/src/components/skills/SkillDetail.test.tsx @@ -58,7 +58,7 @@ const SKILL: SkillDetailData = { files: [ { path: 'SKILL.md', - kind: 'text', + state: 'text', content: '---\nname: skill-test\n---\n# Skill Body', body: '# Skill Body', language: 'markdown', @@ -71,7 +71,7 @@ const SKILL: SkillDetailData = { model: 'sonnet', }, }, - { path: 'run.ts', kind: 'text', content: 'console.log("run")', language: 'typescript' }, + { path: 'run.ts', state: 'text', content: 'console.log("run")', language: 'typescript' }, ], skillRoot: '/tmp/skill-test', } @@ -145,8 +145,8 @@ describe('SkillDetail', () => { ], files: [ ...SKILL.files, - { path: 'assets/logo.png', kind: 'image', content: '', language: 'image' }, - { path: 'tool.bin', kind: 'binary', content: '', language: 'binary' }, + { path: 'assets/logo.png', state: 'image', content: '', language: 'image' }, + { path: 'tool.bin', state: 'binary', content: '', language: 'binary' }, ], }, }) diff --git a/desktop/src/components/skills/SkillDetail.tsx b/desktop/src/components/skills/SkillDetail.tsx index 129122f8..c4507f63 100644 --- a/desktop/src/components/skills/SkillDetail.tsx +++ b/desktop/src/components/skills/SkillDetail.tsx @@ -150,7 +150,7 @@ function SkillFileView({ onViewModeChange: (mode: ViewMode) => void }) { const t = useTranslation() - const isMarkdown = file.kind === 'text' && file.language === 'markdown' + const isMarkdown = file.state === 'text' && file.language === 'markdown' const showPreview = isMarkdown && viewMode === 'preview' return ( @@ -182,17 +182,17 @@ function SkillFileView({ function SkillFileBody({ file, skillRoot, showPreview }: { file: SkillFile; skillRoot: string; showPreview: boolean }) { const t = useTranslation() - if (file.kind === 'image') { + if (file.state === 'image') { return (
{file.path}
) } - if (file.kind !== 'text') { + if (file.state !== 'text') { return (
- +
) } diff --git a/desktop/src/components/workspace/WorkspacePanel.test.tsx b/desktop/src/components/workspace/WorkspacePanel.test.tsx index f496e22b..03dd19d6 100644 --- a/desktop/src/components/workspace/WorkspacePanel.test.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.test.tsx @@ -713,7 +713,7 @@ describe('WorkspacePanel', () => { entries: Array<{ name: string; path: string; isDirectory: boolean }> }>() const fileRequest = deferred<{ - state: 'ok' + state: 'text' path: string content: string language: string @@ -782,7 +782,7 @@ describe('WorkspacePanel', () => { }) await act(async () => { fileRequest.resolve({ - state: 'ok', + state: 'text', path: 'src/index.ts', content: 'export const ready = true', language: 'typescript', @@ -979,7 +979,7 @@ describe('WorkspacePanel', () => { }, })) - getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'ok', path: 'src/App.tsx', content: 'export {}', language: 'tsx', size: 9 }) + getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'text', path: 'src/App.tsx', content: 'export {}', language: 'tsx', size: 9 }) const view = await renderPanel('session-narrow') await clickElement(view.getByRole('treeitem', { name: 'src/App.tsx' })) @@ -1002,7 +1002,7 @@ describe('WorkspacePanel', () => { 'session-tree-tab': { '': { state: 'ok', path: '', entries: [{ name: 'App.tsx', path: 'App.tsx', isDirectory: false }] } }, }, })) - getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'ok', path: 'App.tsx', content: 'export {}', language: 'typescript', size: 9 }) + getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'text', path: 'App.tsx', content: 'export {}', language: 'typescript', size: 9 }) const view = await renderPanel('session-tree-tab') await act(() => { @@ -1045,7 +1045,7 @@ describe('WorkspacePanel', () => { title: 'theme.ts', language: 'typescript', content: 'export const theme = "dark"', - state: 'ok', + state: 'text', size: 27, }]), })) @@ -1124,8 +1124,7 @@ describe('WorkspacePanel', () => { title: 'large-file.ts', content: longFile, language: 'typescript', - previewType: 'text', - state: 'ok', + state: 'text', }]), })) @@ -1163,9 +1162,8 @@ describe('WorkspacePanel', () => { })) getMocks().getWorkspaceFileMock.mockResolvedValue({ - state: 'ok', + state: 'image', path: 'logo.png', - previewType: 'image', dataUrl: 'data:image/png;base64,iVBORw0KGgo=', mimeType: 'image/png', language: 'image', @@ -1190,7 +1188,7 @@ describe('WorkspacePanel', () => { title: 'README.md', language: 'markdown', content: '# Project Notes\n\n- **Done** item\n\n```ts\nexport const ok = true\n```', - state: 'ok', + state: 'text', size: 70, }]), })) @@ -1281,7 +1279,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const a = 1\nconst b = 2', - state: 'ok', + state: 'text', size: 24, }]), })) @@ -1344,7 +1342,7 @@ describe('WorkspacePanel', () => { title: 'README.md', language: 'markdown', content: '# Project Notes\n\nShip the release.', - state: 'ok', + state: 'text', size: 34, }]), })) @@ -1402,7 +1400,7 @@ describe('WorkspacePanel', () => { ? { state: 'ok', path, entries: [{ name: 'lib', path: 'src/lib', isDirectory: true }] } : { state: 'ok', path, entries: [{ name: 'a.ts', path: 'src/lib/a.ts', isDirectory: false }] } )) - getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'ok', path: 'src/lib/a.ts', content: 'export {}', language: 'ts', size: 9 }) + getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'text', path: 'src/lib/a.ts', content: 'export {}', language: 'ts', size: 9 }) await setWorkspaceState((state) => ({ ...state, panelByTab: { ...state.panelByTab, 'session-reveal-load': { ...panelState({ id: 'files', kind: 'files' }), selectedFile: 'src/lib/a.ts' } }, @@ -1427,7 +1425,7 @@ describe('WorkspacePanel', () => { it('reveals a path segment in the file tree and opens a terminal in it from its menu', async () => { Object.assign(window, { [ELECTRON_BRIDGE_KEY]: {} }) - getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'ok', path: 'src/index.ts', content: 'export {}', language: 'ts', size: 9 }) + getMocks().getWorkspaceFileMock.mockResolvedValue({ state: 'text', path: 'src/index.ts', content: 'export {}', language: 'ts', size: 9 }) await setWorkspaceState((state) => ({ ...state, panelByTab: { ...state.panelByTab, 'session-crumbs': { ...panelState({ id: 'files', kind: 'files' }), selectedFile: 'src/index.ts' } }, @@ -1766,7 +1764,7 @@ describe('WorkspacePanel', () => { title: 'App.tsx', language: 'tsx', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1804,7 +1802,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1839,7 +1837,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1869,7 +1867,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1899,7 +1897,7 @@ describe('WorkspacePanel', () => { title: 'guide.md', language: 'markdown', content: '# Guide\nAlpha note and Beta note', - state: 'ok', + state: 'text', size: 33, }]), })) diff --git a/desktop/src/components/workspace/WorkspacePanel.tsx b/desktop/src/components/workspace/WorkspacePanel.tsx index c9c18018..f2e73435 100644 --- a/desktop/src/components/workspace/WorkspacePanel.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.tsx @@ -553,14 +553,15 @@ function FileExpandedBody({ const [wrap, setWrap] = useState(true) const state = loading || !entry ? 'loading' : entry.state ?? 'loading' const isDiff = entry?.kind === 'diff' - const isImage = state === 'ok' && entry?.previewType === 'image' - const isMarkdownFile = state === 'ok' && !isDiff && !isImage && entry ? isMarkdownPreview(entry) : false + const isFileContent = state === 'text' || state === 'image' + const isImage = state === 'image' + const isMarkdownFile = isFileContent && !isDiff && !isImage && entry ? isMarkdownPreview(entry) : false const isMarkdown = isMarkdownFile && (showPreview || !fill) - const isCode = state === 'ok' && !isDiff && !isImage && !isMarkdown + const isCode = isFileContent && !isDiff && !isImage && !isMarkdown const isEmptyDiff = state === 'ok' && isDiff && !(entry?.diff ?? '').trim() const frameClass = `overflow-auto ${fill ? 'min-h-0 flex-1' : 'max-h-[420px] rounded-md'}` const codeSurfaceClass = `${frameClass} bg-code` - const contentMenu = fill && path !== null && state === 'ok' ? fileMenu : undefined + const contentMenu = fill && path !== null && isFileContent ? fileMenu : undefined let content: ReactNode if (path === null) { @@ -590,7 +591,7 @@ function FileExpandedBody({ className={`${frameClass} bg-background`} /> ) - } else if (state === 'ok') { + } else if (state === 'text') { content = ( { it('opens a typed address as a project file, or as a web page in the desktop app', async () => { mocks.getWorkspaceFileMock.mockImplementation(async (_sessionId: string, path: string) => ( - path === 'src/a.ts' ? { state: 'ok', path, content: '' } : { state: 'missing', path } + path === 'src/a.ts' ? { state: 'text', path, content: '' } : { state: 'missing', path } )) mocks.submitBrowserInput.mockResolvedValue(undefined) const store = useWorkspacePanelStore.getState() diff --git a/desktop/src/stores/workspacePanelStore.ts b/desktop/src/stores/workspacePanelStore.ts index 0951d9fd..1a7ad789 100644 --- a/desktop/src/stores/workspacePanelStore.ts +++ b/desktop/src/stores/workspacePanelStore.ts @@ -35,7 +35,6 @@ export type WorkspacePreviewEntry = { content?: string dataUrl?: string mimeType?: string - previewType?: 'text' | 'image' diff?: string state?: WorkspacePreviewState error?: string @@ -343,7 +342,7 @@ function resolvePanelTarget( async function isWorkspaceFile(sessionId: string, path: string) { const result = await sessionsApi.getWorkspaceFile(sessionId, path) - return result.state === 'ok' || result.state === 'binary' || result.state === 'too_large' + return result.state === 'text' || result.state === 'image' || result.state === 'binary' || result.state === 'too_large' } export function getShellDisplayName(shell: string | undefined) { @@ -979,7 +978,6 @@ async function loadPreview( content: result.content, dataUrl: result.dataUrl, mimeType: result.mimeType, - previewType: result.previewType ?? 'text', language: result.language, size: result.size, state: result.state, diff --git a/desktop/src/types/skill.ts b/desktop/src/types/skill.ts index f0c6cb6d..642c802f 100644 --- a/desktop/src/types/skill.ts +++ b/desktop/src/types/skill.ts @@ -1,3 +1,5 @@ +import type { FilePreviewState } from '../api/sessions' + export type SkillSource = 'user' | 'claudeCode' | 'project' | 'plugin' | 'mcp' | 'bundled' export type SkillMeta = { @@ -21,9 +23,11 @@ export type FileTreeNode = { export type SkillFrontmatter = Record +export type SkillFileState = Exclude + export type SkillFile = { path: string - kind: 'text' | 'image' | 'binary' | 'too_large' + state: SkillFileState content: string language: string frontmatter?: SkillFrontmatter diff --git a/docs/features/ui-refresh/visual-refresh.zh.md b/docs/features/ui-refresh/visual-refresh.zh.md index 61d8f32f..13713937 100644 --- a/docs/features/ui-refresh/visual-refresh.zh.md +++ b/docs/features/ui-refresh/visual-refresh.zh.md @@ -36,7 +36,7 @@ **服务端。** [openTargetService.ts](../../../src/server/services/openTargetService.ts) 的 `resolveOpenPath` 允许文件:编辑器直接打开文件,文件管理器打开它所在的目录。 -**技能详情页(第二轮)。** [SkillDetail.tsx](../../../desktop/src/components/skills/SkillDetail.tsx) 用 `Tabs` 新增的 `line` 变体做两个标签;[SkillFileTree.tsx](../../../desktop/src/components/skills/SkillFileTree.tsx) 用 `@pierre/trees` 显示文件树,样式与 Files 标签共用 [fileTreeCss.ts](../../../desktop/src/components/shared/fileTreeCss.ts)。设置页的内容区改成纵向弹性布局,详情页铺满剩余高度,「内容」标签的树和预览在面板内滚动,不再让整个设置页滚动。服务端 [skills.ts](../../../src/server/api/skills.ts) 给每个文件标 `kind`(`text`、`image`、`binary`、`too_large`),路径统一用 `/` 分隔;图片不随详情一起返回,选中时由页面通过 `/api/filesystem/file` 加载。图片扩展名到 MIME 类型的对应表只有一份,在 [imageMime.ts](../../../src/server/services/imageMime.ts),技能详情、Files 预览和 `/api/filesystem/file` 共用。 +**技能详情页(第二轮)。** [SkillDetail.tsx](../../../desktop/src/components/skills/SkillDetail.tsx) 用 `Tabs` 新增的 `line` 变体做两个标签;[SkillFileTree.tsx](../../../desktop/src/components/skills/SkillFileTree.tsx) 用 `@pierre/trees` 显示文件树,样式与 Files 标签共用 [fileTreeCss.ts](../../../desktop/src/components/shared/fileTreeCss.ts)。设置页的内容区改成纵向弹性布局,详情页铺满剩余高度,「内容」标签的树和预览在面板内滚动,不再让整个设置页滚动。服务端 [skills.ts](../../../src/server/api/skills.ts) 给每个文件标 `state`(`text`、`image`、`binary`、`too_large`),路径统一用 `/` 分隔;图片不随详情一起返回,选中时由页面通过 `/api/filesystem/file` 加载。图片扩展名到 MIME 类型的对应表只有一份,在 [imageMime.ts](../../../src/server/services/imageMime.ts),技能详情、Files 预览和 `/api/filesystem/file` 共用。 ## 检查 diff --git a/src/server/__tests__/file-preview.test.ts b/src/server/__tests__/file-preview.test.ts new file mode 100644 index 00000000..73be0e3f --- /dev/null +++ b/src/server/__tests__/file-preview.test.ts @@ -0,0 +1,132 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import * as fs from 'node:fs/promises' +import * as os from 'node:os' +import * as path from 'node:path' +import { readFilePreview, type FilePreviewOptions } from '../services/filePreview.js' + +const ONE_KIB = 1024 +const cleanupDirs = new Set() + +async function makeTempDir(prefix: string): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix)) + cleanupDirs.add(dir) + return dir +} + +function options(overrides: Partial = {}): FilePreviewOptions { + return { maxBytes: ONE_KIB, language: 'text', oversize: 'refuse', ...overrides } +} + +afterEach(async () => { + for (const dir of cleanupDirs) { + await fs.rm(dir, { recursive: true, force: true }) + } + cleanupDirs.clear() +}) + +describe('readFilePreview', () => { + it('reads a text file the caller can show', async () => { + const dir = await makeTempDir('file-preview-text-') + const file = path.join(dir, 'note.ts') + const content = 'export const answer = 42\n' + await fs.writeFile(file, content) + + await expect(readFilePreview(file, options({ language: 'typescript' }))).resolves.toEqual({ + state: 'text', + language: 'typescript', + size: content.length, + content, + truncated: false, + readBytes: content.length, + }) + }) + + it('marks a file holding a zero byte as binary', async () => { + const dir = await makeTempDir('file-preview-binary-') + const file = path.join(dir, 'data.bin') + await fs.writeFile(file, Buffer.from([0x41, 0x00, 0x42])) + + await expect(readFilePreview(file, options())).resolves.toMatchObject({ + state: 'binary', + language: 'binary', + size: 3, + }) + }) + + it('refuses an oversized file when the caller refuses it', async () => { + const dir = await makeTempDir('file-preview-refuse-') + const file = path.join(dir, 'big.txt') + await fs.writeFile(file, 'a'.repeat(ONE_KIB + 10)) + + await expect(readFilePreview(file, options())).resolves.toEqual({ + state: 'too_large', + language: 'text', + size: ONE_KIB + 10, + }) + }) + + it('truncates an oversized file when the caller reads a preview', async () => { + const dir = await makeTempDir('file-preview-truncate-') + const file = path.join(dir, 'big.txt') + await fs.writeFile(file, 'a'.repeat(ONE_KIB + 10)) + + const preview = await readFilePreview(file, options({ oversize: 'truncate' })) + + expect(preview).toMatchObject({ + state: 'text', + size: ONE_KIB + 10, + readBytes: ONE_KIB, + truncated: true, + }) + expect(preview.content).toHaveLength(ONE_KIB) + }) + + it('reads a file of exactly the limit, in both modes', async () => { + const dir = await makeTempDir('file-preview-limit-') + const file = path.join(dir, 'exact.txt') + await fs.writeFile(file, 'a'.repeat(ONE_KIB)) + + for (const oversize of ['refuse', 'truncate'] as const) { + const preview = await readFilePreview(file, options({ oversize })) + + expect(preview).toMatchObject({ state: 'text', size: ONE_KIB, readBytes: ONE_KIB, truncated: false }) + } + }) + + it('reports an error it cannot attribute to absence', async () => { + const dir = await makeTempDir('file-preview-error-') + + await expect(readFilePreview(path.join(dir, 'bad\u0000name.ts'), options())).resolves.toMatchObject({ + state: 'error', + size: 0, + }) + }) + + it('reports a missing file instead of throwing', async () => { + const dir = await makeTempDir('file-preview-missing-') + + await expect(readFilePreview(path.join(dir, 'nope.ts'), options())).resolves.toEqual({ + state: 'missing', + language: 'text', + size: 0, + }) + }) + + it('reports an image without reading it, and inlines it only on request', async () => { + const dir = await makeTempDir('file-preview-image-') + const file = path.join(dir, 'pixel.png') + const bytes = Buffer.from('hello', 'utf8') + await fs.writeFile(file, bytes) + + await expect(readFilePreview(file, options())).resolves.toEqual({ + state: 'image', + language: 'image', + size: bytes.length, + mimeType: 'image/png', + }) + await expect(readFilePreview(file, options({ inlineImage: true }))).resolves.toMatchObject({ + state: 'image', + dataUrl: `data:image/png;base64,${bytes.toString('base64')}`, + }) + }) +}) diff --git a/src/server/__tests__/sessions.test.ts b/src/server/__tests__/sessions.test.ts index fb57b33c..cd107f6e 100644 --- a/src/server/__tests__/sessions.test.ts +++ b/src/server/__tests__/sessions.test.ts @@ -2761,7 +2761,7 @@ describe('Sessions API', () => { size: number } expect(fileBody).toMatchObject({ - state: 'ok', + state: 'text', path: 'src/app.ts', language: 'typescript', size: 25, @@ -2895,9 +2895,8 @@ describe('Sessions API', () => { ) expect(fileRes.status).toBe(200) expect(await fileRes.json()).toMatchObject({ - state: 'ok', + state: 'text', path: 'src/app.ts', - previewType: 'text', language: 'typescript', content: 'export const answer = 2\n', }) @@ -2909,14 +2908,12 @@ describe('Sessions API', () => { const imageBody = await imageRes.json() as { state: string path: string - previewType: string mimeType: string dataUrl: string } expect(imageBody).toMatchObject({ - state: 'ok', + state: 'image', path: 'assets/pixel.png', - previewType: 'image', mimeType: 'image/png', }) expect(imageBody.dataUrl).toStartWith('data:image/png;base64,') diff --git a/src/server/__tests__/skills.test.ts b/src/server/__tests__/skills.test.ts index e1b5e5da..6a0233ce 100644 --- a/src/server/__tests__/skills.test.ts +++ b/src/server/__tests__/skills.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it } from 'bun:test' +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test' import * as fs from 'node:fs/promises' import * as os from 'node:os' import * as path from 'node:path' @@ -219,14 +219,38 @@ describe('Skills API', () => { expect(res.status).toBe(200) const body = await res.json() as { - detail: { files: Array<{ path: string; kind: string; content: string; body?: string }> } + detail: { files: Array<{ path: string; state: string; content: string; body?: string }> } } const byPath = new Map(body.detail.files.map((file) => [file.path, file])) - expect(byPath.get('SKILL.md')).toMatchObject({ kind: 'text', content: skillMd, body: 'asset body' }) - expect(byPath.get('assets/logo.png')).toEqual({ path: 'assets/logo.png', kind: 'image', content: '', language: 'image' }) - expect(byPath.get('tool.bin')).toMatchObject({ kind: 'binary', content: '' }) - expect(byPath.get('big.txt')).toMatchObject({ kind: 'too_large', content: '' }) + expect(byPath.get('SKILL.md')).toMatchObject({ state: 'text', content: skillMd, body: 'asset body' }) + expect(byPath.get('assets/logo.png')).toEqual({ path: 'assets/logo.png', state: 'image', content: '', language: 'image' }) + expect(byPath.get('tool.bin')).toMatchObject({ state: 'binary', content: '' }) + expect(byPath.get('big.txt')).toMatchObject({ state: 'too_large', content: '' }) + }) + + it.skipIf(process.platform === 'win32')('skips a skill file it cannot read, and says so', async () => { + const skillsRoot = path.join(tmpHome, '.claude', 'skills') + const skillMd = ['---', 'description: Unreadable asset', '---', '', 'asset body'].join('\n') + await writeSkill(skillsRoot, 'unreadable-skill', skillMd) + const unreadable = path.join(skillsRoot, 'unreadable-skill', 'secret.txt') + await fs.writeFile(unreadable, 'cannot read me') + await fs.chmod(unreadable, 0o000) + + const errorSpy = spyOn(console, 'error') + + try { + const { req, url, segments } = makeRequest('/api/skills/detail?source=user&name=unreadable-skill') + const res = await handleSkillsApi(req, url, segments) + const body = await res.json() as { detail: { files: Array<{ path: string }> } } + + expect(res.status).toBe(200) + expect(body.detail.files.map(file => file.path)).not.toContain('secret.txt') + expect(errorSpy.mock.calls.some(call => String(call[0]).includes('Failed to read skill file'))).toBe(true) + } finally { + errorSpy.mockRestore() + await fs.chmod(unreadable, 0o600) + } }) it('lists plugin skills after reload rereads an external enable toggle', async () => { diff --git a/src/server/__tests__/workspace-service.test.ts b/src/server/__tests__/workspace-service.test.ts index ef1d5c97..103de3b6 100644 --- a/src/server/__tests__/workspace-service.test.ts +++ b/src/server/__tests__/workspace-service.test.ts @@ -359,7 +359,7 @@ describe('WorkspaceService', () => { await fs.mkdir(path.join(workDir, 'folder')) await expect(service.readFile('session-1', 'note.ts')).resolves.toMatchObject({ - state: 'ok', + state: 'text', language: 'typescript', size: 25, content: 'export const answer = 42\n', @@ -370,8 +370,7 @@ describe('WorkspaceService', () => { size: 4, }) await expect(service.readFile('session-1', 'image.png')).resolves.toMatchObject({ - state: 'ok', - previewType: 'image', + state: 'image', language: 'image', mimeType: 'image/png', dataUrl: 'data:image/png;base64,iVBORwA=', @@ -379,16 +378,14 @@ describe('WorkspaceService', () => { }) const largeImage = await service.readFile('session-1', 'large-image.png') expect(largeImage).toMatchObject({ - state: 'ok', - previewType: 'image', + state: 'image', language: 'image', mimeType: 'image/png', size: ONE_MIB + 5, }) expect(largeImage.dataUrl).toStartWith('data:image/png;base64,') await expect(service.readFile('session-1', 'large.txt')).resolves.toMatchObject({ - state: 'ok', - previewType: 'text', + state: 'text', language: 'text', size: ONE_MIB + 1, readBytes: ONE_MIB, diff --git a/src/server/api/skills.ts b/src/server/api/skills.ts index 426ffab4..dd8110e4 100644 --- a/src/server/api/skills.ts +++ b/src/server/api/skills.ts @@ -13,7 +13,7 @@ import { isCommandEnabled } from '../../types/command.js' import { resetSettingsCache } from '../../utils/settings/settingsCache.js' import type { LoadedPlugin } from '../../types/plugin.js' import { ApiError, errorResponse } from '../middleware/errorHandler.js' -import { detectImageMimeType } from '../services/imageMime.js' +import { readFilePreview, type FilePreviewState } from '../services/filePreview.js' type SkillMeta = { name: string @@ -37,9 +37,11 @@ type FileTreeNode = { children?: FileTreeNode[] } +type SkillFileState = Exclude + type SkillFile = { path: string - kind: 'text' | 'image' | 'binary' | 'too_large' + state: SkillFileState content: string language: string frontmatter?: Record @@ -127,17 +129,28 @@ async function loadSkillMeta( } } -async function readSkillFile(fullPath: string, relPath: string): Promise { - if (detectImageMimeType(fullPath)) return { path: relPath, kind: 'image', content: '', language: 'image' } - const { size } = await fs.stat(fullPath) +async function readSkillFile(fullPath: string, relPath: string): Promise { const language = detectLanguage(path.basename(fullPath)) - if (size > MAX_FILE_SIZE) return { path: relPath, kind: 'too_large', content: '', language } - const data = await fs.readFile(fullPath) - if (data.includes(0)) return { path: relPath, kind: 'binary', content: '', language: 'binary' } - const content = data.toString('utf8') - if (relPath !== 'SKILL.md' || language !== 'markdown') return { path: relPath, kind: 'text', content, language } - const { frontmatter, body } = normalizeFrontmatter(content, fullPath) - return { path: relPath, kind: 'text', content, body, frontmatter, language, isEntry: true } + const preview = await readFilePreview(fullPath, { maxBytes: MAX_FILE_SIZE, oversize: 'refuse', language }) + + if (preview.state === 'missing') return null + + if (preview.state === 'error') { + console.error('[Skills] Failed to read skill file:', fullPath, preview.error) + return null + } + + const file: SkillFile = { + path: relPath, + state: preview.state, + content: preview.content ?? '', + language: preview.language, + } + + if (file.state !== 'text' || relPath !== 'SKILL.md' || language !== 'markdown') return file + + const { frontmatter, body } = normalizeFrontmatter(file.content, fullPath) + return { ...file, body, frontmatter, isEntry: true } } async function buildFileTree( @@ -181,7 +194,9 @@ async function buildFileTree( if (node.children!.length === 0) delete node.children } else if (entry.isFile()) { try { - files.push(await readSkillFile(fullPath, relPath)) + const file = await readSkillFile(fullPath, relPath) + if (!file) continue + files.push(file) nodes.push({ name: entry.name, path: relPath, type: 'file' }) fileCount++ } catch (error) { diff --git a/src/server/services/filePreview.ts b/src/server/services/filePreview.ts new file mode 100644 index 00000000..29e784fc --- /dev/null +++ b/src/server/services/filePreview.ts @@ -0,0 +1,114 @@ +import * as fs from 'node:fs/promises' +import { detectImageMimeType } from './imageMime.js' + +export type FilePreviewState = 'text' | 'image' | 'binary' | 'too_large' | 'missing' | 'error' + +export type FilePreviewOversizeMode = 'refuse' | 'truncate' + +export type FilePreviewOptions = { + maxBytes: number + language: string + oversize: FilePreviewOversizeMode + inlineImage?: boolean + describeError?: (error: unknown) => string +} + +export type FilePreview = { + state: FilePreviewState + language: string + size: number + content?: string + dataUrl?: string + mimeType?: string + truncated?: boolean + readBytes?: number + error?: string +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +export async function readFilePreview( + absolutePath: string, + options: FilePreviewOptions, +): Promise { + const { maxBytes, language, oversize, inlineImage = false, describeError } = options + + const fail = (error: unknown, size = 0): FilePreview => ({ + state: 'error', + language, + size, + error: describeError ? describeError(error) : errorMessage(error), + }) + + let stat: Awaited> + try { + stat = await fs.stat(absolutePath) + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === 'ENOENT' || code === 'ENOTDIR') { + return { state: 'missing', language, size: 0 } + } + return fail(error) + } + + if (!stat.isFile()) { + return { state: 'missing', language, size: 0 } + } + + const imageMimeType = detectImageMimeType(absolutePath) + + if (imageMimeType) { + if (!inlineImage) { + return { state: 'image', language: 'image', size: stat.size, mimeType: imageMimeType } + } + try { + const data = await fs.readFile(absolutePath) + return { + state: 'image', + language: 'image', + size: stat.size, + mimeType: imageMimeType, + dataUrl: `data:${imageMimeType};base64,${data.toString('base64')}`, + } + } catch (error) { + return fail(error, stat.size) + } + } + + if (stat.size > maxBytes && oversize === 'refuse') { + return { state: 'too_large', language, size: stat.size } + } + + let data: Buffer + try { + if (stat.size > maxBytes) { + const fileHandle = await fs.open(absolutePath, 'r') + try { + const previewBuffer = Buffer.alloc(maxBytes) + const { bytesRead } = await fileHandle.read(previewBuffer, 0, maxBytes, 0) + data = previewBuffer.subarray(0, bytesRead) + } finally { + await fileHandle.close() + } + } else { + data = await fs.readFile(absolutePath) + } + } catch (error) { + return fail(error, stat.size) + } + + if (data.includes(0)) { + return { state: 'binary', language: 'binary', size: stat.size } + } + + return { + state: 'text', + language, + size: stat.size, + content: data.toString('utf8'), + truncated: data.length < stat.size, + readBytes: data.length, + } +} diff --git a/src/server/services/workspaceService.ts b/src/server/services/workspaceService.ts index 16b4258c..17cd81fa 100644 --- a/src/server/services/workspaceService.ts +++ b/src/server/services/workspaceService.ts @@ -6,7 +6,7 @@ import { diffLines } from 'diff' import type { MessageEntry } from '../transcript/entries.js' import type { FileHistorySnapshot } from '../../utils/fileHistory.js' import { getClaudeConfigHomeDir } from '../../utils/envUtils.js' -import { detectImageMimeType } from './imageMime.js' +import { readFilePreview, type FilePreview } from './filePreview.js' import { isSameOrInsidePathForPlatform, normalizeDriveRootPathForPlatform, @@ -74,18 +74,8 @@ export type WorkspaceStatusResult = { error?: string } -export type WorkspaceReadFileResult = { - state: 'ok' | 'binary' | 'too_large' | 'missing' | 'error' +export type WorkspaceReadFileResult = FilePreview & { path: string - previewType?: 'text' | 'image' - content?: string - dataUrl?: string - mimeType?: string - language: string - size: number - truncated?: boolean - readBytes?: number - error?: string } export type WorkspaceTreeEntry = { @@ -393,87 +383,16 @@ export class WorkspaceService { filePath: string, ): Promise { const resolvedPath = await this.resolveWorkspacePath(sessionId, filePath) + const preview = await readFilePreview(resolvedPath.absolutePath, { + maxBytes: MAX_PREVIEW_BYTES, + oversize: 'truncate', + language: this.detectLanguage(resolvedPath.absolutePath), + inlineImage: true, + describeError: (error) => + this.formatFsError('Failed to read workspace file', resolvedPath.absolutePath, error), + }) - const stat = await this.safeStat(resolvedPath.absolutePath) - if (stat.kind === 'error') { - return { - state: 'error', - path: resolvedPath.relativePath, - language: this.detectLanguage(resolvedPath.absolutePath), - size: 0, - error: stat.message, - } - } - if (stat.kind === 'missing' || !stat.stat.isFile()) { - return { - state: 'missing', - path: resolvedPath.relativePath, - language: this.detectLanguage(resolvedPath.absolutePath), - size: 0, - } - } - - const language = this.detectLanguage(resolvedPath.absolutePath) - const imageMimeType = detectImageMimeType(resolvedPath.absolutePath) - - let content: Buffer - try { - if (!imageMimeType && stat.stat.size > MAX_PREVIEW_BYTES) { - const fileHandle = await fs.open(resolvedPath.absolutePath, 'r') - try { - const previewBuffer = Buffer.alloc(MAX_PREVIEW_BYTES) - const { bytesRead } = await fileHandle.read(previewBuffer, 0, MAX_PREVIEW_BYTES, 0) - content = previewBuffer.subarray(0, bytesRead) - } finally { - await fileHandle.close() - } - } else { - content = await fs.readFile(resolvedPath.absolutePath) - } - } catch (error) { - return { - state: 'error', - path: resolvedPath.relativePath, - language, - size: stat.stat.size, - error: this.formatFsError( - 'Failed to read workspace file', - resolvedPath.absolutePath, - error, - ), - } - } - if (imageMimeType) { - return { - state: 'ok', - path: resolvedPath.relativePath, - previewType: 'image', - dataUrl: `data:${imageMimeType};base64,${content.toString('base64')}`, - mimeType: imageMimeType, - language: 'image', - size: stat.stat.size, - } - } - - if (content.includes(0)) { - return { - state: 'binary', - path: resolvedPath.relativePath, - language: 'binary', - size: stat.stat.size, - } - } - - return { - state: 'ok', - path: resolvedPath.relativePath, - previewType: 'text', - content: content.toString('utf8'), - language, - size: stat.stat.size, - truncated: content.length < stat.stat.size, - readBytes: content.length, - } + return { ...preview, path: resolvedPath.relativePath } } async readTree( @@ -650,7 +569,7 @@ export class WorkspaceService { if (change.diff?.trim()) return change.diff const file = await this.readFile(sessionId, relativePath) - if (file.state !== 'ok' || file.previewType === 'image' || typeof file.content !== 'string') { + if (file.state !== 'text' || typeof file.content !== 'string') { return null } return this.buildSyntheticDiff('/dev/null', relativePath, '', file.content)