fix: pass workspace directory in Files API requests (#1588)
* fix: pass effective workspace directory in Files API requests The web Files API used useDirectoryStore.currentDirectory as the workspace root, but the FilesView's effective directory comes from useEffectiveDirectory() which can differ (e.g. worktree sessions). When they diverged the server rejected file reads with 'Path is outside of active workspace'. Add directory override to FileReadOptions so callers can pass the effective directory per-call. The FilesView now passes its root (from useEffectiveDirectory) through readFile, statFile, image/PDF URLs, and the desktop image fallback. The server receives the correct workspace root via x-opencode-directory header or directory query parameter. Fixes #1456 * fix: cover files workspace directory regressions * fix: sync directory store on draft session and forward cache options The content cache wrapper in RuntimeAPIProvider was dropping the options parameter (including the per-call directory override) when making internal statFile and readFreshFile calls during cache validation and misses. This caused the underlying web API to fall back to getDirectory() which reads useDirectoryStore.currentDirectory. Additionally, openNewSessionDraft, setNewSessionDraftTarget, and overrideNewSessionDraftTarget updated the draft's directory without ever syncing useDirectoryStore. Since the web API's getDirectory() reads from that store, it returned the stale previous-project directory during draft sessions, causing 'Path is outside of active workspace' errors when opening files. Forward options through all internal calls in the content cache wrapper, and sync useDirectoryStore via setDirectory() whenever the draft session directory changes. --------- Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
This commit is contained in:
committed by
GitHub
co-authored by
Bohdan Triapitsyn
parent
5773297ecf
commit
71bae089a7
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { RuntimeUrlQuery, RuntimeUrlResolver } from '@openchamber/ui/lib/runtime-url';
|
||||
|
||||
const runtimeFetchMock = vi.fn();
|
||||
|
||||
vi.mock('@openchamber/ui/lib/runtime-fetch', () => ({
|
||||
runtimeFetch: runtimeFetchMock,
|
||||
}));
|
||||
|
||||
const toUrl = (path: string, query?: RuntimeUrlQuery): string => {
|
||||
const params = query instanceof URLSearchParams ? query : new URLSearchParams();
|
||||
const queryString = params.toString();
|
||||
return queryString ? `${path}?${queryString}` : path;
|
||||
};
|
||||
|
||||
const urls: RuntimeUrlResolver = {
|
||||
api: toUrl,
|
||||
authenticatedAsset: toUrl,
|
||||
auth: toUrl,
|
||||
health: (query?: RuntimeUrlQuery) => toUrl('/health', query),
|
||||
rawFile: (path: string) => toUrl('/api/fs/raw', new URLSearchParams({ path })),
|
||||
sse: toUrl,
|
||||
websocket: toUrl,
|
||||
};
|
||||
|
||||
describe('createWebFilesAPI', () => {
|
||||
it('uses per-call workspace directory for stat and read requests', async () => {
|
||||
const { createWebFilesAPI } = await import('./files');
|
||||
const api = createWebFilesAPI({ urls, getDirectory: () => '/stale-workspace' });
|
||||
|
||||
runtimeFetchMock.mockResolvedValueOnce(Response.json({ path: '/worktree-b/file.txt', isFile: true, size: 12 }));
|
||||
await api.statFile?.('/worktree-b/file.txt', { directory: '/worktree-a' });
|
||||
|
||||
expect(runtimeFetchMock).toHaveBeenLastCalledWith('/api/fs/stat?path=%2Fworktree-b%2Ffile.txt', {
|
||||
headers: { 'x-opencode-directory': '/worktree-a' },
|
||||
});
|
||||
|
||||
runtimeFetchMock.mockResolvedValueOnce(new Response('content'));
|
||||
await api.readFile?.('/worktree-b/file.txt', { directory: '/worktree-a' });
|
||||
|
||||
expect(runtimeFetchMock).toHaveBeenLastCalledWith('/api/fs/read?path=%2Fworktree-b%2Ffile.txt', {
|
||||
cache: 'default',
|
||||
headers: { 'x-opencode-directory': '/worktree-a' },
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the workspace directory header for downloads', async () => {
|
||||
const { createWebFilesAPI } = await import('./files');
|
||||
const api = createWebFilesAPI({ urls, getDirectory: () => '/current-workspace' });
|
||||
|
||||
runtimeFetchMock.mockResolvedValueOnce(new Response('', { status: 500 }));
|
||||
await expect(api.downloadFile?.('/current-workspace/file.txt')).rejects.toThrow('Download failed');
|
||||
|
||||
expect(runtimeFetchMock).toHaveBeenLastCalledWith('/api/fs/raw', {
|
||||
query: { path: '/current-workspace/file.txt', download: true },
|
||||
headers: { 'x-opencode-directory': '/current-workspace' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ const normalizePath = (path: string): string => path.replace(/\\/g, '/');
|
||||
|
||||
interface WebFilesAPIOptions {
|
||||
urls: RuntimeUrlResolver;
|
||||
getDirectory?: () => string | undefined;
|
||||
}
|
||||
|
||||
type WebDirectoryEntry = {
|
||||
@@ -45,7 +46,12 @@ const toDirectoryListResult = (fallbackDirectory: string, payload: WebDirectoryL
|
||||
};
|
||||
};
|
||||
|
||||
export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
const directoryHeaders = (getDirectory?: () => string | undefined, override?: string): Record<string, string> | undefined => {
|
||||
const directory = override || getDirectory?.();
|
||||
return directory ? { 'x-opencode-directory': directory } : undefined;
|
||||
};
|
||||
|
||||
export const createWebFilesAPI = ({ urls, getDirectory }: WebFilesAPIOptions): FilesAPI => ({
|
||||
async listDirectory(path: string, options): Promise<DirectoryListResult> {
|
||||
const target = normalizePath(path);
|
||||
const params = new URLSearchParams();
|
||||
@@ -56,7 +62,9 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
params.set('respectGitignore', 'true');
|
||||
}
|
||||
|
||||
const response = await runtimeFetch(urls.api('/api/fs/list', params));
|
||||
const response = await runtimeFetch(urls.api('/api/fs/list', params), {
|
||||
headers: directoryHeaders(getDirectory),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -83,7 +91,9 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
params.set('limit', String(payload.maxResults));
|
||||
}
|
||||
|
||||
const response = await runtimeFetch(urls.api('/api/find/file', params));
|
||||
const response = await runtimeFetch(urls.api('/api/find/file', params), {
|
||||
headers: directoryHeaders(getDirectory),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -103,7 +113,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
const target = normalizePath(path);
|
||||
const response = await runtimeFetch(urls.api('/api/fs/mkdir'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...directoryHeaders(getDirectory) },
|
||||
body: JSON.stringify({ path: target }),
|
||||
});
|
||||
|
||||
@@ -128,7 +138,9 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
if (options?.outsideFileGrant) {
|
||||
params.set('outsideFileGrant', options.outsideFileGrant);
|
||||
}
|
||||
const response = await runtimeFetch(urls.api('/api/fs/stat', params));
|
||||
const response = await runtimeFetch(urls.api('/api/fs/stat', params), {
|
||||
headers: directoryHeaders(getDirectory, options?.directory),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
@@ -158,6 +170,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
}
|
||||
const response = await runtimeFetch(urls.api('/api/fs/read', params), {
|
||||
cache: options?.optional ? 'no-store' : 'default',
|
||||
headers: directoryHeaders(getDirectory, options?.directory),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -173,7 +186,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
const target = normalizePath(path);
|
||||
const response = await runtimeFetch(urls.api('/api/fs/write'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...directoryHeaders(getDirectory) },
|
||||
body: JSON.stringify({ path: target, content }),
|
||||
});
|
||||
|
||||
@@ -193,7 +206,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
const target = normalizePath(path);
|
||||
const response = await runtimeFetch(urls.api('/api/fs/delete'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...directoryHeaders(getDirectory) },
|
||||
body: JSON.stringify({ path: target }),
|
||||
});
|
||||
|
||||
@@ -209,7 +222,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
async rename(oldPath: string, newPath: string): Promise<{ success: boolean; path: string }> {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/rename'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...directoryHeaders(getDirectory) },
|
||||
body: JSON.stringify({ oldPath, newPath }),
|
||||
});
|
||||
|
||||
@@ -228,7 +241,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
async revealPath(targetPath: string): Promise<{ success: boolean }> {
|
||||
const response = await runtimeFetch(urls.api('/api/fs/reveal'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...directoryHeaders(getDirectory) },
|
||||
body: JSON.stringify({ path: normalizePath(targetPath) }),
|
||||
});
|
||||
|
||||
@@ -245,6 +258,7 @@ export const createWebFilesAPI = ({ urls }: WebFilesAPIOptions): FilesAPI => ({
|
||||
const target = normalizePath(path);
|
||||
const response = await runtimeFetch('/api/fs/raw', {
|
||||
query: { path: target, download: true },
|
||||
headers: directoryHeaders(getDirectory),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Download failed (${response.status})`);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
setRuntimeUrlResolver,
|
||||
type RuntimeUrlResolver,
|
||||
} from '@openchamber/ui/lib/runtime-url';
|
||||
import { useDirectoryStore } from '@openchamber/ui/stores/useDirectoryStore';
|
||||
import { createWebTerminalAPI } from './terminal';
|
||||
import { createWebGitAPI } from './git';
|
||||
import { createWebFilesAPI } from './files';
|
||||
@@ -39,7 +40,7 @@ export const createWebAPIs = (options: WebAPIsOptions = {}): RuntimeAPIs => {
|
||||
runtime: { platform: 'web', isDesktop: false, isVSCode: false, label: 'web' },
|
||||
terminal: createWebTerminalAPI(),
|
||||
git: createWebGitAPI(),
|
||||
files: createWebFilesAPI({ urls: activeUrls }),
|
||||
files: createWebFilesAPI({ urls: activeUrls, getDirectory: () => useDirectoryStore.getState().currentDirectory }),
|
||||
settings: createWebSettingsAPI(),
|
||||
permissions: createWebPermissionsAPI(),
|
||||
notifications: createWebNotificationsAPI(),
|
||||
|
||||
Reference in New Issue
Block a user