diff --git a/ui-packages/web/src/core/agent/reader-message.ts b/ui-packages/web/src/core/agent/reader-message.ts index 944da0c..f0c9127 100644 --- a/ui-packages/web/src/core/agent/reader-message.ts +++ b/ui-packages/web/src/core/agent/reader-message.ts @@ -2,10 +2,11 @@ import type { UserMessage } from '@earendil-works/pi-ai' import { nanoid } from 'nanoid' import type { PreviewKind, StoredFileMetadata } from '../files' +// Saved with the conversation, so the name stays what the reader saw when they attached it. export type ConversationAttachment = Pick< StoredFileMetadata, - 'id' | 'name' | 'mediaType' | 'previewKind' | 'size' -> + 'id' | 'mediaType' | 'previewKind' | 'size' +> & { name: string } export type ReaderUserMessage = UserMessage & { reader: { @@ -31,7 +32,8 @@ export const createReaderUserMessage = ( const request = text || 'Review the attached workspace files.' const metadata = attachments.map(attachment => ({ fileId: attachment.id, - name: attachment.name, + // Attachments are always stored at the library root, so the name they keep is their path. + path: attachment.name, type: attachment.previewKind, recommendedTool: recommendedTool(attachment.previewKind), })) diff --git a/ui-packages/web/src/core/document-text.test.tsx b/ui-packages/web/src/core/document-text.test.tsx index 6916f89..90fd255 100644 --- a/ui-packages/web/src/core/document-text.test.tsx +++ b/ui-packages/web/src/core/document-text.test.tsx @@ -9,6 +9,7 @@ import { createLocalTools } from '../features/agent/local-tools' import { createPdfRuntime } from '../features/agent/pdf/runtime' import { readViewport } from '../features/reader/reader-viewport' import { findTextMatches, markdownText, normalizeSearchText } from './document-text' +import { rootSources } from './files' describe('searchable document text', () => { it.each([ @@ -77,7 +78,10 @@ describe('formula and diagram source context', () => { it('resolves viewport formula anchors through the public search and read tools', async () => { const source = 'Before $x^2$ after.\n\n$$\\frac{a}{b}$$' - const imported = await importStoredFiles([new File([source], 'formulas.md')], 'keep') + const imported = await importStoredFiles( + rootSources([new File([source], 'formulas.md')]), + 'keep', + ) const fileId = imported.addedIds[0] if (!fileId) throw new Error('Missing imported fixture') const { container } = render() @@ -92,8 +96,8 @@ describe('formula and diagram source context', () => { }) const tools = createLocalTools( () => ({ - openFiles: [{ id: fileId, name: 'formulas.md', type: 'markdown' }], - activeFile: { id: fileId, name: 'formulas.md', type: 'markdown' }, + openFiles: [{ id: fileId, path: 'formulas.md', type: 'markdown' }], + activeFile: { id: fileId, path: 'formulas.md', type: 'markdown' }, viewport: readViewport(container, container), }), writeStoredTextFile, diff --git a/ui-packages/web/src/core/file-export.test.ts b/ui-packages/web/src/core/file-export.test.ts index 8f39893..674298d 100644 --- a/ui-packages/web/src/core/file-export.test.ts +++ b/ui-packages/web/src/core/file-export.test.ts @@ -2,9 +2,9 @@ import { describe, expect, it, vi } from 'vitest' import { findDirectoryConflicts, saveBlobAs, writeBlobToDirectory } from './file-export' import type { StoredFileMetadata } from './files' -const metadata = (id: string, name: string): StoredFileMetadata => ({ +const metadata = (id: string, path: string): StoredFileMetadata => ({ id, - name, + path, collection: 'files', mediaType: 'text/plain', previewKind: 'text', @@ -24,7 +24,60 @@ const writableFile = (write: (data: Blob) => void): FileSystemFileHandle => }) as unknown as FileSystemWritableFileStream, }) as FileSystemFileHandle +type FakeFolder = Map + +// Behaves like a real directory handle: folders and files share names, and nothing appears +// unless asked to be created. +const fakeDirectory = (folder: FakeFolder): FileSystemDirectoryHandle => + ({ + getDirectoryHandle: async (name: string, options?: { create?: boolean }) => { + const entry = folder.get(name) + if (entry instanceof Map) return fakeDirectory(entry) + if (entry) throw new DOMException('A file is in the way', 'TypeMismatchError') + if (!options?.create) throw new DOMException('Missing', 'NotFoundError') + const created: FakeFolder = new Map() + folder.set(name, created) + return fakeDirectory(created) + }, + getFileHandle: async (name: string, options?: { create?: boolean }) => { + const entry = folder.get(name) + if (entry instanceof Map) + throw new DOMException('A folder is in the way', 'TypeMismatchError') + if (!entry && !options?.create) throw new DOMException('Missing', 'NotFoundError') + return writableFile(data => folder.set(name, data)) + }, + }) as unknown as FileSystemDirectoryHandle + describe('browser file export', () => { + it('creates the folders of a path when writing a file', async () => { + const root: FakeFolder = new Map() + const blob = new Blob(['nested']) + + await writeBlobToDirectory(fakeDirectory(root), 'docs/v1.2/Notes.md', blob) + + const docs = root.get('docs') + const version = docs instanceof Map ? docs.get('v1.2') : undefined + expect(version instanceof Map ? version.get('Notes.md') : undefined).toBe(blob) + }) + + it('reports a path as a conflict when a file stands where one of its folders would go', async () => { + const notes: FakeFolder = new Map([['a.md', new Blob(['existing'])]]) + const root: FakeFolder = new Map([ + ['docs', new Blob(['a file named docs'])], + ['notes', notes], + ]) + const files = [ + metadata('blocked', 'docs/a.md'), + metadata('existing', 'notes/a.md'), + metadata('new', 'missing/b.md'), + ] + + await expect(findDirectoryConflicts(fakeDirectory(root), files, [])).resolves.toEqual([ + 'docs/a.md', + 'notes/a.md', + ]) + }) + it('ignores managed files and reports new name conflicts before writing', async () => { const files = [metadata('managed', 'Managed.md'), metadata('new', 'Existing.md')] const directory = { @@ -36,7 +89,7 @@ describe('browser file export', () => { await expect( findDirectoryConflicts(directory, files, [ - { id: 'managed', name: 'Managed.md', revision: 1 }, + { id: 'managed', path: 'Managed.md', revision: 1 }, ]), ).resolves.toEqual(['Existing.md']) expect(directory.getFileHandle).toHaveBeenCalledOnce() diff --git a/ui-packages/web/src/core/file-export.ts b/ui-packages/web/src/core/file-export.ts index c272ae4..e572ca2 100644 --- a/ui-packages/web/src/core/file-export.ts +++ b/ui-packages/web/src/core/file-export.ts @@ -1,4 +1,4 @@ -import type { StoredFileMetadata } from './files' +import { baseName, type StoredFileMetadata } from './files' type FileSystemPermissionMode = 'read' | 'readwrite' type FileSystemPermissionState = 'denied' | 'granted' | 'prompt' @@ -22,7 +22,7 @@ type FilePickerWindow = Window & { showSaveFilePicker?: (options?: SaveFilePickerOptions) => Promise } -export type ExportedFileVersion = Pick +export type ExportedFileVersion = Pick export type FolderExportRecord = { id: 'files' @@ -50,9 +50,15 @@ export const ensureDirectoryWritePermission = async (directory: WritableDirector : false } -const directoryContains = async (directory: FileSystemDirectoryHandle, name: string) => { +const folderSegments = (path: string) => path.split('/').slice(0, -1) + +// Something already standing on the path counts, whether it is the file itself or a file where +// one of its folders would go. +const directoryContains = async (directory: FileSystemDirectoryHandle, path: string) => { try { - await directory.getFileHandle(name) + let folder = directory + for (const segment of folderSegments(path)) folder = await folder.getDirectoryHandle(segment) + await folder.getFileHandle(baseName(path)) return true } catch (error) { if (error instanceof DOMException && error.name === 'NotFoundError') return false @@ -66,11 +72,11 @@ export const findDirectoryConflicts = async ( files: readonly StoredFileMetadata[], savedFiles: readonly ExportedFileVersion[], ) => { - const managed = new Set(savedFiles.map(file => `${file.id}\0${file.name}`)) + const managed = new Set(savedFiles.map(file => `${file.id}\0${file.path}`)) const conflicts: string[] = [] for (const file of files) { - if (managed.has(`${file.id}\0${file.name}`)) continue - if (await directoryContains(directory, file.name)) conflicts.push(file.name) + if (managed.has(`${file.id}\0${file.path}`)) continue + if (await directoryContains(directory, file.path)) conflicts.push(file.path) } return conflicts } @@ -92,9 +98,14 @@ const writeBlob = async (handle: FileSystemFileHandle, blob: Blob) => { export const writeBlobToDirectory = async ( directory: FileSystemDirectoryHandle, - name: string, + path: string, blob: Blob, -) => writeBlob(await directory.getFileHandle(name, { create: true }), blob) +) => { + let folder = directory + for (const segment of folderSegments(path)) + folder = await folder.getDirectoryHandle(segment, { create: true }) + await writeBlob(await folder.getFileHandle(baseName(path), { create: true }), blob) +} const downloadBlob = (name: string, blob: Blob) => { const url = URL.createObjectURL(blob) diff --git a/ui-packages/web/src/core/files.ts b/ui-packages/web/src/core/files.ts index cfcaa9a..97642bb 100644 --- a/ui-packages/web/src/core/files.ts +++ b/ui-packages/web/src/core/files.ts @@ -15,7 +15,7 @@ export type FileCollection = 'files' | 'attachments' export type StoredFileMetadata = { id: string - name: string + path: string collection?: FileCollection mediaType: string previewKind: PreviewKind @@ -27,7 +27,14 @@ export type StoredFileMetadata = { export type StoredFileContent = { id: string; blob: Blob } -export type ImportRejectionReason = 'file-too-large' | 'library-full' | 'storage-unavailable' +export type ImportRejectionReason = + | 'file-too-large' + | 'library-full' + | 'storage-unavailable' + | 'invalid-path' + | 'path-conflict' + +export type ImportSource = { path: string; file: File } export type ImportedFile = { sourceIndex: number @@ -39,7 +46,7 @@ export type ImportResult = { addedIds: string[] replacedIds: string[] imported: ImportedFile[] - rejected: Array<{ sourceIndex: number; name: string; reason: ImportRejectionReason }> + rejected: Array<{ sourceIndex: number; path: string; reason: ImportRejectionReason }> } const extensionOf = (name: string) => name.toLowerCase().match(/\.([^.]+)$/)?.[1] ?? '' @@ -88,12 +95,38 @@ export const formatBytes = (bytes: number) => { return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB` } -export const duplicateNames = (files: readonly File[], existing: readonly StoredFileMetadata[]) => { - const names = new Set(existing.map(file => file.name.toLowerCase())) - return files.reduce((duplicates, file) => { - const normalized = file.name.toLowerCase() - if (names.has(normalized) && !duplicates.includes(file.name)) duplicates.push(file.name) - names.add(normalized) +const maximumPathLength = 1024 + +export const containsControlCharacter = (value: string) => + Array.from(value).some(character => { + const codePoint = character.codePointAt(0) + return codePoint !== undefined && (codePoint < 32 || codePoint === 127) + }) + +// A path is relative and every '/'-separated segment names something. Any character a file +// name may hold is allowed, so files imported from disk keep their names. Paths are checked and +// never rewritten, so every caller agrees on which file a path means. +export const isWorkspacePath = (path: string) => + path.length > 0 && + path.length <= maximumPathLength && + !path.startsWith('/') && + path.split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..') + +export const baseName = (path: string) => path.slice(path.lastIndexOf('/') + 1) + +// Files chosen or dropped one by one land in the library root under their own names. +export const rootSources = (files: readonly File[]): ImportSource[] => + files.map(file => ({ path: file.name, file })) + +export const duplicatePaths = ( + sources: readonly ImportSource[], + existing: readonly StoredFileMetadata[], +) => { + const paths = new Set(existing.map(file => file.path.toLowerCase())) + return sources.reduce((duplicates, { path }) => { + const normalized = path.toLowerCase() + if (paths.has(normalized) && !duplicates.includes(path)) duplicates.push(path) + paths.add(normalized) return duplicates }, []) } diff --git a/ui-packages/web/src/core/reader-state.ts b/ui-packages/web/src/core/reader-state.ts index 993fb75..5f15d70 100644 --- a/ui-packages/web/src/core/reader-state.ts +++ b/ui-packages/web/src/core/reader-state.ts @@ -1,7 +1,7 @@ import type { PreviewKind } from './files' // The format travels with the reference so the assistant knows which tools fit the open file. -export type FileRef = { id: string; name: string; type: PreviewKind } +export type FileRef = { id: string; path: string; type: PreviewKind } export type ReaderState = { openFiles: FileRef[] activeFile: (FileRef & { pageNumber?: number; source?: { dirty: boolean } }) | null diff --git a/ui-packages/web/src/data/conversation-store.test.ts b/ui-packages/web/src/data/conversation-store.test.ts index 91e3f1d..66216f0 100644 --- a/ui-packages/web/src/data/conversation-store.test.ts +++ b/ui-packages/web/src/data/conversation-store.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { createReaderUserMessage } from '../core/agent/reader-message' import { emptyConversationDraft, type StoredConversation } from '../core/conversations' +import { rootSources } from '../core/files' import { appendStoredConversationMessages, getStoredConversation, @@ -25,7 +26,7 @@ const conversation = ( describe('conversation store', () => { it('stores drafts and ordered Pi messages, then deletes only the conversation', async () => { const imported = await importStoredFiles( - [new File(['shared'], 'Shared.md', { type: 'text/markdown' })], + rootSources([new File(['shared'], 'Shared.md', { type: 'text/markdown' })]), 'keep', ) const stored = { @@ -59,7 +60,7 @@ describe('conversation store', () => { await removeStoredConversation(stored.id) expect(await getStoredConversation(stored.id)).toBeNull() - expect((await listStoredFiles()).some(file => file.name === 'Shared.md')).toBe(true) + expect((await listStoredFiles()).some(file => file.path === 'Shared.md')).toBe(true) }) it('pages by activity and id without duplicates when timestamps match', async () => { diff --git a/ui-packages/web/src/data/file-store.test.ts b/ui-packages/web/src/data/file-store.test.ts index 3d87da4..d94f5ed 100644 --- a/ui-packages/web/src/data/file-store.test.ts +++ b/ui-packages/web/src/data/file-store.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { FileCollection } from '../core/files' +import { type FileCollection, rootSources } from '../core/files' import { samples } from '../core/samples' import { closeFileStore, @@ -11,6 +11,7 @@ import { updateStoredTextFile, writeStoredTextFile, } from './file-store' +import { getFolderExport } from './folder-export-store' const textFile = (name: string, content: string) => new File([content], name, { type: 'text/markdown', lastModified: 1 }) @@ -56,8 +57,9 @@ describe('local file store', () => { }) expect(await listStoredFiles()).toEqual([ - expect.objectContaining({ id: 'legacy', collection: 'files' }), + expect.objectContaining({ id: 'legacy', path: 'Legacy.md', collection: 'files' }), ]) + expect((await listStoredFiles())[0]).not.toHaveProperty('name') expect(await (await getStoredFileContent('legacy'))?.text()).toBe('legacy') }) @@ -90,11 +92,64 @@ describe('local file store', () => { }) expect(await listStoredFiles()).toEqual([ - expect.objectContaining({ id: 'version-two', name: 'Version two.md' }), + expect.objectContaining({ id: 'version-two', path: 'Version two.md' }), ]) expect(await (await getStoredFileContent('version-two'))?.text()).toBe('old') }) + it('places version-six files and saved export versions on paths', async () => { + await closeFileStore() + await new Promise((resolve, reject) => { + const request = indexedDB.open('gamma-reader-files', 6) + request.onupgradeneeded = () => { + const files = request.result.createObjectStore('files', { keyPath: 'id' }) + files.createIndex('by-created-at', 'createdAt') + request.result.createObjectStore('contents', { keyPath: 'id' }) + request.result.createObjectStore('conversations', { keyPath: 'id' }) + request.result.createObjectStore('messages', { keyPath: ['conversationId', 'position'] }) + const exports = request.result.createObjectStore('folderExports', { keyPath: 'id' }) + files.put({ + id: 'version-six', + name: 'Version six.md', + collection: 'attachments', + mediaType: 'text/markdown', + previewKind: 'markdown', + size: 3, + lastModified: 1, + createdAt: 1, + revision: 4, + }) + exports.put({ + id: 'files', + directory: { kind: 'directory', name: 'Reading' }, + savedFiles: [{ id: 'version-six', name: 'Version six.md', revision: 4 }], + savedAt: 1, + }) + } + request.onsuccess = () => { + request.result.close() + resolve() + } + request.onerror = () => reject(request.error) + }) + + const [file] = await listStoredFiles() + expect(file).toEqual({ + id: 'version-six', + path: 'Version six.md', + collection: 'attachments', + mediaType: 'text/markdown', + previewKind: 'markdown', + size: 3, + lastModified: 1, + createdAt: 1, + revision: 4, + }) + expect((await getFolderExport())?.savedFiles).toEqual([ + { id: 'version-six', path: 'Version six.md', revision: 4 }, + ]) + }) + it('can retry after opening IndexedDB fails', async () => { vi.spyOn(indexedDB, 'open').mockImplementationOnce(() => { throw new DOMException('Temporarily unavailable', 'UnknownError') @@ -110,42 +165,42 @@ describe('local file store', () => { expect(initial).toEqual([ expect.objectContaining({ id: 'getting-started', - name: 'Start here.md', + path: 'Start here.md', previewKind: 'markdown', }), expect.objectContaining({ id: 'art-of-noticing', - name: 'The art of noticing.pdf', + path: 'The art of noticing.pdf', previewKind: 'pdf', }), expect.objectContaining({ id: 'field-notes', - name: 'Field notes.docx', + path: 'Field notes.docx', previewKind: 'docx', }), expect.objectContaining({ id: 'observation-log', - name: 'Observation log.xlsx', + path: 'Observation log.xlsx', previewKind: 'xlsx', }), expect.objectContaining({ id: 'explore-wave', - name: 'Explore a wave.lab.md', + path: 'Explore a wave.lab.md', previewKind: 'markdown', }), expect.objectContaining({ id: 'seven-mornings', - name: 'Seven mornings.lab.md', + path: 'Seven mornings.lab.md', previewKind: 'markdown', }), expect.objectContaining({ id: 'orbit-demo', - name: 'Orbit.p5.js', + path: 'Orbit.p5.js', previewKind: 'text', }), expect.objectContaining({ id: 'how-gamma-reader-works', - name: 'How Gamma Reader works.svg', + path: 'How Gamma Reader works.svg', previewKind: 'image', }), ]) @@ -159,27 +214,30 @@ describe('local file store', () => { }) it('replaces a duplicate in place or keeps it under a numbered name', async () => { - const added = await importStoredFiles([textFile('Draft.md', 'first')], 'keep') + const added = await importStoredFiles(rootSources([textFile('Draft.md', 'first')]), 'keep') expect(added.addedIds).toHaveLength(1) const id = onlyAddedId(added) - const replaced = await importStoredFiles([textFile('Draft.md', 'second')], 'replace') + const replaced = await importStoredFiles( + rootSources([textFile('Draft.md', 'second')]), + 'replace', + ) expect(replaced).toMatchObject({ addedIds: [], replacedIds: [id], rejected: [] }) expect(await getStoredFileContent(id)).not.toBeNull() expect(await (await getStoredFileContent(id))?.text()).toBe('second') - const kept = await importStoredFiles([textFile('Draft.md', 'third')], 'keep') + const kept = await importStoredFiles(rootSources([textFile('Draft.md', 'third')]), 'keep') expect(kept.addedIds).toHaveLength(1) const keptId = onlyAddedId(kept) const files = await listStoredFiles() - expect(files.find(file => file.id === id)).toMatchObject({ name: 'Draft.md', revision: 2 }) - expect(files.find(file => file.id === keptId)?.name).toBe('Draft (2).md') + expect(files.find(file => file.id === id)).toMatchObject({ path: 'Draft.md', revision: 2 }) + expect(files.find(file => file.id === keptId)?.path).toBe('Draft (2).md') }) it('writes generated text through the same limits and replacement model', async () => { const first = await writeStoredTextFile('Generated.json', '{"value":"初稿"}') expect(first).toMatchObject({ - name: 'Generated.json', + path: 'Generated.json', collection: 'files', previewKind: 'text', revision: 1, @@ -195,7 +253,7 @@ describe('local file store', () => { await expect( writeStoredTextFile('Cancelled.txt', 'not written', controller.signal), ).rejects.toThrow() - expect((await listStoredFiles()).some(file => file.name === 'Cancelled.txt')).toBe(false) + expect((await listStoredFiles()).some(file => file.path === 'Cancelled.txt')).toBe(false) }) it('stores generated SVG as an image and repairs legacy SVG Blob types when reading', async () => { @@ -206,7 +264,7 @@ describe('local file store', () => { expect((await getStoredFileContent(generated.id))?.type).toBe('image/svg+xml') const legacy = await importStoredFiles( - [new File([source], 'Legacy.svg', { type: 'text/plain;charset=utf-8' })], + rootSources([new File([source], 'Legacy.svg', { type: 'text/plain;charset=utf-8' })]), 'keep', ) const legacyId = onlyAddedId(legacy) @@ -217,30 +275,71 @@ describe('local file store', () => { it('stores only the last copy when a selected batch repeats a new name', async () => { const result = await importStoredFiles( - [textFile('Repeated.md', 'first'), textFile('Repeated.md', 'last')], + rootSources([textFile('Repeated.md', 'first'), textFile('Repeated.md', 'last')]), 'replace', ) expect(result.addedIds).toHaveLength(1) expect(result.replacedIds).toEqual([]) - expect((await listStoredFiles()).filter(file => file.name === 'Repeated.md')).toHaveLength(1) + expect((await listStoredFiles()).filter(file => file.path === 'Repeated.md')).toHaveLength(1) expect(await (await getStoredFileContent(onlyAddedId(result)))?.text()).toBe('last') }) + it('stores files on folder paths and numbers a kept duplicate within its folder', async () => { + const result = await importStoredFiles( + [ + { path: 'docs/v1.2/Guide.md', file: textFile('Guide.md', 'first') }, + { path: 'docs/v1.2/Guide.md', file: textFile('Guide.md', 'second') }, + ], + 'keep', + ) + + expect(result.imported.map(item => item.metadata.path)).toEqual([ + 'docs/v1.2/Guide.md', + 'docs/v1.2/Guide (2).md', + ]) + const [first] = result.imported + expect(await (await getStoredFileContent(first?.metadata.id ?? ''))?.text()).toBe('first') + }) + + it('rejects paths that are malformed or would put a file where a folder is', async () => { + await importStoredFiles([{ path: 'docs/a.md', file: textFile('a.md', 'a') }], 'keep') + + const result = await importStoredFiles( + ['docs', 'docs/a.md/b.md', '../a.md', '/a.md', 'a//b.md'].map(path => ({ + path, + file: textFile('x.md', 'x'), + })), + 'replace', + ) + + expect(result.imported).toEqual([]) + expect(result.rejected.map(item => [item.path, item.reason])).toEqual([ + ['docs', 'path-conflict'], + ['docs/a.md/b.md', 'path-conflict'], + ['../a.md', 'invalid-path'], + ['/a.md', 'invalid-path'], + ['a//b.md', 'invalid-path'], + ]) + // Names a disk allows, such as one with a backslash, still import at the root. + const kept = await importStoredFiles(rootSources([textFile('a\\b.md', 'kept')]), 'keep') + expect(kept.imported[0]?.metadata.path).toBe('a\\b.md') + }) + it('recognizes common UTF-8 document formats with application MIME types as text', async () => { await importStoredFiles( - [new File(['{"local":true}'], 'Context.json', { type: 'application/json' })], + rootSources([new File(['{"local":true}'], 'Context.json', { type: 'application/json' })]), 'keep', ) - expect((await listStoredFiles()).find(file => file.name === 'Context.json')?.previewKind).toBe( + expect((await listStoredFiles()).find(file => file.path === 'Context.json')?.previewKind).toBe( 'text', ) }) it('stores chat attachments in the shared workspace with source mappings', async () => { const result = await importStoredFiles( - [textFile('Chat notes.md', 'private attachment content')], + rootSources([textFile('Chat notes.md', 'private attachment content')]), 'keep', 'attachments', ) @@ -249,9 +348,9 @@ describe('local file store', () => { expect(result.imported[0]).toMatchObject({ sourceIndex: 0, action: 'added', - metadata: { name: 'Chat notes.md', collection: 'attachments' }, + metadata: { path: 'Chat notes.md', collection: 'attachments' }, }) - expect((await listStoredFiles()).find(file => file.name === 'Chat notes.md')).toMatchObject({ + expect((await listStoredFiles()).find(file => file.path === 'Chat notes.md')).toMatchObject({ collection: 'attachments', }) expect(await (await getStoredFileContent(result.imported[0]?.metadata.id ?? ''))?.text()).toBe( @@ -264,19 +363,19 @@ describe('local file store', () => { async collection => { const size = 200 * 1024 * 1024 const result = await importStoredFiles( - [fileWithReportedSize('large.pdf', size)], + rootSources([fileWithReportedSize('large.pdf', size)]), 'keep', collection, ) const id = onlyAddedId(result) const before = await getStoredFile(id) const rejected = await importStoredFiles( - [fileWithReportedSize('large.pdf', size + 1)], + rootSources([fileWithReportedSize('large.pdf', size + 1)]), 'replace', collection, ) expect(rejected.rejected).toEqual([ - { sourceIndex: 0, name: 'large.pdf', reason: 'file-too-large' }, + { sourceIndex: 0, path: 'large.pdf', reason: 'file-too-large' }, ]) expect((await getStoredFile(id))?.metadata).toEqual(before?.metadata) expect(await (await getStoredFileContent(id))?.text()).toBe('content') @@ -289,20 +388,23 @@ describe('local file store', () => { const files = Array.from({ length: 5 }, (_, index) => fileWithReportedSize(`large-${index}.bin`, size), ) - expect((await importStoredFiles(files, 'keep')).addedIds).toHaveLength(5) + expect((await importStoredFiles(rootSources(files), 'keep')).addedIds).toHaveLength(5) const remaining = 1024 * 1024 * 1024 - seedBytes - 5 * size const tail = fileWithReportedSize('tail.bin', remaining) - const id = onlyAddedId(await importStoredFiles([tail], 'keep', 'attachments')) - const overflow = await importStoredFiles([fileWithReportedSize('extra.bin', 1)], 'keep') + const id = onlyAddedId(await importStoredFiles(rootSources([tail]), 'keep', 'attachments')) + const overflow = await importStoredFiles( + rootSources([fileWithReportedSize('extra.bin', 1)]), + 'keep', + ) expect(overflow.rejected[0]?.reason).toBe('library-full') const rejected = await importStoredFiles( - [fileWithReportedSize('tail.bin', remaining + 1)], + rootSources([fileWithReportedSize('tail.bin', remaining + 1)]), 'replace', 'attachments', ) expect(rejected.rejected[0]?.reason).toBe('library-full') expect((await getStoredFile(id))?.metadata.size).toBe(remaining) - const replaced = await importStoredFiles([tail], 'replace', 'attachments') + const replaced = await importStoredFiles(rootSources([tail]), 'replace', 'attachments') expect(replaced.imported[0]).toMatchObject({ action: 'replaced', metadata: { id } }) }) @@ -313,9 +415,12 @@ describe('local file store', () => { value: { estimate: async () => ({ quota: 100, usage: 99 }) }, }) try { - const result = await importStoredFiles([fileWithReportedSize('small.bin', 2)], 'keep') + const result = await importStoredFiles( + rootSources([fileWithReportedSize('small.bin', 2)]), + 'keep', + ) expect(result.rejected[0]?.reason).toBe('storage-unavailable') - expect((await listStoredFiles()).some(file => file.name === 'small.bin')).toBe(false) + expect((await listStoredFiles()).some(file => file.path === 'small.bin')).toBe(false) } finally { if (descriptor) Object.defineProperty(navigator, 'storage', descriptor) else Reflect.deleteProperty(navigator, 'storage') diff --git a/ui-packages/web/src/data/file-store.ts b/ui-packages/web/src/data/file-store.ts index 31aa37f..5b82d7a 100644 --- a/ui-packages/web/src/data/file-store.ts +++ b/ui-packages/web/src/data/file-store.ts @@ -1,7 +1,10 @@ import { nanoid } from 'nanoid' import { + baseName, type FileCollection, type ImportResult, + type ImportSource, + isWorkspacePath, maximumFileBytes, maximumLibraryBytes, previewKindFor, @@ -27,7 +30,7 @@ const openFileDatabase = openWorkspaceDatabase const svgMediaType = 'image/svg+xml' const isSvg = (name: string) => name.toLowerCase().endsWith('.svg') const storedBlob = (metadata: StoredFileMetadata | undefined, blob: Blob) => - metadata && isSvg(metadata.name) && blob.type !== svgMediaType + metadata && isSvg(metadata.path) && blob.type !== svgMediaType ? new Blob([blob], { type: svgMediaType }) : blob @@ -59,24 +62,35 @@ export const getStoredFile = async (id: string) => { transaction.done, ]) if (!metadata) return null - if (!content) throw new Error(`Stored file content is missing: ${metadata.name}`) + if (!content) throw new Error(`Stored file content is missing: ${metadata.path}`) return { metadata, blob: storedBlob(metadata, content.blob) } } -const nextName = (requested: string, occupied: Set) => { - const dot = requested.lastIndexOf('.') +// Only the file name takes the number, so a dot in a folder name never splits the path. +const nextPath = (requested: string, occupied: Set) => { + const folder = requested.slice(0, requested.length - baseName(requested).length) + const name = baseName(requested) + const dot = name.lastIndexOf('.') const hasExtension = dot > 0 - const stem = hasExtension ? requested.slice(0, dot) : requested - const extension = hasExtension ? requested.slice(dot) : '' + const stem = hasExtension ? name.slice(0, dot) : name + const extension = hasExtension ? name.slice(dot) : '' let number = 2 - let candidate = `${stem} (${number})${extension}` + let candidate = `${folder}${stem} (${number})${extension}` while (occupied.has(candidate.toLowerCase())) { number += 1 - candidate = `${stem} (${number})${extension}` + candidate = `${folder}${stem} (${number})${extension}` } return candidate } +// A path cannot name a file and a folder at once: one may not lie inside the other. +const shadows = (path: string, occupied: Iterable) => { + const key = path.toLowerCase() + for (const other of occupied) + if (other.startsWith(`${key}/`) || key.startsWith(`${other}/`)) return true + return false +} + const hasBrowserCapacity = async (bytes: number) => { if (bytes <= 0 || !navigator.storage?.estimate) return true try { @@ -95,7 +109,7 @@ type PlannedWrite = { } export const importStoredFiles = async ( - selected: readonly File[], + selected: readonly ImportSource[], duplicateMode: DuplicateMode, collection: FileCollection = 'files', signal?: AbortSignal, @@ -104,43 +118,49 @@ export const importStoredFiles = async ( const database = await openFileDatabase() const existing = await database.getAllFromIndex('files', 'by-created-at') const existingIds = new Set(existing.map(file => file.id)) - const planned = new Map(existing.map(file => [file.name.toLowerCase(), file])) + const planned = new Map(existing.map(file => [file.path.toLowerCase(), file])) const writes = new Map() const rejected: ImportResult['rejected'] = [] let totalBytes = existing.reduce((total, file) => total + file.size, 0) const createdAt = Date.now() - selected.forEach((file, index) => { - if (file.size > maximumFileBytes) { - rejected.push({ sourceIndex: index, name: file.name, reason: 'file-too-large' }) + selected.forEach(({ path: requested, file }, index) => { + const duplicate = planned.get(requested.toLowerCase()) + const path = + duplicate && duplicateMode === 'keep' + ? nextPath(requested, new Set(planned.keys())) + : requested + const reason = !isWorkspacePath(requested) + ? 'invalid-path' + : file.size > maximumFileBytes + ? 'file-too-large' + : shadows(path, planned.keys()) + ? 'path-conflict' + : null + if (reason) { + rejected.push({ sourceIndex: index, path: requested, reason }) return } - const requestedKey = file.name.toLowerCase() - const duplicate = planned.get(requestedKey) - const name = - duplicate && duplicateMode === 'keep' - ? nextName(file.name, new Set(planned.keys())) - : file.name const replaced = duplicate !== undefined && duplicateMode === 'replace' const id = replaced ? duplicate.id : nanoid() const previousSize = replaced ? duplicate.size : 0 if (totalBytes - previousSize + file.size > maximumLibraryBytes) { - rejected.push({ sourceIndex: index, name: file.name, reason: 'library-full' }) + rejected.push({ sourceIndex: index, path: requested, reason: 'library-full' }) return } const metadata: StoredFileMetadata = { id, - name, + path, collection, mediaType: file.type || 'application/octet-stream', - previewKind: previewKindFor(name, file.type), + previewKind: previewKindFor(path, file.type), size: file.size, lastModified: file.lastModified, createdAt: replaced ? duplicate.createdAt : createdAt + index, revision: replaced ? duplicate.revision + 1 : 1, } totalBytes += file.size - previousSize - planned.set(name.toLowerCase(), metadata) + planned.set(path.toLowerCase(), metadata) writes.set(id, { sourceIndex: index, metadata, @@ -159,7 +179,7 @@ export const importStoredFiles = async ( ...rejected, ...plannedWrites.map(write => ({ sourceIndex: write.sourceIndex, - name: write.metadata.name, + path: write.metadata.path, reason: 'storage-unavailable' as const, })), ], @@ -193,7 +213,7 @@ export const importStoredFiles = async ( ...rejected, ...plannedWrites.map(write => ({ sourceIndex: write.sourceIndex, - name: write.metadata.name, + path: write.metadata.path, reason: 'storage-unavailable' as const, })), ], @@ -217,19 +237,28 @@ export const importStoredFiles = async ( const writeError = (reason: ImportResult['rejected'][number]['reason']) => { if (reason === 'file-too-large') return new Error('The file exceeds the 200 MiB file limit.') if (reason === 'library-full') return new Error('The file exceeds the 1 GiB library limit.') + if (reason === 'invalid-path') + return new Error('Use a relative path whose segments are not empty, "." or "..".') + if (reason === 'path-conflict') + return new Error('The path would place a file where a folder is, or inside a file.') return new Error('The file does not fit in browser storage.') } -export const writeStoredTextFile = async (name: string, content: string, signal?: AbortSignal) => { +export const writeStoredTextFile = async (path: string, content: string, signal?: AbortSignal) => { signal?.throwIfAborted() const existing = (await listStoredFiles()).find( - file => file.name.toLowerCase() === name.toLowerCase(), + file => file.path.toLowerCase() === path.toLowerCase(), ) - const file = new File([content], name, { - type: isSvg(name) ? svgMediaType : 'text/plain;charset=utf-8', + const file = new File([content], baseName(path), { + type: isSvg(path) ? svgMediaType : 'text/plain;charset=utf-8', lastModified: Date.now(), }) - const result = await importStoredFiles([file], 'replace', existing?.collection ?? 'files', signal) + const result = await importStoredFiles( + [{ path, file }], + 'replace', + existing?.collection ?? 'files', + signal, + ) const written = result.imported[0]?.metadata if (written) return written const rejected = result.rejected[0] diff --git a/ui-packages/web/src/data/folder-export-store.test.ts b/ui-packages/web/src/data/folder-export-store.test.ts index ead48c6..e9794ba 100644 --- a/ui-packages/web/src/data/folder-export-store.test.ts +++ b/ui-packages/web/src/data/folder-export-store.test.ts @@ -7,7 +7,7 @@ describe('folder export store', () => { const record: FolderExportRecord = { id: 'files', directory: { kind: 'directory', name: 'Reading' } as WritableDirectoryHandle, - savedFiles: [{ id: 'notes', name: 'Notes.md', revision: 3 }], + savedFiles: [{ id: 'notes', path: 'Notes.md', revision: 3 }], savedAt: 42, } diff --git a/ui-packages/web/src/data/workspace-database.ts b/ui-packages/web/src/data/workspace-database.ts index 4634125..ff3dda9 100644 --- a/ui-packages/web/src/data/workspace-database.ts +++ b/ui-packages/web/src/data/workspace-database.ts @@ -24,6 +24,10 @@ export type WorkspaceDatabase = DBSchema & { folderExports: { key: string; value: FolderExportRecord } } +// Records written before version 7 named a file instead of placing it on a path. +type LegacyFileRecord = Omit & { path?: string; name?: string } +type LegacyExportedFile = { id: string; revision: number; path?: string; name?: string } + // A page opens one project for its whole life, chosen from the address before anything is read. let databaseName = legacyDatabaseName let databasePromise: Promise> | undefined @@ -57,7 +61,7 @@ const seedSamples = async (database: IDBPDatabase) => { const blob = new Blob([sample.content], { type: sample.mediaType }) files.put({ id: sample.id, - name: sample.name, + path: sample.name, collection: 'files', mediaType: blob.type, previewKind: previewKindFor(sample.name, blob.type), @@ -74,7 +78,7 @@ const seedSamples = async (database: IDBPDatabase) => { export const openWorkspaceDatabase = () => { if (databasePromise) return databasePromise let seeding = false - databasePromise = openDB(databaseName, 6, { + databasePromise = openDB(databaseName, 7, { upgrade(database, oldVersion, _newVersion, transaction) { if (oldVersion < 1) { const files = database.createObjectStore('files', { keyPath: 'id' }) @@ -83,19 +87,6 @@ export const openWorkspaceDatabase = () => { // Only the first library carries the starter files; a new project starts empty. seeding = databaseName === legacyDatabaseName } - if (oldVersion === 1) { - const files = transaction.objectStore('files') - void (async () => { - let cursor = await files.openCursor() - while (cursor) { - await cursor.update({ ...cursor.value, collection: 'files' }) - cursor = await cursor.continue() - } - })().catch(error => { - console.error('Unable to migrate the local file library', error) - transaction.abort() - }) - } if (oldVersion < 3) { const conversations = database.createObjectStore('conversations', { keyPath: 'id' }) conversations.createIndex('by-last-active', ['lastActiveAt', 'id']) @@ -105,19 +96,48 @@ export const openWorkspaceDatabase = () => { messages.createIndex('by-conversation', 'conversationId') } if (oldVersion < 4) database.createObjectStore('folderExports', { keyPath: 'id' }) - // Files imported before a format was supported still carry the old preview kind. - if (oldVersion > 0 && oldVersion < 6) { + // One pass rewrites every older record, so no two cursors write back stale copies of it: + // version 1 lacked a collection, files from before version 6 may carry an outdated + // preview kind, and files from before version 7 were named rather than placed on a path. + if (oldVersion > 0 && oldVersion < 7) { const files = transaction.objectStore('files') void (async () => { let cursor = await files.openCursor() while (cursor) { - const previewKind = previewKindFor(cursor.value.name, cursor.value.mediaType) - if (previewKind !== cursor.value.previewKind) - await cursor.update({ ...cursor.value, previewKind }) + const { name, ...value }: LegacyFileRecord = cursor.value + const path = value.path ?? name + if (path === undefined) throw new Error(`Stored file has no path: ${value.id}`) + await cursor.update({ + ...value, + path, + collection: oldVersion === 1 ? 'files' : value.collection, + previewKind: + oldVersion < 6 ? previewKindFor(path, value.mediaType) : value.previewKind, + }) + cursor = await cursor.continue() + } + })().catch(error => { + console.error('Unable to migrate the local file library', error) + transaction.abort() + }) + } + if (oldVersion >= 4 && oldVersion < 7) { + const exports = transaction.objectStore('folderExports') + void (async () => { + let cursor = await exports.openCursor() + while (cursor) { + const savedFiles: readonly LegacyExportedFile[] = cursor.value.savedFiles + await cursor.update({ + ...cursor.value, + savedFiles: savedFiles.map(({ id, revision, name, path = name }) => { + if (path === undefined) throw new Error(`Saved export has no path: ${id}`) + return { id, revision, path } + }), + }) cursor = await cursor.continue() } })().catch(error => { - console.error('Unable to refresh stored preview kinds', error) + console.error('Unable to migrate the saved export folder', error) transaction.abort() }) } diff --git a/ui-packages/web/src/features/agent/create-reader-agent.test.ts b/ui-packages/web/src/features/agent/create-reader-agent.test.ts index 96914d6..39a0591 100644 --- a/ui-packages/web/src/features/agent/create-reader-agent.test.ts +++ b/ui-packages/web/src/features/agent/create-reader-agent.test.ts @@ -1,6 +1,7 @@ import type { PDFDocumentProxy } from 'pdfjs-dist' import { describe, expect, it, vi } from 'vitest' import { createReaderUserMessage } from '../../core/agent/reader-message' +import { rootSources } from '../../core/files' import type { ReaderState } from '../../core/reader-state' import { getStoredFile, @@ -140,7 +141,7 @@ describe('reader agent', () => { '
Saved
', expect.any(AbortSignal), ) - const written = (await listStoredFiles()).find(file => file.name === 'Study notes.html') + const written = (await listStoredFiles()).find(file => file.path === 'Study notes.html') if (!written) throw new Error('Written file is missing') expect(written.previewKind).toBe('html') expect(await (await getStoredFileContent(written.id))?.text()).toBe('
Saved
') @@ -153,14 +154,14 @@ describe('reader agent', () => { it('runs local tools through Pi and supplies context only after a tool request', async () => { const imported = await importStoredFiles( - [new File(['# Local secret\n\nThe fox reads quietly.'], 'private.md')], + rootSources([new File(['# Local secret\n\nThe fox reads quietly.'], 'private.md')]), 'keep', ) const fileId = imported.addedIds[0] if (!fileId) throw new Error('Missing fixture') const state: ReaderState = { - openFiles: [{ id: fileId, name: 'private.md', type: 'markdown' }], - activeFile: { id: fileId, name: 'private.md', type: 'markdown' }, + openFiles: [{ id: fileId, path: 'private.md', type: 'markdown' }], + activeFile: { id: fileId, path: 'private.md', type: 'markdown' }, viewport: { startText: 'The fox', endText: 'quietly.' }, } const requests: { messages: { role: string; content: string; tool_call_id?: string }[] }[] = [] @@ -223,7 +224,7 @@ describe('reader agent', () => { it('uses a one-shot vision model and returns only its text to the main agent', async () => { const imported = await importStoredFiles( - [new File(['private-image-bytes'], 'screen.png', { type: 'image/png' })], + rootSources([new File(['private-image-bytes'], 'screen.png', { type: 'image/png' })]), 'keep', ) const fileId = imported.addedIds[0] @@ -270,7 +271,7 @@ describe('reader agent', () => { it('rejects missing and non-image files before contacting the vision model', async () => { const imported = await importStoredFiles( - [new File(['Readable text'], 'note.txt', { type: 'text/plain' })], + rootSources([new File(['Readable text'], 'note.txt', { type: 'text/plain' })]), 'keep', ) const fileId = imported.addedIds[0] @@ -330,7 +331,7 @@ describe('reader agent', () => { pdfTools.render.mockClear() pdfTools.read.mockClear() const imported = await importStoredFiles( - [new File(['pdf'], 'Study.pdf', { type: 'application/pdf' })], + rootSources([new File(['pdf'], 'Study.pdf', { type: 'application/pdf' })]), 'keep', ) const fileId = imported.addedIds[0] @@ -400,7 +401,10 @@ describe('reader agent', () => { value: '

季度报告

营收增长了两成。

', messages: [], }) - const imported = await importStoredFiles([new File(['docx bytes'], 'report.docx')], 'keep') + const imported = await importStoredFiles( + rootSources([new File(['docx bytes'], 'report.docx')]), + 'keep', + ) const fileId = imported.addedIds[0] if (!fileId) throw new Error('Missing fixture') const stored = await getStoredFile(fileId) @@ -426,7 +430,10 @@ describe('reader agent', () => { }, { sheet: '汇总', data: [['合计', 3]] }, ]) - const imported = await importStoredFiles([new File(['xlsx bytes'], 'effort.xlsx')], 'keep') + const imported = await importStoredFiles( + rootSources([new File(['xlsx bytes'], 'effort.xlsx')]), + 'keep', + ) const fileId = imported.addedIds[0] if (!fileId) throw new Error('Missing fixture') const stored = await getStoredFile(fileId) diff --git a/ui-packages/web/src/features/agent/document-tools.ts b/ui-packages/web/src/features/agent/document-tools.ts index 0f7812f..aac0dcc 100644 --- a/ui-packages/web/src/features/agent/document-tools.ts +++ b/ui-packages/web/src/features/agent/document-tools.ts @@ -39,7 +39,7 @@ export type DocumentAccess = { open: (fileId: string, signal?: AbortSignal) => Promise } type DocumentCursor = - | { operation: 'list'; name: string; index: number } + | { operation: 'list'; path: string; index: number } | { operation: 'search' query: string @@ -60,7 +60,7 @@ type DocumentCursor = } const validDocumentCursor = (value: unknown): value is DocumentCursor => { if (!record(value)) return false - if (value.operation === 'list') return typeof value.name === 'string' && integer(value.index, 0) + if (value.operation === 'list') return typeof value.path === 'string' && integer(value.index, 0) if (typeof value.fileId !== 'string' || !integer(value.revision, 1) || !integer(value.page, 1)) return false if (value.operation === 'search') @@ -78,13 +78,13 @@ const list = async ( signal?: AbortSignal, ): Promise => { signal?.throwIfAborted() - const name = normalizeSearchText(input.name ?? '') - if (name.length > 512) - throw new LocalToolError('Use a shorter file name filter (up to 512 characters).') + const path = normalizeSearchText(input.path ?? '') + if (path.length > 512) + throw new LocalToolError('Use a shorter path filter (up to 512 characters).') const cursor = decodeCursor(input.cursor, validDocumentCursor) - if (cursor && (cursor.operation !== 'list' || cursor.name !== name)) throw mismatchedCursor() + if (cursor && (cursor.operation !== 'list' || cursor.path !== path)) throw mismatchedCursor() const files = (await access.listFiles()).filter(file => - normalizeSearchText(file.name).includes(name), + normalizeSearchText(file.path).includes(path), ) const result: ListResult = { files: [], next: null } for (let index = cursor?.index ?? 0; index < files.length; index++) { @@ -94,15 +94,15 @@ const list = async ( const { reason, textReadable } = access.getReadability(file) const entry = { id: file.id, - name: file.name, + path: file.path, collection: file.collection ?? 'files', type: file.previewKind, textReadable, ...(reason ? { reason } : {}), } const next = { - ...(name ? { name } : {}), - cursor: encodeCursor({ operation: 'list', name, index }), + ...(path ? { path } : {}), + cursor: encodeCursor({ operation: 'list', path, index }), } if (result.files.length >= 100 || !fitsResult({ files: [...result.files, entry], next })) { if (!result.files.length) throw new LocalToolError('File metadata exceeds the result limit.') @@ -210,7 +210,7 @@ const search = async ( } const entry = { fileId: file.id, - name: file.name, + path: file.path, ...match, excerpt: boundedText(match.excerpt, 1200), } @@ -230,17 +230,17 @@ const search = async ( if (!hasText) result.issues.push({ fileId: file.id, - name: file.name, + path: file.path, reason: 'No extractable text in this file. OCR is not available.', }) } catch (error) { signal?.throwIfAborted() if (source && resume && resume.revision !== source.file.revision) throw error if (!(error instanceof LocalToolError)) - console.error('Unable to search file', file.name, error) + console.error('Unable to search file', file.path, error) result.issues.push({ fileId: file.id, - name: file.name, + path: file.path, reason: boundedText( error instanceof Error ? error.message : 'Unable to read this file.', 300, @@ -334,7 +334,7 @@ const readDocument = async ( const end = start + (content.match(/\n/g)?.length ?? 0) - (content.endsWith('\n') ? 1 : 0) return { fileId: input.fileId, - name: source.file.name, + path: source.file.path, range: source.unit === 'page' ? { unit: 'page', start: page, end: page } diff --git a/ui-packages/web/src/features/agent/docx/runtime.ts b/ui-packages/web/src/features/agent/docx/runtime.ts index e05e60f..da5252d 100644 --- a/ui-packages/web/src/features/agent/docx/runtime.ts +++ b/ui-packages/web/src/features/agent/docx/runtime.ts @@ -22,7 +22,7 @@ export const createDocxRuntime = () => { if (current?.id !== file.id || current.revision !== file.revision) { const { markdown, messages } = await convertDocxToMarkdown(stored.blob, { images: false }) signal?.throwIfAborted() - reportDocxMessages(file.name, messages) + reportDocxMessages(file.path, messages) current = { id: file.id, revision: file.revision, text: markdownText(markdown) } } const { text } = current diff --git a/ui-packages/web/src/features/agent/image-tools.ts b/ui-packages/web/src/features/agent/image-tools.ts index d27bf8e..2e55439 100644 --- a/ui-packages/web/src/features/agent/image-tools.ts +++ b/ui-packages/web/src/features/agent/image-tools.ts @@ -30,7 +30,7 @@ export const createImageTools = (loadFile: typeof getStoredFile, analyze: Vision input.question?.trim() || 'Describe this image and transcribe any important visible text.', signal, ) - return { fileId: stored.metadata.id, name: stored.metadata.name, analysis } + return { fileId: stored.metadata.id, path: stored.metadata.path, analysis } }, ), ] diff --git a/ui-packages/web/src/features/agent/local-tools.test.ts b/ui-packages/web/src/features/agent/local-tools.test.ts index f8c64d6..130167e 100644 --- a/ui-packages/web/src/features/agent/local-tools.test.ts +++ b/ui-packages/web/src/features/agent/local-tools.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { rootSources } from '../../core/files' import { getStoredFile, importStoredFiles, @@ -39,7 +40,7 @@ const tools = createDocumentTools({ }) const add = async (name: string, text: string, type = 'text/plain') => { - const result = await importStoredFiles([new File([text], name, { type })], 'keep') + const result = await importStoredFiles(rootSources([new File([text], name, { type })]), 'keep') const id = result.addedIds[0] if (!id) throw new Error('Fixture import failed') return id @@ -50,19 +51,21 @@ const budget = (result: unknown) => describe('local reader tools', () => { it('lists capabilities, filters names, and paginates without losing files', async () => { await importStoredFiles( - Array.from( - { length: 105 }, - (_, index) => new File(['text'], `Fixture ${index}.txt`, { type: 'text/plain' }), + rootSources( + Array.from( + { length: 105 }, + (_, index) => new File(['text'], `Fixture ${index}.txt`, { type: 'text/plain' }), + ), ), 'keep', ) await add('Fixture unsupported.html', '

text

', 'text/html') await importStoredFiles( - [new File(['context'], 'Fixture attachment.txt', { type: 'text/plain' })], + rootSources([new File(['context'], 'Fixture attachment.txt', { type: 'text/plain' })]), 'keep', 'attachments', ) - let next: ListInput | null = { name: 'FIXTURE' } + let next: ListInput | null = { path: 'FIXTURE' } const files = [] while (next) { const result = await tools.list(next) @@ -72,7 +75,7 @@ describe('local reader tools', () => { } expect(files).toHaveLength(107) expect(new Set(files.map(file => file.id)).size).toBe(107) - expect(files.find(file => file.name === 'Fixture attachment.txt')).toMatchObject({ + expect(files.find(file => file.path === 'Fixture attachment.txt')).toMatchObject({ collection: 'attachments', textReadable: true, }) @@ -92,7 +95,7 @@ describe('local reader tools', () => { { type: 'text/markdown' }, ), ) - await importStoredFiles(contents, 'keep') + await importStoredFiles(rootSources(contents), 'keep') let next: SearchInput | null = { query: 'SEARCH this\nphrase' } const matches: SearchMatch[] = [] while (next) { @@ -143,7 +146,7 @@ describe('local reader tools', () => { tools.read({ ...result.next, range: { unit: 'line', start: 2, end: 3 } }), ).rejects.toThrow('does not match') await importStoredFiles( - [new File(['new content'], 'Changing.txt', { type: 'text/plain' })], + rootSources([new File(['new content'], 'Changing.txt', { type: 'text/plain' })]), 'replace', ) await expect(tools.read(result.next)).rejects.toThrow('File changed') @@ -155,12 +158,14 @@ describe('local reader tools', () => { it('reports unreadable files separately and bounds pages of errors', async () => { await importStoredFiles( - Array.from( - { length: 130 }, - (_, index) => - new File(['

Unreadable fixture

'], `Unreadable ${index}.html`, { - type: 'text/html', - }), + rootSources( + Array.from( + { length: 130 }, + (_, index) => + new File(['

Unreadable fixture

'], `Unreadable ${index}.html`, { + type: 'text/html', + }), + ), ), 'keep', ) @@ -179,7 +184,7 @@ describe('local reader tools', () => { expect(issueCount).toBe(131) expect(ids).toEqual([id]) const bad = await importStoredFiles( - [new File([new Uint8Array([255])], 'Broken.txt', { type: 'text/plain' })], + rootSources([new File([new Uint8Array([255])], 'Broken.txt', { type: 'text/plain' })]), 'keep', ) await expect(tools.read({ fileId: bad.addedIds[0] ?? '' })).rejects.toThrow('UTF-8') @@ -287,7 +292,7 @@ describe('active source tools', () => { it('reads raw source with lossless bounded pagination and detects changes', () => { let source: ActiveSourceSnapshot = { fileId: 'a', - name: 'A.md', + path: 'A.md', version: crypto.randomUUID(), content: `# Raw source\n${'中😀'.repeat(15000)}`, } @@ -317,7 +322,7 @@ describe('active source tools', () => { it('edits only the matching active file and version with a unique exact match', () => { let source: ActiveSourceSnapshot = { fileId: 'a', - name: 'A.md', + path: 'A.md', version: crypto.randomUUID(), content: 'same same', } diff --git a/ui-packages/web/src/features/agent/local-tools.ts b/ui-packages/web/src/features/agent/local-tools.ts index 4102e1e..ad4e713 100644 --- a/ui-packages/web/src/features/agent/local-tools.ts +++ b/ui-packages/web/src/features/agent/local-tools.ts @@ -42,14 +42,14 @@ const validSourceCursor = (value: unknown): value is SourceCursor => integer(value.offset, 0) export type WorkspaceTextWriter = ( - name: string, + path: string, content: string, signal?: AbortSignal, ) => Promise export type ActiveSourceSnapshot = { fileId: string - name: string + path: string version: string content: string } @@ -113,7 +113,7 @@ const readActiveSource = ( const end = start + (content.match(/\n/g)?.length ?? 0) - (content.endsWith('\n') ? 1 : 0) return { fileId: source.fileId, - name: source.name, + path: source.path, version: source.version, range: content ? { unit: 'line', start, end } : null, content, diff --git a/ui-packages/web/src/features/agent/pdf/SKILL.md b/ui-packages/web/src/features/agent/pdf/SKILL.md index 39e9d0b..85e9cc4 100644 --- a/ui-packages/web/src/features/agent/pdf/SKILL.md +++ b/ui-packages/web/src/features/agent/pdf/SKILL.md @@ -7,7 +7,7 @@ Use this guidance when a question depends on a PDF document. - Use get_reader_state when the reader refers to the current file or page. Otherwise use list or a supplied attachment fileId. - For document-level questions, use pdf_info to check the page count and pdf_outline to discover embedded bookmarks. An empty outline does not mean the document has no chapters. Read its contents pages or search for headings instead. - For a specific question, search first, then pass a match's fileId and range directly to read. For a chapter, use the bookmark's page and inspect the text to establish the boundaries; a bookmark is a destination, not an exact chapter range. -- All tool page numbers are one-based physical file pages. Printed page numbers can differ. Cite the file name and physical page number; do not silently substitute a printed number. +- All tool page numbers are one-based physical file pages. Printed page numbers can differ. Cite the file path and physical page number; do not silently substitute a printed number. ## Read text or inspect the page diff --git a/ui-packages/web/src/features/agent/pdf/runtime.test.ts b/ui-packages/web/src/features/agent/pdf/runtime.test.ts index 16f3421..9d37ef2 100644 --- a/ui-packages/web/src/features/agent/pdf/runtime.test.ts +++ b/ui-packages/web/src/features/agent/pdf/runtime.test.ts @@ -1,5 +1,6 @@ import type { PDFDocumentProxy } from 'pdfjs-dist' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { rootSources } from '../../../core/files' import { getStoredFile, importStoredFiles, removeStoredFile } from '../../../data/file-store' import { createPdfRuntime } from './runtime' @@ -43,7 +44,7 @@ beforeEach(() => { }) const addPdf = async (name = 'Book.pdf', mode: 'keep' | 'replace' = 'keep') => { const result = await importStoredFiles( - [new File(['pdf'], name, { type: 'application/pdf' })], + rootSources([new File(['pdf'], name, { type: 'application/pdf' })]), mode, ) const file = result.imported[0]?.metadata diff --git a/ui-packages/web/src/features/agent/system-prompt.ts b/ui-packages/web/src/features/agent/system-prompt.ts index 0418c29..9894036 100644 --- a/ui-packages/web/src/features/agent/system-prompt.ts +++ b/ui-packages/web/src/features/agent/system-prompt.ts @@ -1,10 +1,10 @@ export const systemPrompt = `You are a reading companion. Help the reader understand and compare their documents. Respond in the reader's language, clearly and concisely. -Use tools when a question depends on documents. Read an available skill when its description matches the task. Use get_reader_state to discover the current file and visible text; use list to discover workspace files and chat attachments. When a message includes attachment metadata, use its fileId directly with read, search or analyze_image. Use search to locate text, then read to retrieve the relevant passage. Use analyze_image when it is available and the question depends on an image; provide the user's focus as its question. Search ranges can be passed directly to read. Follow next when more results are needed, even if a search batch has no matches. Search is incomplete while next is non-null; report issues that prevented reading. Do not assume you have seen a whole document from one excerpt. Identify sources by file name and, when useful, page or line range. +Use tools when a question depends on documents. Read an available skill when its description matches the task. Use get_reader_state to discover the current file and visible text; use list to discover workspace files and chat attachments. When a message includes attachment metadata, use its fileId directly with read, search or analyze_image. Use search to locate text, then read to retrieve the relevant passage. Use analyze_image when it is available and the question depends on an image; provide the user's focus as its question. Search ranges can be passed directly to read. Follow next when more results are needed, even if a search batch has no matches. Search is incomplete while next is non-null; report issues that prevented reading. Do not assume you have seen a whole document from one excerpt. Identify sources by file path and, when useful, page or line range. Reading state can change between questions. Obtain fresh state when the reader refers to what they are currently reading. Do not claim to see selections or unreadable documents. Explain tool limitations or missing text when relevant. -Use write only when the reader explicitly asks you to create, save or completely rewrite a file. Write accepts UTF-8 text content in any text-based format and saves it in this browser's workspace. Use list first when a requested name may already exist because write replaces the complete contents of a same-named file. A successful write does not export the file to the host filesystem. +Use write only when the reader explicitly asks you to create, save or completely rewrite a file. Write accepts UTF-8 text content in any text-based format and saves it in this browser's workspace. Files live on paths such as docs/notes.md; folders exist only through the files inside them. Use list first when a requested path may already exist because write replaces the complete contents of the file on that path. A successful write does not export the file to the host filesystem. Source drafts are separate from saved files. read and search retrieve the IndexedDB saved copy; read_active_source retrieves raw source, including unsaved edits. get_reader_state reports source.dirty when an editable source is available. Use read_active_source then edit_active_source when asked to edit the current source; copy its fileId and opaque version string unchanged as expectedVersion. Do not calculate or reuse a version from an earlier read. Draft edits update the page but do not save the file. The reader uses Save to persist a draft. Do not use write as a substitute for saving an existing unsaved draft. Report whether you changed a draft or saved a file accurately. diff --git a/ui-packages/web/src/features/agent/tool-types.ts b/ui-packages/web/src/features/agent/tool-types.ts index cfe2846..a4719f4 100644 --- a/ui-packages/web/src/features/agent/tool-types.ts +++ b/ui-packages/web/src/features/agent/tool-types.ts @@ -2,14 +2,14 @@ import type { FileCollection, PreviewKind } from '../../core/files' import type { FileRef } from '../../core/reader-state' export type ReadRange = { unit: 'line' | 'page'; start: number; end: number } -export type ListInput = { name?: string; cursor?: string } +export type ListInput = { path?: string; cursor?: string } export type SearchInput = { query: string; fileId?: string; cursor?: string } export type ReadInput = { fileId: string; range?: ReadRange; cursor?: string } export type SourceLineRange = { unit: 'line'; start: number; end: number } export type ReadActiveSourceInput = { range?: SourceLineRange; cursor?: string } export type ReadActiveSourceResult = { fileId: string - name: string + path: string version: string range: SourceLineRange | null content: string @@ -23,17 +23,17 @@ export type EditActiveSourceInput = { } export type EditActiveSourceResult = { version: string } export type AnalyzeImageInput = { fileId: string; question?: string } -export type AnalyzeImageResult = { fileId: string; name: string; analysis: string } +export type AnalyzeImageResult = { fileId: string; path: string; analysis: string } export type FileEntry = FileRef & { collection: FileCollection type: PreviewKind textReadable: boolean reason?: string } -export type FileIssue = { fileId: string; name: string; reason: string } +export type FileIssue = { fileId: string; path: string; reason: string } export type SearchMatch = { fileId: string - name: string + path: string range: ReadRange excerpt: string } @@ -45,7 +45,7 @@ export type SearchResult = { } export type ReadResult = { fileId: string - name: string + path: string range: ReadRange | null content: string next: ReadInput | null diff --git a/ui-packages/web/src/features/agent/tools.ts b/ui-packages/web/src/features/agent/tools.ts index 3b22dc8..950fec5 100644 --- a/ui-packages/web/src/features/agent/tools.ts +++ b/ui-packages/web/src/features/agent/tools.ts @@ -69,13 +69,13 @@ export const createReaderTools = ( const write = { ...piWrite, description: - 'Create or completely overwrite one UTF-8 text file in the browser workspace. Use a root-level file name such as notes.md; folders are not available.', + 'Create or completely overwrite one UTF-8 text file in the browser workspace. Use a workspace path such as notes.md or docs/notes.md; folders follow from the path.', } const tools = [ bind( 'list', - 'List workspace files and chat attachments, including whether their text is readable. Follow next to continue.', - Type.Object({ name: Type.Optional(Type.String()), cursor }), + 'List workspace files and chat attachments by path, including whether their text is readable. path filters to paths containing that text. Follow next to continue.', + Type.Object({ path: Type.Optional(Type.String()), cursor }), documents.list, ), bind( diff --git a/ui-packages/web/src/features/agent/workspace-write-env.test.ts b/ui-packages/web/src/features/agent/workspace-write-env.test.ts index d228586..726f2e1 100644 --- a/ui-packages/web/src/features/agent/workspace-write-env.test.ts +++ b/ui-packages/web/src/features/agent/workspace-write-env.test.ts @@ -5,6 +5,7 @@ import { withAbortSignal, } from '@earendil-works/pi-agent-core' import { describe, expect, it, vi } from 'vitest' +import { rootSources } from '../../core/files' import { getStoredFileContent, importStoredFiles, @@ -40,14 +41,14 @@ describe('browser workspace write environment', () => { expect(created.content).toEqual([ { type: 'text', text: 'Successfully wrote to Study notes.md' }, ]) - const first = (await listStoredFiles()).find(file => file.name === 'Study notes.md') + const first = (await listStoredFiles()).find(file => file.path === 'Study notes.md') if (!first) throw new Error('Written file is missing') expect(first).toMatchObject({ collection: 'files', previewKind: 'markdown', revision: 1 }) expect(first.size).toBe(new TextEncoder().encode('# 第一版').byteLength) await executeWrite('/workspace/study NOTES.md', '# Final') const second = (await listStoredFiles()).find(file => file.id === first.id) - expect(second).toMatchObject({ name: 'study NOTES.md', revision: 2 }) + expect(second).toMatchObject({ path: 'study NOTES.md', revision: 2 }) expect(await (await getStoredFileContent(first.id))?.text()).toBe('# Final') }) @@ -55,7 +56,7 @@ describe('browser workspace write environment', () => { await executeWrite('report.html', '
Report
') await executeWrite('component.tsx', 'export const Value = 1') const attachment = await importStoredFiles( - [new File(['draft'], 'chat.txt', { type: 'text/plain' })], + rootSources([new File(['draft'], 'chat.txt', { type: 'text/plain' })]), 'keep', 'attachments', ) @@ -64,18 +65,32 @@ describe('browser workspace write environment', () => { await executeWrite('chat.txt', 'revised') const files = await listStoredFiles() - expect(files.find(file => file.name === 'report.html')?.previewKind).toBe('html') - expect(files.find(file => file.name === 'component.tsx')?.previewKind).toBe('text') + expect(files.find(file => file.path === 'report.html')?.previewKind).toBe('html') + expect(files.find(file => file.path === 'component.tsx')?.previewKind).toBe('text') expect(files.find(file => file.id === attachmentId)).toMatchObject({ collection: 'attachments', revision: 2, }) }) - it('rejects nested and external paths, binary writes and cancelled calls', async () => { - await expect(executeWrite('../outside.md', 'blocked')).rejects.toThrow('workspace root') - await expect(executeWrite('folder/nested.md', 'blocked')).rejects.toThrow('workspace root') - await expect(executeWrite('/outside.md', 'blocked')).rejects.toThrow('workspace root') + it('writes into folders named by the path', async () => { + await executeWrite('/workspace/docs/notes.md', '# Nested') + + const nested = (await listStoredFiles()).find(file => file.path === 'docs/notes.md') + if (!nested) throw new Error('Nested file is missing') + expect(await (await getStoredFileContent(nested.id))?.text()).toBe('# Nested') + await expect(executeWrite('docs', 'blocked')).rejects.toThrow('where a folder is') + }) + + it('rejects traversal and external paths, binary writes and cancelled calls', async () => { + for (const path of [ + '../outside.md', + 'docs/../outside.md', + '/outside.md', + 'docs//a.md', + 'a\\b.md', + ]) + await expect(executeWrite(path, 'blocked')).rejects.toThrow('without parent traversal') const env = createWorkspaceWriteEnv(writeStoredTextFile) await expect( diff --git a/ui-packages/web/src/features/agent/workspace-write-env.ts b/ui-packages/web/src/features/agent/workspace-write-env.ts index aada544..6d21cae 100644 --- a/ui-packages/web/src/features/agent/workspace-write-env.ts +++ b/ui-packages/web/src/features/agent/workspace-write-env.ts @@ -8,28 +8,22 @@ import { ok, toError, } from '@earendil-works/pi-agent-core' +import { baseName, containsControlCharacter, isWorkspacePath } from '../../core/files' import { listStoredFiles } from '../../data/file-store' import type { WorkspaceTextWriter } from './local-tools' const root = '/workspace' -const fileName = (path: string) => { +const relativePath = (path: string) => { const relative = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path.replace(/^\.\//, '') - if ( - !relative || - path === root || - (path.startsWith('/') && !path.startsWith(`${root}/`)) || - relative.includes('/') || - relative.includes('\\') || - relative === '.' || - relative === '..' || - [...relative].some(character => character.charCodeAt(0) < 32) - ) + // An absolute path outside the workspace keeps its leading '/', which the check rejects. The + // model must also stay clear of characters that read as separators or are invisible. + if (!isWorkspacePath(relative) || relative.includes('\\') || containsControlCharacter(relative)) throw new FileError( 'invalid', - 'Use one file name in the workspace root without parent traversal.', + 'Use a relative workspace path such as notes.md or docs/notes.md without parent traversal.', path, ) return relative @@ -61,9 +55,9 @@ const unsupported = async () => ) const metadataFor = async (path: string) => { - const requested = fileName(path) + const requested = relativePath(path) const metadata = (await listStoredFiles()).find( - file => file.name.toLowerCase() === requested.toLowerCase(), + file => file.path.toLowerCase() === requested.toLowerCase(), ) if (!metadata) throw new FileError('not_found', `File not found: ${requested}`, path) return metadata @@ -71,9 +65,9 @@ const metadataFor = async (path: string) => { export const createWorkspaceWriteEnv = (writeTextFile: WorkspaceTextWriter): ExecutionEnv => ({ cwd: root, - absolutePath: (path, context) => attempt(path, () => `${root}/${fileName(path)}`, context), + absolutePath: (path, context) => attempt(path, () => `${root}/${relativePath(path)}`, context), canonicalPath: (path, context) => - attempt(path, async () => `${root}/${(await metadataFor(path)).name}`, context), + attempt(path, async () => `${root}/${(await metadataFor(path)).path}`, context), exists: (path, context) => attempt( path, @@ -94,8 +88,8 @@ export const createWorkspaceWriteEnv = (writeTextFile: WorkspaceTextWriter): Exe async () => { const metadata = await metadataFor(path) return { - name: metadata.name, - path: `${root}/${metadata.name}`, + name: baseName(metadata.path), + path: `${root}/${metadata.path}`, kind: 'file', size: metadata.size, mtimeMs: metadata.lastModified, @@ -109,7 +103,7 @@ export const createWorkspaceWriteEnv = (writeTextFile: WorkspaceTextWriter): Exe async () => { if (typeof content !== 'string') throw new FileError('not_supported', 'Only UTF-8 text content can be written.', path) - await writeTextFile(fileName(path), content, context.abortSignal) + await writeTextFile(relativePath(path), content, context.abortSignal) }, context, ), diff --git a/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx b/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx index 7142d84..4a339d4 100644 --- a/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx +++ b/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx @@ -553,7 +553,7 @@ describe('conversation', () => { } const sent = body.messages.find(message => message.role === 'user') expect(sent?.content[0]?.text).toBe('Review the attached workspace files.') - expect(sent?.content[1]?.text).toContain('"name":"Chat notes.md"') + expect(sent?.content[1]?.text).toContain('"path":"Chat notes.md"') expect(sent?.content[1]?.text).toContain('"fileId":') expect(String(requests[0]?.body)).not.toContain('private attachment content') diff --git a/ui-packages/web/src/features/conversation/use-draft-attachments.ts b/ui-packages/web/src/features/conversation/use-draft-attachments.ts index 5de0afe..f6f26a1 100644 --- a/ui-packages/web/src/features/conversation/use-draft-attachments.ts +++ b/ui-packages/web/src/features/conversation/use-draft-attachments.ts @@ -1,7 +1,7 @@ import { nanoid } from 'nanoid' import { useCallback, useRef, useState } from 'react' import type { ConversationAttachment } from '../../core/agent/reader-message' -import type { ImportResult } from '../../core/files' +import { baseName, type ImportResult, type StoredFileMetadata } from '../../core/files' export type DraftAttachment = | { key: string; file: File; status: 'adding' } @@ -12,9 +12,26 @@ type AddWorkspaceAttachments = (files: readonly File[]) => Promise const maximumDraftAttachments = 10 +// The message keeps a snapshot of what the reader attached, not the library record itself. +const attachmentFrom = ({ + id, + path, + mediaType, + previewKind, + size, +}: StoredFileMetadata): ConversationAttachment => ({ + id, + name: baseName(path), + mediaType, + previewKind, + size, +}) + const rejectionText = (reason: ImportResult['rejected'][number]['reason']) => { if (reason === 'file-too-large') return 'File is over 200 MiB.' if (reason === 'library-full') return 'The 1 GiB workspace limit is full.' + if (reason === 'invalid-path') return 'The file name cannot be stored.' + if (reason === 'path-conflict') return 'A folder in the workspace has the same name.' return 'The browser could not store this file.' } @@ -64,7 +81,8 @@ export const useDraftAttachments = (importFiles: AddWorkspaceAttachments) => { const index = pending.findIndex(candidate => candidate.key === item.key) if (index < 0 || item.status !== 'adding') return item const metadata = imported.get(index) - if (metadata) return { key: item.key, metadata, status: 'ready' } + if (metadata) + return { key: item.key, metadata: attachmentFrom(metadata), status: 'ready' } return { key: item.key, file: item.file, @@ -111,7 +129,7 @@ export const useDraftAttachments = (importFiles: AddWorkspaceAttachments) => { item.key !== key || item.status !== 'adding' ? item : metadata - ? { key, metadata, status: 'ready' } + ? { key, metadata: attachmentFrom(metadata), status: 'ready' } : { key, file: failed.file, diff --git a/ui-packages/web/src/features/reader/csv-reader.test.tsx b/ui-packages/web/src/features/reader/csv-reader.test.tsx index 54a36c1..a8a9eed 100644 --- a/ui-packages/web/src/features/reader/csv-reader.test.tsx +++ b/ui-packages/web/src/features/reader/csv-reader.test.tsx @@ -7,7 +7,7 @@ vi.mock('../../shell/workspace-context', () => ({ useReaderBinding: vi.fn() })) const file: StoredFileMetadata = { id: 'sightings', - name: 'sightings.csv', + path: 'sightings.csv', mediaType: 'text/csv', previewKind: 'text', size: 64, diff --git a/ui-packages/web/src/features/reader/document-tab-bar/index.tsx b/ui-packages/web/src/features/reader/document-tab-bar/index.tsx index d0adbae..be55d42 100644 --- a/ui-packages/web/src/features/reader/document-tab-bar/index.tsx +++ b/ui-packages/web/src/features/reader/document-tab-bar/index.tsx @@ -5,7 +5,7 @@ import { type RefObject, useLayoutEffect, useRef } from 'react' import { OpenDocuments } from './open-documents' import styles from './style.module.scss' -export type DocumentTabItem = { id: string; name: string; dirty: boolean } +export type DocumentTabItem = { id: string; label: string; title: string; dirty: boolean } type DocumentTabBarProps = { items: readonly DocumentTabItem[] @@ -82,10 +82,10 @@ const DocumentTab = ({ - {item.name} + {item.label} {item.dirty && ( ● @@ -95,7 +95,7 @@ const DocumentTab = ({ )} diff --git a/ui-packages/web/src/features/reader/docx-reader.test.tsx b/ui-packages/web/src/features/reader/docx-reader.test.tsx index 6bb7a24..33f6a21 100644 --- a/ui-packages/web/src/features/reader/docx-reader.test.tsx +++ b/ui-packages/web/src/features/reader/docx-reader.test.tsx @@ -26,7 +26,7 @@ const converts = (conversion: Partial) => { const file: StoredFileMetadata = { id: 'report', - name: '季度报告.docx', + path: '季度报告.docx', mediaType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', previewKind: 'docx', size: 2048, diff --git a/ui-packages/web/src/features/reader/docx-reader.tsx b/ui-packages/web/src/features/reader/docx-reader.tsx index 5fdaaef..55d47f9 100644 --- a/ui-packages/web/src/features/reader/docx-reader.tsx +++ b/ui-packages/web/src/features/reader/docx-reader.tsx @@ -59,7 +59,7 @@ export const DocxReader = ({ : { id: document.id, revision: document.revision, - result: convertDocument(blob, document.name), + result: convertDocument(blob, document.path), } if (pending !== cached) { conversion.current = pending @@ -72,10 +72,10 @@ export const DocxReader = ({ return () => { current = false } - }, [blob, document.id, document.name, document.revision]) + }, [blob, document.id, document.path, document.revision]) if (state.status === 'loading') - return
Opening {document.name}…
+ return
Opening {document.path}…
if (state.status === 'error') return (
diff --git a/ui-packages/web/src/features/reader/file-preview.tsx b/ui-packages/web/src/features/reader/file-preview.tsx index aace32e..7b70f4f 100644 --- a/ui-packages/web/src/features/reader/file-preview.tsx +++ b/ui-packages/web/src/features/reader/file-preview.tsx @@ -78,7 +78,7 @@ export const FilePreview = ({ return (

Preview unavailable

-

{document.name}

+

{document.path}

{formatBytes(document.size)}

This file is stored locally and can be used as context in a later iteration.

@@ -97,7 +97,7 @@ export const FilePreview = ({ state.document.id !== document.id || (!textReader && state.document.revision !== document.revision) ) - return
Opening {document.name}…
+ return
Opening {document.path}…
if (textReader) return ( @@ -140,7 +140,7 @@ export const FilePreview = ({ if (document.previewKind === 'pdf') { const source = pdfSources.current.get(document.id) if (!source || source.revision !== document.revision) - return
Opening {document.name}…
+ return
Opening {document.path}…
return ( Preparing PDF preview…
}> {