From f898369a97fd7d97ab54cc536144976a4c5ad77d Mon Sep 17 00:00:00 2001 From: iruzen-dono Date: Sun, 15 Nov 2026 12:41:44 +0000 Subject: [PATCH 1/2] refactor(server): read skill and workspace previews through one function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two functions decided whether a file is text, binary or too large, and returned different shapes for the same answer: `readSkillFile` in a route file returned `kind`, and `WorkspaceService.readFile` returned `state` plus a `previewType` that only ever restated it. `AGENTS.md` asks route handlers to stay thin and call services, which the skill reader did not. `readFilePreview` in `src/server/services/filePreview.ts` is now the only place that classification happens. It takes the caller's size limit, whether an oversized file is refused or truncated, and whether an image is inlined, so the skill page keeps refusing above 100 KB and the Files tab keeps reading the first 1 MB. Both readers delegate and drop their duplicated checks. One result shape, `state: 'text' | 'image' | 'binary' | 'too_large' | 'missing' | 'error'`, reaches the server types, the desktop types (`types/skill.ts`, `api/sessions.ts`, `stores/workspacePanelStore.ts`, `WorkspacePanel.tsx`) and `SkillDetail`. `previewType` is gone: `state === 'image'` says it. The behaviour difference the issue asked to see: a skill file that cannot be read — it vanished between the directory walk and the read — used to throw out of `readSkillFile` and be logged by the caller as a read failure. It is now skipped through the shared `missing` / `error` state, which is the answer the Files tab already gave for the same file. Refs #247 --- desktop/src/__tests__/skillsSettings.test.tsx | 8 +- desktop/src/api/sessions.ts | 5 +- .../components/skills/SkillDetail.test.tsx | 8 +- desktop/src/components/skills/SkillDetail.tsx | 8 +- .../workspace/WorkspacePanel.test.tsx | 6 +- .../components/workspace/WorkspacePanel.tsx | 13 +- .../src/stores/workspacePanelStore.test.ts | 2 +- desktop/src/stores/workspacePanelStore.ts | 4 +- desktop/src/types/skill.ts | 4 +- src/server/__tests__/file-preview.test.ts | 111 +++++++++++++++++ src/server/__tests__/sessions.test.ts | 9 +- src/server/__tests__/skills.test.ts | 10 +- .../__tests__/workspace-service.test.ts | 11 +- src/server/api/skills.ts | 34 ++++-- src/server/services/filePreview.ts | 114 ++++++++++++++++++ src/server/services/workspaceService.ts | 105 ++-------------- 16 files changed, 299 insertions(+), 153 deletions(-) create mode 100644 src/server/__tests__/file-preview.test.ts create mode 100644 src/server/services/filePreview.ts 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..d2cb465f 100644 --- a/desktop/src/components/workspace/WorkspacePanel.test.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.test.tsx @@ -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', diff --git a/desktop/src/components/workspace/WorkspacePanel.tsx b/desktop/src/components/workspace/WorkspacePanel.tsx index c9c18018..f8565b5b 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' || state === 'ok' + 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' || state === 'ok') { 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..d1835d27 100644 --- a/desktop/src/types/skill.ts +++ b/desktop/src/types/skill.ts @@ -21,9 +21,11 @@ export type FileTreeNode = { export type SkillFrontmatter = Record +export type SkillFileState = 'text' | 'image' | 'binary' | 'too_large' + export type SkillFile = { path: string - kind: 'text' | 'image' | 'binary' | 'too_large' + state: SkillFileState content: string language: string frontmatter?: SkillFrontmatter diff --git a/src/server/__tests__/file-preview.test.ts b/src/server/__tests__/file-preview.test.ts new file mode 100644 index 00000000..e29b78c0 --- /dev/null +++ b/src/server/__tests__/file-preview.test.ts @@ -0,0 +1,111 @@ +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('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..0bfe6a4b 100644 --- a/src/server/__tests__/skills.test.ts +++ b/src/server/__tests__/skills.test.ts @@ -219,14 +219,14 @@ 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('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..518fba59 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 @@ -39,7 +39,7 @@ type FileTreeNode = { type SkillFile = { path: string - kind: 'text' | 'image' | 'binary' | 'too_large' + state: FilePreviewState content: string language: string frontmatter?: Record @@ -127,17 +127,23 @@ 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' || preview.state === '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 +187,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) From 6b6be36ae701db0a057e57cb98f3ee511534d999 Mon Sep 17 00:00:00 2001 From: iruzen-dono Date: Sun, 15 Nov 2026 16:06:05 +0000 Subject: [PATCH 2/2] fix(server): log and cover the preview paths the review called out Log an unreadable skill file with its path before skipping it, drop the last 'ok' comparisons from the workspace panel, derive SkillFileState from FilePreviewState on both sides, name the state in the visual refresh document, and cover the exact-limit and error branches. --- .../workspace/WorkspacePanel.test.tsx | 30 +++++++++---------- .../components/workspace/WorkspacePanel.tsx | 6 ++-- desktop/src/types/skill.ts | 4 ++- docs/features/ui-refresh/visual-refresh.zh.md | 2 +- src/server/__tests__/file-preview.test.ts | 21 +++++++++++++ src/server/__tests__/skills.test.ts | 26 +++++++++++++++- src/server/api/skills.ts | 11 +++++-- 7 files changed, 77 insertions(+), 23 deletions(-) diff --git a/desktop/src/components/workspace/WorkspacePanel.test.tsx b/desktop/src/components/workspace/WorkspacePanel.test.tsx index d2cb465f..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, }]), })) @@ -1188,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, }]), })) @@ -1279,7 +1279,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const a = 1\nconst b = 2', - state: 'ok', + state: 'text', size: 24, }]), })) @@ -1342,7 +1342,7 @@ describe('WorkspacePanel', () => { title: 'README.md', language: 'markdown', content: '# Project Notes\n\nShip the release.', - state: 'ok', + state: 'text', size: 34, }]), })) @@ -1400,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' } }, @@ -1425,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' } }, @@ -1764,7 +1764,7 @@ describe('WorkspacePanel', () => { title: 'App.tsx', language: 'tsx', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1802,7 +1802,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1837,7 +1837,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1867,7 +1867,7 @@ describe('WorkspacePanel', () => { title: 'App.ts', language: 'text', content: 'const title = "Todo"\nexport default title', - state: 'ok', + state: 'text', size: 42, }]), })) @@ -1897,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 f8565b5b..f2e73435 100644 --- a/desktop/src/components/workspace/WorkspacePanel.tsx +++ b/desktop/src/components/workspace/WorkspacePanel.tsx @@ -553,7 +553,7 @@ function FileExpandedBody({ const [wrap, setWrap] = useState(true) const state = loading || !entry ? 'loading' : entry.state ?? 'loading' const isDiff = entry?.kind === 'diff' - const isFileContent = state === 'text' || state === 'image' || state === 'ok' + const isFileContent = state === 'text' || state === 'image' const isImage = state === 'image' const isMarkdownFile = isFileContent && !isDiff && !isImage && entry ? isMarkdownPreview(entry) : false const isMarkdown = isMarkdownFile && (showPreview || !fill) @@ -591,7 +591,7 @@ function FileExpandedBody({ className={`${frameClass} bg-background`} /> ) - } else if (state === 'text' || state === 'ok') { + } else if (state === 'text') { content = ( -export type SkillFileState = 'text' | 'image' | 'binary' | 'too_large' +export type SkillFileState = Exclude export type SkillFile = { path: string 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 index e29b78c0..73be0e3f 100644 --- a/src/server/__tests__/file-preview.test.ts +++ b/src/server/__tests__/file-preview.test.ts @@ -81,6 +81,27 @@ describe('readFilePreview', () => { 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-') diff --git a/src/server/__tests__/skills.test.ts b/src/server/__tests__/skills.test.ts index 0bfe6a4b..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' @@ -229,6 +229,30 @@ describe('Skills API', () => { 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 () => { const marketplaceRoot = path.join(tmpHome, 'marketplace-root') const pluginRoot = path.join(marketplaceRoot, 'plugins', 'draw') diff --git a/src/server/api/skills.ts b/src/server/api/skills.ts index 518fba59..dd8110e4 100644 --- a/src/server/api/skills.ts +++ b/src/server/api/skills.ts @@ -37,9 +37,11 @@ type FileTreeNode = { children?: FileTreeNode[] } +type SkillFileState = Exclude + type SkillFile = { path: string - state: FilePreviewState + state: SkillFileState content: string language: string frontmatter?: Record @@ -131,7 +133,12 @@ async function readSkillFile(fullPath: string, relPath: string): Promise