@myrialabs/clopen 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/backend/engine/adapters/claude/environment.ts +0 -17
  2. package/backend/engine/adapters/claude/error-handler.ts +0 -4
  3. package/backend/engine/install-recipes.ts +26 -95
  4. package/backend/files/file-operations.test.ts +75 -0
  5. package/backend/files/file-operations.ts +10 -56
  6. package/backend/files/image-processing.test.ts +52 -0
  7. package/backend/files/image-processing.ts +11 -1
  8. package/backend/files/path-browsing.ts +141 -139
  9. package/backend/git/git-service.ts +13 -2
  10. package/backend/http/files-upload.test.ts +174 -0
  11. package/backend/http/files-upload.ts +27 -7
  12. package/backend/http/upload-temp-cleanup.ts +53 -0
  13. package/backend/index.ts +4 -0
  14. package/backend/mcp/remote-server.test.ts +150 -0
  15. package/backend/mcp/remote-server.ts +68 -0
  16. package/backend/terminal/pty-session-manager.ts +18 -11
  17. package/backend/ws/files/index.ts +5 -0
  18. package/backend/ws/files/reveal.ts +61 -0
  19. package/backend/ws/files/search.test.ts +115 -0
  20. package/backend/ws/files/search.ts +77 -26
  21. package/backend/ws/files/write.ts +3 -1
  22. package/backend/ws/git/branch-name.ts +170 -0
  23. package/backend/ws/git/branch.ts +15 -2
  24. package/backend/ws/git/commit-message.ts +8 -2
  25. package/backend/ws/git/index.ts +3 -1
  26. package/backend/ws/user/crud.ts +8 -4
  27. package/dist/assets/main-Ba19ADkk.js +377 -0
  28. package/dist/assets/main-CwCZzMVm.css +1 -0
  29. package/dist/index.html +2 -2
  30. package/package.json +1 -1
  31. package/shared/constants/git.ts +5 -0
  32. package/shared/types/git.ts +5 -0
  33. package/shared/types/stores/settings.ts +17 -0
  34. package/dist/assets/main-BgOiIS43.js +0 -360
  35. package/dist/assets/main-CJdJeen6.css +0 -1
@@ -1,19 +1,34 @@
1
1
  import { join, extname } from 'path';
2
+ import { readdir as fsReaddir } from 'node:fs/promises';
2
3
  import { existsSync } from 'fs';
3
4
 
4
5
  import { debug } from '$shared/utils/logger';
5
6
 
6
- // Bun-compatible readdir implementation (cross-platform)
7
+ // Cross-platform readdir using fs.promises
7
8
  async function readdir(path: string): Promise<string[]> {
8
- let proc;
9
- if (process.platform === 'win32') {
10
- proc = Bun.spawn(['cmd', '/c', 'dir', '/b', '/a', path], { stdout: 'pipe', stderr: 'ignore' });
11
- } else {
12
- proc = Bun.spawn(['ls', '-1A', path], { stdout: 'pipe', stderr: 'ignore' });
9
+ const entries = await fsReaddir(path, { withFileTypes: true });
10
+ return entries.map(e => e.name);
11
+ }
12
+
13
+ async function statIfExists(path: string): Promise<Awaited<ReturnType<ReturnType<typeof Bun.file>['stat']>> | null> {
14
+ try {
15
+ return await Bun.file(path).stat();
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ // Returns true when every visible entry is a .app bundle or the "Applications" alias —
22
+ // the signature of a DMG/installer mount, not a general-purpose volume.
23
+ async function isLikelyMacAppVolume(volumePath: string): Promise<boolean> {
24
+ try {
25
+ const entries = await readdir(volumePath);
26
+ const visible = entries.filter(e => !e.startsWith('.'));
27
+ if (visible.length === 0) return false;
28
+ return visible.every(e => e.endsWith('.app') || e === 'Applications');
29
+ } catch {
30
+ return false;
13
31
  }
14
- const result = await new Response(proc.stdout).text();
15
- // Split and clean up, removing \r characters for Windows compatibility
16
- return result.trim().split(/\r?\n/).map(line => line.trim()).filter(Boolean);
17
32
  }
18
33
 
19
34
  // Return types
@@ -29,6 +44,7 @@ export interface PathBrowseData {
29
44
  type: 'file' | 'directory';
30
45
  path: string;
31
46
  modified: string;
47
+ kind?: 'home' | 'root' | 'volume' | 'drive';
32
48
  size?: number;
33
49
  extension?: string;
34
50
  }>;
@@ -58,6 +74,16 @@ export async function handlePathBrowsing(path: string): Promise<PathBrowseData>
58
74
  targetPath = path;
59
75
  }
60
76
 
77
+ // Windows: a bare drive letter ("C:") is drive-relative — it points at the
78
+ // drive's *current* directory, not its root. Path normalization (resolve /
79
+ // realpath) and manual entry can both strip the trailing separator, which
80
+ // then makes join() produce drive-relative child paths like "C:Users" whose
81
+ // stat() fails, leaving the listing empty. Append the separator so we always
82
+ // browse the drive root.
83
+ if (/^[A-Za-z]:$/.test(targetPath)) {
84
+ targetPath += '\\';
85
+ }
86
+
61
87
  // Check if path exists (use stat instead of exists for directories)
62
88
  const file = Bun.file(targetPath);
63
89
  const stats = await file.stat();
@@ -161,165 +187,138 @@ export async function handlePathBrowsing(path: string): Promise<PathBrowseData>
161
187
 
162
188
  // Helper function to handle Unix mount points listing (Linux, macOS, etc.)
163
189
  export async function handleUnixMountPoints(): Promise<PathBrowseData> {
164
- const commonMountPoints: Array<{
190
+ const items: Array<{
165
191
  name: string;
166
192
  type: 'file' | 'directory';
167
193
  path: string;
168
194
  modified: string;
169
- size?: number;
170
- extension?: string;
195
+ kind: 'home' | 'root' | 'volume';
171
196
  }> = [];
172
197
 
173
- // Always add root filesystem
174
- const rootFile = Bun.file('/');
175
- if (await rootFile.exists()) {
176
- const stats = await rootFile.stat();
177
- commonMountPoints.push({
178
- name: 'Root (/) Filesystem',
179
- type: 'directory',
180
- path: '/',
181
- modified: stats.mtime.toISOString()
182
- });
183
- }
184
-
185
- // Add user home directory
198
+ // Home directory — all Unix platforms
186
199
  const homeDir = process.env.HOME;
187
200
  if (homeDir) {
188
- const homeFile = Bun.file(homeDir);
189
- if (await homeFile.exists()) {
190
- const stats = await homeFile.stat();
191
- commonMountPoints.push({
192
- name: 'Home Directory',
193
- type: 'directory',
194
- path: homeDir,
195
- modified: stats.mtime.toISOString()
196
- });
201
+ const stats = await statIfExists(homeDir);
202
+ if (stats?.isDirectory()) {
203
+ items.push({ name: 'Home Directory', type: 'directory', path: homeDir, modified: stats.mtime.toISOString(), kind: 'home' });
197
204
  }
198
205
  }
199
206
 
200
- // Common mount points to check
201
- const potentialMounts = [
202
- '/mnt', // Linux mount point
203
- '/media', // Linux removable media
204
- '/Volumes', // macOS mount point
205
- '/usr', // Unix system directory
206
- '/var', // Unix variable directory
207
- '/opt', // Optional software
208
- '/tmp' // Temporary directory
209
- ];
210
-
211
- for (const mountPath of potentialMounts) {
212
- try {
213
- const mountFile = Bun.file(mountPath);
214
- if (await mountFile.exists()) {
215
- const stats = await mountFile.stat();
216
- if (stats.isDirectory()) {
217
- let displayName = mountPath;
218
-
219
- // Special names for common directories
220
- switch (mountPath) {
221
- case '/mnt':
222
- displayName = 'Mount Points (/mnt)';
223
- break;
224
- case '/media':
225
- displayName = 'Media (/media)';
226
- break;
227
- case '/Volumes':
228
- displayName = 'Volumes (/Volumes)';
229
- break;
230
- case '/usr':
231
- displayName = 'System (/usr)';
232
- break;
233
- case '/var':
234
- displayName = 'Variable (/var)';
235
- break;
236
- case '/opt':
237
- displayName = 'Optional (/opt)';
238
- break;
239
- case '/tmp':
240
- displayName = 'Temporary (/tmp)';
241
- break;
207
+ if (process.platform === 'darwin') {
208
+ // macOS: enumerate /Volumes/* — skip installer/DMG mounts
209
+ const volumesStats = await statIfExists('/Volumes');
210
+ if (volumesStats?.isDirectory()) {
211
+ try {
212
+ const volumeNames = await readdir('/Volumes');
213
+ for (const name of volumeNames) {
214
+ const vPath = `/Volumes/${name}`;
215
+ try {
216
+ const vStats = await statIfExists(vPath);
217
+ if (!vStats?.isDirectory()) continue;
218
+ if (await isLikelyMacAppVolume(vPath)) continue;
219
+ items.push({ name, type: 'directory', path: vPath, modified: vStats.mtime.toISOString(), kind: 'volume' });
220
+ } catch {
221
+ // Skip inaccessible volumes
242
222
  }
243
-
244
- commonMountPoints.push({
245
- name: displayName,
246
- type: 'directory',
247
- path: mountPath,
248
- modified: stats.mtime.toISOString()
249
- });
250
223
  }
224
+ } catch {
225
+ // Skip if /Volumes is unreadable
251
226
  }
252
- } catch {
253
- // Skip inaccessible mount points
254
227
  }
255
- }
228
+ } else if (process.platform === 'linux') {
229
+ // Linux: root + /mnt/*, /media/*, /run/media/{user}/* (systemd automount)
230
+ const rootStats = await statIfExists('/');
231
+ if (rootStats?.isDirectory()) {
232
+ items.push({ name: 'Root (/) Filesystem', type: 'directory', path: '/', modified: rootStats.mtime.toISOString(), kind: 'root' });
233
+ }
256
234
 
257
- // On macOS, try to get mounted volumes from /Volumes
258
- const volumesFile = Bun.file('/Volumes');
259
- if (process.platform === 'darwin' && await volumesFile.exists()) {
260
- try {
261
- const volumeItems = await readdir('/Volumes');
262
- for (const volume of volumeItems) {
263
- const volumePath = `/Volumes/${volume}`;
264
- try {
265
- const volumeFile = Bun.file(volumePath);
266
- if (await volumeFile.exists()) {
267
- const stats = await volumeFile.stat();
268
- if (stats.isDirectory()) {
269
- commonMountPoints.push({
270
- name: `${volume} Volume`,
271
- type: 'directory',
272
- path: volumePath,
273
- modified: stats.mtime.toISOString()
274
- });
235
+ for (const base of ['/mnt', '/media']) {
236
+ const baseStats = await statIfExists(base);
237
+ if (!baseStats?.isDirectory()) continue;
238
+ try {
239
+ const entries = await readdir(base);
240
+ for (const entry of entries) {
241
+ const entryPath = `${base}/${entry}`;
242
+ try {
243
+ const entryStats = await statIfExists(entryPath);
244
+ if (entryStats?.isDirectory()) {
245
+ items.push({ name: entry, type: 'directory', path: entryPath, modified: entryStats.mtime.toISOString(), kind: 'volume' });
275
246
  }
247
+ } catch {
248
+ // Skip inaccessible mounts
276
249
  }
277
- } catch {
278
- // Skip inaccessible volumes
279
250
  }
251
+ } catch {
252
+ // Skip if base is unreadable
280
253
  }
281
- } catch {
282
- // Skip if can't read /Volumes
283
254
  }
284
- }
285
255
 
286
- // On Linux, try to get mounted filesystems from /mnt and /media
287
- if (process.platform === 'linux') {
288
- for (const baseMount of ['/mnt', '/media']) {
289
- const baseMountFile = Bun.file(baseMount);
290
- if (await baseMountFile.exists()) {
291
- try {
292
- const mountItems = await readdir(baseMount);
293
- for (const mount of mountItems) {
294
- const mountPath = `${baseMount}/${mount}`;
295
- try {
296
- const mountFile = Bun.file(mountPath);
297
- if (await mountFile.exists()) {
298
- const stats = await mountFile.stat();
299
- if (stats.isDirectory()) {
300
- commonMountPoints.push({
301
- name: `${mount} (${baseMount})`,
302
- type: 'directory',
303
- path: mountPath,
304
- modified: stats.mtime.toISOString()
305
- });
256
+ // systemd automount: /run/media/{user}/{volume}
257
+ const runMediaStats = await statIfExists('/run/media');
258
+ if (runMediaStats?.isDirectory()) {
259
+ try {
260
+ const users = await readdir('/run/media');
261
+ for (const user of users) {
262
+ const userPath = `/run/media/${user}`;
263
+ try {
264
+ const userStats = await statIfExists(userPath);
265
+ if (!userStats?.isDirectory()) continue;
266
+ const volumes = await readdir(userPath);
267
+ for (const vol of volumes) {
268
+ const volPath = `${userPath}/${vol}`;
269
+ try {
270
+ const volStats = await statIfExists(volPath);
271
+ if (volStats?.isDirectory()) {
272
+ items.push({ name: vol, type: 'directory', path: volPath, modified: volStats.mtime.toISOString(), kind: 'volume' });
306
273
  }
274
+ } catch {
275
+ // Skip inaccessible
307
276
  }
308
- } catch {
309
- // Skip inaccessible mounts
310
277
  }
278
+ } catch {
279
+ // Skip inaccessible user dir
280
+ }
281
+ }
282
+ } catch {
283
+ // Skip if /run/media is unreadable
284
+ }
285
+ }
286
+ } else {
287
+ // Other Unix (FreeBSD, OpenBSD, etc.): root + /mnt and /media subdirectories
288
+ const rootStats = await statIfExists('/');
289
+ if (rootStats?.isDirectory()) {
290
+ items.push({ name: 'Root (/) Filesystem', type: 'directory', path: '/', modified: rootStats.mtime.toISOString(), kind: 'root' });
291
+ }
292
+
293
+ for (const base of ['/mnt', '/media']) {
294
+ const baseStats = await statIfExists(base);
295
+ if (!baseStats?.isDirectory()) continue;
296
+ try {
297
+ const entries = await readdir(base);
298
+ for (const entry of entries) {
299
+ const entryPath = `${base}/${entry}`;
300
+ try {
301
+ const entryStats = await statIfExists(entryPath);
302
+ if (entryStats?.isDirectory()) {
303
+ items.push({ name: entry, type: 'directory', path: entryPath, modified: entryStats.mtime.toISOString(), kind: 'volume' });
304
+ }
305
+ } catch {
306
+ // Skip inaccessible
311
307
  }
312
- } catch {
313
- // Skip if can't read mount directory
314
308
  }
309
+ } catch {
310
+ // Skip if base is unreadable
315
311
  }
316
312
  }
317
313
  }
318
314
 
319
- // Remove duplicates based on path
320
- const uniqueMounts = commonMountPoints.filter((mount, index, self) =>
321
- index === self.findIndex(m => m.path === mount.path)
322
- );
315
+ // Deduplicate by path
316
+ const seen = new Set<string>();
317
+ const uniqueMounts = items.filter(item => {
318
+ if (seen.has(item.path)) return false;
319
+ seen.add(item.path);
320
+ return true;
321
+ });
323
322
 
324
323
  return {
325
324
  name: 'System',
@@ -341,6 +340,7 @@ export async function handleWindowsDrives(): Promise<PathBrowseData> {
341
340
  type: 'file' | 'directory';
342
341
  path: string;
343
342
  modified: string;
343
+ kind: 'drive';
344
344
  size?: number;
345
345
  extension?: string;
346
346
  }> = [];
@@ -364,7 +364,8 @@ export async function handleWindowsDrives(): Promise<PathBrowseData> {
364
364
  name: `${drive} Drive`,
365
365
  type: 'directory',
366
366
  path: drivePath,
367
- modified: new Date().toISOString() // Use current time for drives
367
+ modified: new Date().toISOString(),
368
+ kind: 'drive'
368
369
  });
369
370
  }
370
371
 
@@ -378,7 +379,8 @@ export async function handleWindowsDrives(): Promise<PathBrowseData> {
378
379
  name: `${drive} Drive`,
379
380
  type: 'directory',
380
381
  path: drivePath,
381
- modified: new Date().toISOString()
382
+ modified: new Date().toISOString(),
383
+ kind: 'drive'
382
384
  });
383
385
  }
384
386
  } catch {
@@ -317,6 +317,14 @@ export class GitService {
317
317
  }
318
318
  }
319
319
 
320
+ async checkoutCommit(cwd: string, commitHash: string): Promise<void> {
321
+ assertSafeGitRevish(commitHash, 'commit hash');
322
+ const result = await execGit(['checkout', commitHash], cwd);
323
+ if (result.exitCode !== 0) {
324
+ throw new Error(`git checkout failed: ${result.stderr}`);
325
+ }
326
+ }
327
+
320
328
  async deleteBranch(cwd: string, name: string, force = false): Promise<void> {
321
329
  assertSafeGitRevish(name, 'branch name');
322
330
  const flag = force ? '-D' : '-d';
@@ -335,9 +343,12 @@ export class GitService {
335
343
  }
336
344
  }
337
345
 
338
- async mergeBranch(cwd: string, branchName: string): Promise<{ success: boolean; message: string }> {
346
+ async mergeBranch(cwd: string, branchName: string, noFastForward = false): Promise<{ success: boolean; message: string }> {
339
347
  assertSafeGitRevish(branchName, 'merge branch');
340
- const result = await execGit(['merge', branchName], cwd);
348
+ const args = ['merge'];
349
+ if (noFastForward) args.push('--no-ff');
350
+ args.push(branchName);
351
+ const result = await execGit(args, cwd);
341
352
  return {
342
353
  success: result.exitCode === 0,
343
354
  message: result.exitCode === 0 ? result.stdout : result.stderr
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Integration tests for file upload race condition fix.
3
+ *
4
+ * These tests verify that the atomic hard-link approach prevents race
5
+ * conditions when multiple uploads target the same file name by calling
6
+ * the actual filesUploadRoute handler with mock HTTP requests.
7
+ */
8
+
9
+ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
10
+ import { mkdir, rm, readFile } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { filesUploadRoute } from './files-upload';
15
+ import { authQueries } from '../database/queries';
16
+ import { hashToken } from '../auth/tokens';
17
+ import { projectQueries } from '../database/queries/project-queries';
18
+ import { initializeDatabase, closeDatabase } from '../database';
19
+
20
+ const TEST_DIR = join(import.meta.dir, '.test-upload-integration');
21
+ const TEST_WORKSPACE = join(TEST_DIR, 'workspace');
22
+
23
+ let testUserId: string;
24
+ let testToken: string;
25
+ let testProjectId: string;
26
+
27
+ /**
28
+ * Helper to create a mock upload request with proper authentication and parameters.
29
+ */
30
+ function createMockUploadRequest(
31
+ file: File,
32
+ targetPath: string,
33
+ fileName: string,
34
+ token: string
35
+ ): Request {
36
+ const url = new URL('http://localhost/api/files/upload');
37
+ url.searchParams.set('targetPath', targetPath);
38
+ url.searchParams.set('fileName', fileName);
39
+ url.searchParams.set('fileSize', String(file.size));
40
+
41
+ return new Request(url.toString(), {
42
+ method: 'POST',
43
+ body: file,
44
+ headers: {
45
+ 'authorization': `Bearer ${token}`
46
+ }
47
+ });
48
+ }
49
+
50
+ beforeAll(async () => {
51
+ // Initialize database
52
+ await initializeDatabase();
53
+
54
+ // Create test directory structure
55
+ await mkdir(TEST_WORKSPACE, { recursive: true });
56
+
57
+ // Create test user
58
+ testUserId = randomUUID();
59
+ authQueries.createUser({
60
+ id: testUserId,
61
+ name: 'Test User',
62
+ color: '#000000',
63
+ avatar: 'test',
64
+ role: 'admin',
65
+ personal_access_token_hash: null,
66
+ created_at: new Date().toISOString()
67
+ });
68
+
69
+ // Create test session
70
+ testToken = randomUUID();
71
+ const sessionId = randomUUID();
72
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); // 24 hours
73
+ authQueries.createSession({
74
+ id: sessionId,
75
+ user_id: testUserId,
76
+ token_hash: hashToken(testToken),
77
+ expires_at: expiresAt,
78
+ created_at: new Date().toISOString(),
79
+ last_active_at: new Date().toISOString()
80
+ });
81
+
82
+ // Create test project
83
+ const project = projectQueries.create({
84
+ name: 'Test Project',
85
+ path: TEST_WORKSPACE,
86
+ created_at: new Date().toISOString(),
87
+ last_opened_at: new Date().toISOString()
88
+ });
89
+ testProjectId = project.id;
90
+
91
+ // Link user to project
92
+ projectQueries.addUserProject(testUserId, testProjectId);
93
+ });
94
+
95
+ afterAll(async () => {
96
+ // Clean up database
97
+ authQueries.deleteSessionsByUserId(testUserId);
98
+ authQueries.deleteUser(testUserId);
99
+ projectQueries.deleteProject(testProjectId);
100
+
101
+ // Close database
102
+ closeDatabase();
103
+
104
+ // Clean up filesystem
105
+ await rm(TEST_DIR, { recursive: true, force: true });
106
+ });
107
+
108
+ beforeEach(async () => {
109
+ // Clean workspace between tests
110
+ await rm(TEST_WORKSPACE, { recursive: true, force: true });
111
+ await mkdir(TEST_WORKSPACE, { recursive: true });
112
+ });
113
+
114
+ describe('File upload integration tests', () => {
115
+ it('concurrent uploads of same file - link-based exclusive create prevents overwrite', async () => {
116
+ const file1 = new File(['content from upload 1'], 'test.txt', { type: 'text/plain' });
117
+ const file2 = new File(['content from upload 2'], 'test.txt', { type: 'text/plain' });
118
+
119
+ // Create mock requests
120
+ const request1 = createMockUploadRequest(file1, TEST_WORKSPACE, 'test.txt', testToken);
121
+ const request2 = createMockUploadRequest(file2, TEST_WORKSPACE, 'test.txt', testToken);
122
+
123
+ // Fire both concurrently
124
+ const [response1, response2] = await Promise.all([
125
+ filesUploadRoute.handle(request1),
126
+ filesUploadRoute.handle(request2)
127
+ ]);
128
+
129
+ // Exactly one 200, one 409
130
+ const statuses = [response1.status, response2.status].sort();
131
+ expect(statuses).toEqual([200, 409]);
132
+
133
+ // Winner's content is on disk (not empty)
134
+ const finalPath = join(TEST_WORKSPACE, 'test.txt');
135
+ const content = await readFile(finalPath, 'utf-8');
136
+ expect(content).toMatch(/content from upload [12]/);
137
+ expect(content.length).toBeGreaterThan(0); // Not empty placeholder
138
+ });
139
+
140
+ it('atomic link-based create prevents race', async () => {
141
+ const file = new File(['test content'], 'atomic.txt', { type: 'text/plain' });
142
+
143
+ // First upload succeeds
144
+ const request1 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
145
+ const response1 = await filesUploadRoute.handle(request1);
146
+ expect(response1.status).toBe(200);
147
+
148
+ // Second upload fails immediately with 409
149
+ const request2 = createMockUploadRequest(file, TEST_WORKSPACE, 'atomic.txt', testToken);
150
+ const response2 = await filesUploadRoute.handle(request2);
151
+ expect(response2.status).toBe(409);
152
+
153
+ // File has first upload's content
154
+ const finalPath = join(TEST_WORKSPACE, 'atomic.txt');
155
+ const content = await readFile(finalPath, 'utf-8');
156
+ expect(content).toBe('test content');
157
+ });
158
+
159
+ it('file appears atomically with full content (no partial-file window)', async () => {
160
+ const largeContent = 'x'.repeat(10000); // 10KB
161
+ const file = new File([largeContent], 'large.txt', { type: 'text/plain' });
162
+
163
+ const request = createMockUploadRequest(file, TEST_WORKSPACE, 'large.txt', testToken);
164
+ const response = await filesUploadRoute.handle(request);
165
+ expect(response.status).toBe(200);
166
+
167
+ // File has full content, not empty
168
+ const finalPath = join(TEST_WORKSPACE, 'large.txt');
169
+ const content = await readFile(finalPath, 'utf-8');
170
+ expect(content).toBe(largeContent);
171
+ expect(content.length).toBe(10000);
172
+ });
173
+ });
174
+
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { Elysia } from 'elysia';
18
18
  import { join } from 'node:path';
19
- import { mkdir, rename, stat, unlink } from 'node:fs/promises';
19
+ import { link, mkdir, stat, unlink } from 'node:fs/promises';
20
20
 
21
21
  import { debug } from '$shared/utils/logger';
22
22
  import { hashToken } from '../auth/tokens';
@@ -24,6 +24,7 @@ import { authQueries, fileAuditLogQueries } from '../database/queries';
24
24
  import { findContainingProjectId, requireFilePathAccessFor } from '../ws/files/path-access';
25
25
  import { clientIpFromRequest } from '../utils/client-ip';
26
26
  import { validateFileSize } from '../files/file-size-limit';
27
+ import { uploadTempCleanup } from './upload-temp-cleanup';
27
28
 
28
29
  type AuthIdentity = { userId: string; role: string };
29
30
 
@@ -125,6 +126,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
125
126
  return new Response(message, { status: 500 });
126
127
  }
127
128
 
129
+ // Early existence check — fast-path rejection before streaming the body
128
130
  if (await Bun.file(resolvedFinal).exists()) {
129
131
  fileAuditLogQueries.logOperation({
130
132
  userId: identity.userId,
@@ -144,11 +146,16 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
144
146
  return new Response('Request body is empty', { status: 400 });
145
147
  }
146
148
 
149
+ // Stream to a unique temp file, then atomically link into place.
150
+ // link() uses O_EXCL semantics — fails with EEXIST if final already exists.
151
+ // The final path only appears with full content (no partial-file visibility).
147
152
  const tempPath = `${resolvedFinal}.${crypto.randomUUID()}.partial`;
153
+ uploadTempCleanup.register(tempPath);
148
154
  const writer = Bun.file(tempPath).writer();
149
155
  let written = 0;
150
156
 
151
157
  const cleanupTemp = async () => {
158
+ uploadTempCleanup.deregister(tempPath);
152
159
  try { await writer.end(); } catch { /* best-effort */ }
153
160
  try { await unlink(tempPath); } catch { /* best-effort */ }
154
161
  };
@@ -171,6 +178,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
171
178
  await writer.end();
172
179
 
173
180
  if (written !== fileSizeParam) {
181
+ uploadTempCleanup.deregister(tempPath);
174
182
  await unlink(tempPath).catch(() => {});
175
183
  return new Response(`Incomplete upload: received ${written} of ${fileSizeParam} bytes`, { status: 400 });
176
184
  }
@@ -178,6 +186,7 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
178
186
  try {
179
187
  validateFileSize(written);
180
188
  } catch (error) {
189
+ uploadTempCleanup.deregister(tempPath);
181
190
  await unlink(tempPath).catch(() => {});
182
191
  fileAuditLogQueries.logOperation({
183
192
  userId: identity.userId,
@@ -193,8 +202,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
193
202
  return new Response(error instanceof Error ? error.message : 'File too large', { status: 413 });
194
203
  }
195
204
 
196
- // Race-check: refuse to overwrite if the destination appeared mid-upload.
197
- if (await Bun.file(resolvedFinal).exists()) {
205
+ // Atomic exclusive link — fails with EEXIST if final already exists
206
+ try {
207
+ await link(tempPath, resolvedFinal);
208
+ } catch (error: unknown) {
209
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
210
+ uploadTempCleanup.deregister(tempPath);
211
+ await unlink(tempPath).catch(() => {});
212
+ return new Response('File already exists', { status: 409 });
213
+ }
198
214
  await unlink(tempPath).catch(() => {});
199
215
  fileAuditLogQueries.logOperation({
200
216
  userId: identity.userId,
@@ -205,12 +221,15 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
205
221
  ipAddress,
206
222
  userAgent,
207
223
  success: false,
208
- errorMessage: 'File already exists (race condition)'
224
+ errorMessage: `link() failed: ${(error as Error).message}`
209
225
  });
210
- return new Response('File already exists', { status: 409 });
226
+ throw error;
211
227
  }
212
228
 
213
- await rename(tempPath, resolvedFinal);
229
+ uploadTempCleanup.deregister(tempPath);
230
+ // Clean up temp — the real file is now the hard-link
231
+ await unlink(tempPath).catch(() => {});
232
+
214
233
  const stats = await stat(resolvedFinal);
215
234
 
216
235
  fileAuditLogQueries.logOperation({
@@ -230,7 +249,8 @@ export const filesUploadRoute = new Elysia().post('/api/files/upload', async ({
230
249
  modified: stats.mtime.toISOString()
231
250
  });
232
251
  } catch (error) {
233
- await cleanupTemp();
252
+ uploadTempCleanup.deregister(tempPath);
253
+ await unlink(tempPath).catch(() => {});
234
254
  debug.error('file', 'HTTP upload error:', error);
235
255
  const message = error instanceof Error ? error.message : 'Upload failed';
236
256
  fileAuditLogQueries.logOperation({