Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions ui-packages/web/src/core/agent/reader-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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),
}))
Expand Down
10 changes: 7 additions & 3 deletions ui-packages/web/src/core/document-text.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down Expand Up @@ -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(<Markdown variant="reader" text={source} />)
Expand All @@ -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,
Expand Down
59 changes: 56 additions & 3 deletions ui-packages/web/src/core/file-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -24,7 +24,60 @@ const writableFile = (write: (data: Blob) => void): FileSystemFileHandle =>
}) as unknown as FileSystemWritableFileStream,
}) as FileSystemFileHandle

type FakeFolder = Map<string, Blob | FakeFolder>

// 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<string, Blob | FakeFolder>([
['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 = {
Expand All @@ -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()
Expand Down
29 changes: 20 additions & 9 deletions ui-packages/web/src/core/file-export.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { StoredFileMetadata } from './files'
import { baseName, type StoredFileMetadata } from './files'

type FileSystemPermissionMode = 'read' | 'readwrite'
type FileSystemPermissionState = 'denied' | 'granted' | 'prompt'
Expand All @@ -22,7 +22,7 @@ type FilePickerWindow = Window & {
showSaveFilePicker?: (options?: SaveFilePickerOptions) => Promise<FileSystemFileHandle>
}

export type ExportedFileVersion = Pick<StoredFileMetadata, 'id' | 'name' | 'revision'>
export type ExportedFileVersion = Pick<StoredFileMetadata, 'id' | 'path' | 'revision'>

export type FolderExportRecord = {
id: 'files'
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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)
Expand Down
51 changes: 42 additions & 9 deletions ui-packages/web/src/core/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type FileCollection = 'files' | 'attachments'

export type StoredFileMetadata = {
id: string
name: string
path: string
collection?: FileCollection
mediaType: string
previewKind: PreviewKind
Expand All @@ -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
Expand All @@ -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] ?? ''
Expand Down Expand Up @@ -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<string[]>((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<string[]>((duplicates, { path }) => {
const normalized = path.toLowerCase()
if (paths.has(normalized) && !duplicates.includes(path)) duplicates.push(path)
paths.add(normalized)
return duplicates
}, [])
}
2 changes: 1 addition & 1 deletion ui-packages/web/src/core/reader-state.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 3 additions & 2 deletions ui-packages/web/src/data/conversation-store.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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 = {
Expand Down Expand Up @@ -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 () => {
Expand Down
Loading