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: 7 additions & 1 deletion ui-packages/web/src/core/document-text.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { render } from '@testing-library/react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { Markdown } from '../components/markdown'
import { getStoredFile, importStoredFiles, writeStoredTextFile } from '../data/file-store'
import {
getStoredFile,
importStoredFiles,
moveStoredFile,
writeStoredTextFile,
} from '../data/file-store'
import { createReaderDocumentAccess } from '../features/agent/create-reader-agent'
import { createDocumentTools } from '../features/agent/document-tools'
import { createLocalTools } from '../features/agent/local-tools'
Expand Down Expand Up @@ -101,6 +106,7 @@ describe('formula and diagram source context', () => {
viewport: readViewport(container, container),
}),
writeStoredTextFile,
moveStoredFile,
)
const documents = createDocumentTools(
createReaderDocumentAccess(createPdfRuntime(getStoredFile)),
Expand Down
51 changes: 51 additions & 0 deletions ui-packages/web/src/data/file-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getStoredFileContent,
importStoredFiles,
listStoredFiles,
moveStoredFile,
removeStoredFile,
updateStoredTextFile,
writeStoredTextFile,
Expand Down Expand Up @@ -326,6 +327,56 @@ describe('local file store', () => {
expect(kept.imported[0]?.metadata.path).toBe('a\\b.md')
})

it('moves a file to a new path, keeping its id, revision and content', async () => {
const [notes] = (
await importStoredFiles(rootSources([textFile('Notes.txt', 'kept')]), 'keep')
).imported.map(item => item.metadata)
if (!notes) throw new Error('Expected the notes file')

const { from, metadata } = await moveStoredFile(notes.id, 'docs/notes.md')

expect(from).toBe('Notes.txt')
expect(metadata).toMatchObject({
id: notes.id,
path: 'docs/notes.md',
revision: notes.revision,
previewKind: 'markdown',
})
expect(await (await getStoredFileContent(notes.id))?.text()).toBe('kept')
await expect(moveStoredFile(notes.id, 'docs/NOTES.md')).resolves.toMatchObject({
metadata: { path: 'docs/NOTES.md' },
})
})

it('refuses a move that would take another path, cross a folder or move an attachment', async () => {
const imported = await importStoredFiles(
[
{ path: 'a.md', file: textFile('a.md', 'a') },
{ path: 'docs/b.md', file: textFile('b.md', 'b') },
],
'keep',
)
const [a] = imported.imported.map(item => item.metadata)
const attachment = await importStoredFiles(
rootSources([textFile('chat.md', 'c')]),
'keep',
'attachments',
)
if (!a) throw new Error('Expected a.md')
const before = await listStoredFiles()

for (const [id, path, reason] of [
[a.id, 'DOCS/b.md', 'path-taken'],
[a.id, 'docs', 'path-conflict'],
[a.id, 'docs/b.md/a.md', 'path-conflict'],
[a.id, '../a.md', 'invalid-path'],
[attachment.addedIds[0] ?? '', 'docs/chat.md', 'attachment'],
['missing', 'x.md', 'missing'],
])
await expect(moveStoredFile(id ?? '', path ?? '')).rejects.toMatchObject({ reason })
expect(await listStoredFiles()).toEqual(before)
})

it('recognizes common UTF-8 document formats with application MIME types as text', async () => {
await importStoredFiles(
rootSources([new File(['{"local":true}'], 'Context.json', { type: 'application/json' })]),
Expand Down
56 changes: 56 additions & 0 deletions ui-packages/web/src/data/file-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,62 @@ export const updateStoredTextFile = async (
}
}

export type MoveRejectionReason =
| 'missing'
| 'invalid-path'
| 'path-taken'
| 'path-conflict'
| 'attachment'

const moveMessages: Record<MoveRejectionReason, string> = {
missing: 'The file is no longer in the workspace.',
'invalid-path': 'Use a relative path whose segments are not empty, "." or "..".',
'path-taken': 'Another file already has that path. Choose another path or ask the reader first.',
'path-conflict': 'The path would place a file where a folder is, or inside a file.',
attachment: 'Chat attachments stay where they are and cannot be moved.',
}

export class MoveRejectedError extends Error {
constructor(readonly reason: MoveRejectionReason) {
super(moveMessages[reason])
}
}

// Moving changes where a file lives, not what it holds, so the revision stays: a source draft
// saved later still matches the file it was read from.
export const moveStoredFile = async (id: string, path: string, signal?: AbortSignal) => {
signal?.throwIfAborted()
const database = await openFileDatabase()
const transaction = database.transaction('files', 'readwrite')
const files = transaction.objectStore('files')
const all = await files.getAll()
const current = all.find(file => file.id === id)
const others = all.filter(file => file.id !== id).map(file => file.path.toLowerCase())
const reason: MoveRejectionReason | null = !current
? 'missing'
: current.collection === 'attachments'
? 'attachment'
: !isWorkspacePath(path)
? 'invalid-path'
: others.includes(path.toLowerCase())
? 'path-taken'
: shadows(path, others)
? 'path-conflict'
: null
if (reason || !current) {
await transaction.done
throw new MoveRejectedError(reason ?? 'missing')
}
signal?.throwIfAborted()
const metadata: StoredFileMetadata = {
...current,
path,
previewKind: previewKindFor(path, current.mediaType),
}
await Promise.all([files.put(metadata), transaction.done])
return { from: current.path, metadata }
}

export const removeStoredFile = async (id: string) => {
const database = await openFileDatabase()
const transaction = database.transaction(['files', 'contents'], 'readwrite')
Expand Down
11 changes: 8 additions & 3 deletions ui-packages/web/src/features/agent/create-reader-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getStoredFileContent,
importStoredFiles,
listStoredFiles,
moveStoredFile,
writeStoredTextFile,
} from '../../data/file-store'
import { modelConfig } from '../../test/model-config'
Expand Down Expand Up @@ -77,7 +78,7 @@ const call = (name: string, args: unknown) =>
{ headers: { 'Content-Type': 'text/event-stream' } },
)
const emptyState = (): ReaderState => ({ openFiles: [], activeFile: null, viewport: null })
const localTools = () => createLocalTools(emptyState, writeStoredTextFile)
const localTools = () => createLocalTools(emptyState, writeStoredTextFile, moveStoredFile)
const session = { id: 'test-conversation', messages: [], ...resolveModelSelection(config) }

describe('reader agent', () => {
Expand Down Expand Up @@ -132,7 +133,11 @@ describe('reader agent', () => {
return reply('Saved as Study notes.html.')
})
const writer = vi.fn(writeStoredTextFile)
const agent = createReaderAgent(config, createLocalTools(emptyState, writer), session)
const agent = createReaderAgent(
config,
createLocalTools(emptyState, writer, moveStoredFile),
session,
)

await agent.prompt('Save this as an HTML file')

Expand Down Expand Up @@ -179,7 +184,7 @@ describe('reader agent', () => {
})
const agent = createReaderAgent(
config,
createLocalTools(() => state, writeStoredTextFile),
createLocalTools(() => state, writeStoredTextFile, moveStoredFile),
session,
)
await agent.prompt('Explain the current paragraph')
Expand Down
22 changes: 22 additions & 0 deletions ui-packages/web/src/features/agent/local-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getStoredFile,
importStoredFiles,
listStoredFiles,
moveStoredFile,
removeStoredFile,
writeStoredTextFile,
} from '../../data/file-store'
Expand Down Expand Up @@ -49,6 +50,25 @@ const budget = (result: unknown) =>
expect(new TextEncoder().encode(JSON.stringify(result)).length).toBeLessThanOrEqual(16 * 1024)

describe('local reader tools', () => {
it('moves a file to a path the model names, reporting where it came from', async () => {
const id = await add('Draft.txt', 'draft')
const local = createLocalTools(
() => ({ openFiles: [], activeFile: null, viewport: null }),
writeStoredTextFile,
moveStoredFile,
)

await expect(local.move({ fileId: id, path: '/workspace/notes/draft.md' })).resolves.toEqual({
fileId: id,
from: 'Draft.txt',
path: 'notes/draft.md',
})
await expect(local.move({ fileId: id, path: '../draft.md' })).rejects.toThrow(
'without parent traversal',
)
expect((await listStoredFiles()).find(file => file.id === id)?.path).toBe('notes/draft.md')
})

it('lists capabilities, filters names, and paginates without losing files', async () => {
await importStoredFiles(
rootSources(
Expand Down Expand Up @@ -299,6 +319,7 @@ describe('active source tools', () => {
const local = createLocalTools(
() => ({ openFiles: [], activeFile: null, viewport: null }),
writeStoredTextFile,
moveStoredFile,
{
get: () => source,
replace: (_fileId, _version, content) =>
Expand Down Expand Up @@ -329,6 +350,7 @@ describe('active source tools', () => {
const local = createLocalTools(
() => ({ openFiles: [], activeFile: null, viewport: null }),
writeStoredTextFile,
moveStoredFile,
{
get: () => source,
replace: (_fileId, _version, content) =>
Expand Down
14 changes: 14 additions & 0 deletions ui-packages/web/src/features/agent/local-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ import {
type EditActiveSourceInput,
type EditActiveSourceResult,
LocalToolError,
type MoveInput,
type MoveResult,
type ReadActiveSourceInput,
type ReadActiveSourceResult,
type SourceLineRange,
} from './tool-types'
import { agentWorkspacePath } from './workspace-write-env'

type SourceCursor = {
operation: 'read-active-source'
Expand All @@ -47,6 +50,12 @@ export type WorkspaceTextWriter = (
signal?: AbortSignal,
) => Promise<StoredFileMetadata>

export type WorkspaceFileMover = (
fileId: string,
path: string,
signal?: AbortSignal,
) => Promise<{ from: string; metadata: StoredFileMetadata }>

export type ActiveSourceSnapshot = {
fileId: string
path: string
Expand Down Expand Up @@ -162,10 +171,15 @@ const editActiveSource = (
export const createLocalTools = (
getReaderState: () => ReaderState,
writeTextFile: WorkspaceTextWriter,
moveFile: WorkspaceFileMover,
activeSource?: ActiveSourceAccess,
) => ({
get_reader_state: getReaderState,
writeTextFile,
move: async (input: MoveInput, signal?: AbortSignal): Promise<MoveResult> => {
const { from, metadata } = await moveFile(input.fileId, agentWorkspacePath(input.path), signal)
return { fileId: metadata.id, from, path: metadata.path }
},
read_active_source: (input?: ReadActiveSourceInput) => {
if (!activeSource) throw new LocalToolError('Active source editing is unavailable.')
return readActiveSource(activeSource, input)
Expand Down
2 changes: 1 addition & 1 deletion ui-packages/web/src/features/agent/system-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Use tools when a question depends on documents. Read an available skill when its

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. 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.
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. To organize or rename existing files, use move rather than writing copies.

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.

Expand Down
2 changes: 2 additions & 0 deletions ui-packages/web/src/features/agent/tool-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export type EditActiveSourceInput = {
newText: string
}
export type EditActiveSourceResult = { version: string }
export type MoveInput = { fileId: string; path: string }
export type MoveResult = { fileId: string; from: string; path: string }
export type AnalyzeImageInput = { fileId: string; question?: string }
export type AnalyzeImageResult = { fileId: string; path: string; analysis: string }
export type FileEntry = FileRef & {
Expand Down
6 changes: 6 additions & 0 deletions ui-packages/web/src/features/agent/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ export const createReaderTools = (
}),
local.edit_active_source,
),
bind(
'move',
'Move or rename one workspace file by fileId to a new path such as docs/notes.md. Folders follow from the path. Content, the file id and open tabs are kept. Fails when another file already has that path; chat attachments cannot be moved.',
Type.Object({ fileId, path: Type.String({ minLength: 1 }) }),
local.move,
),
write,
]
return tools
Expand Down
10 changes: 6 additions & 4 deletions ui-packages/web/src/features/agent/workspace-write-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import type { WorkspaceTextWriter } from './local-tools'

const root = '/workspace'

const relativePath = (path: string) => {
// Every path the model names goes through here, so write and move accept the same paths.
export const agentWorkspacePath = (path: string) => {
const relative = path.startsWith(`${root}/`)
? path.slice(root.length + 1)
: path.replace(/^\.\//, '')
Expand Down Expand Up @@ -55,7 +56,7 @@ const unsupported = async <T>() =>
)

const metadataFor = async (path: string) => {
const requested = relativePath(path)
const requested = agentWorkspacePath(path)
const metadata = (await listStoredFiles()).find(
file => file.path.toLowerCase() === requested.toLowerCase(),
)
Expand All @@ -65,7 +66,8 @@ const metadataFor = async (path: string) => {

export const createWorkspaceWriteEnv = (writeTextFile: WorkspaceTextWriter): ExecutionEnv => ({
cwd: root,
absolutePath: (path, context) => attempt(path, () => `${root}/${relativePath(path)}`, context),
absolutePath: (path, context) =>
attempt(path, () => `${root}/${agentWorkspacePath(path)}`, context),
canonicalPath: (path, context) =>
attempt(path, async () => `${root}/${(await metadataFor(path)).path}`, context),
exists: (path, context) =>
Expand Down Expand Up @@ -103,7 +105,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(relativePath(path), content, context.abortSignal)
await writeTextFile(agentWorkspacePath(path), content, context.abortSignal)
},
context,
),
Expand Down
3 changes: 2 additions & 1 deletion ui-packages/web/src/features/reader/document-tabs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import userEvent from '@testing-library/user-event'
import { useRef } from 'react'
import { describe, expect, it, vi } from 'vitest'
import type { StoredFileMetadata } from '../../core/files'
import { updateStoredTextFile, writeStoredTextFile } from '../../data/file-store'
import { moveStoredFile, updateStoredTextFile, writeStoredTextFile } from '../../data/file-store'
import type { Workspace } from '../../shell/use-workspace'
import { WorkspaceProvider } from '../../shell/workspace-context'
import { createWorkspaceActions, createWorkspaceStore } from '../../shell/workspace-store'
Expand Down Expand Up @@ -81,6 +81,7 @@ const TestTabs = ({
workspace={workspace}
rootRef={rootRef}
writeTextFile={writeStoredTextFile}
moveFile={moveStoredFile}
updateTextFile={updateTextFile}
>
<div ref={rootRef}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { StoredFileMetadata } from '../../../core/files'
import {
getStoredFileContent,
moveStoredFile,
updateStoredTextFile,
writeStoredTextFile,
} from '../../../data/file-store'
Expand Down Expand Up @@ -70,6 +71,7 @@ const Harness = ({
workspace={workspace}
rootRef={rootRef}
writeTextFile={writeStoredTextFile}
moveFile={moveStoredFile}
updateTextFile={updateStoredTextFile}
>
<div ref={rootRef}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { StoredFileMetadata } from '../../../core/files'
import {
getStoredFile,
getStoredFileContent,
moveStoredFile,
updateStoredTextFile,
writeStoredTextFile,
} from '../../../data/file-store'
Expand Down Expand Up @@ -62,6 +63,7 @@ const Harness = ({
workspace={workspace}
rootRef={rootRef}
writeTextFile={writeStoredTextFile}
moveFile={moveStoredFile}
updateTextFile={updateStoredTextFile}
>
<div ref={rootRef}>
Expand Down
Loading