From 87fc10b62fd1e9cab20fe95a1ad1381216da9719 Mon Sep 17 00:00:00 2001 From: yiling Date: Sun, 21 Jun 2026 20:06:06 +0800 Subject: [PATCH] fix(cli): resolve upload status and CLI progress tracker bugs --- apps/cli/src/commands/commands.test.ts | 105 +++++++++++++++++++++++++ apps/cli/src/commands/upload.ts | 77 +++++++++++------- packages/api/src/index.ts | 3 +- packages/api/src/upload.ts | 11 ++- 4 files changed, 162 insertions(+), 34 deletions(-) diff --git a/apps/cli/src/commands/commands.test.ts b/apps/cli/src/commands/commands.test.ts index a5bbaee6..619e88e9 100644 --- a/apps/cli/src/commands/commands.test.ts +++ b/apps/cli/src/commands/commands.test.ts @@ -3,11 +3,20 @@ import { projectLs } from './project' import { ls } from './ls' import { mkdir } from './mkdir' import { getClient } from '../client' +import { upload } from './upload' +import fs from 'node:fs' +import http from 'node:http' vi.mock('../client', () => ({ getClient: vi.fn(), })) +vi.mock('node:http', () => ({ + default: { + request: vi.fn(), + }, +})) + describe('CLI Commands', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let logSpy: any @@ -22,6 +31,9 @@ describe('CLI Commands', () => { api: { projects: { $get: vi.fn(), + ':projectId': { + $get: vi.fn(), + }, }, folders: { $post: vi.fn(), @@ -133,4 +145,97 @@ describe('CLI Commands', () => { expect(logSpy).toHaveBeenCalledWith('Created folder with ID: new_folder_ulid') }) }) + + describe('upload', () => { + it('uploads a file successfully and confirms the task', async () => { + const tempFile = 'temp-test-file.txt' + fs.writeFileSync(tempFile, 'hello world') + + mockClient.api.folders[':folderId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ projectId: 'p123' }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + mockClient.api.projects[':projectId'].$get.mockResolvedValue({ + ok: true, + json: async () => ({ teamId: 't123' }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + mockClient.api.teams[':teamId'].upload.tasks.$post.mockImplementation( + async (req: unknown) => { + const rootNodeId = (req as { json: { files: { id: string }[] } }).json.files[0].id + return { + ok: true, + json: async () => ({ + taskId: 'task123', + presignedUrls: [ + { id: rootNodeId, fileId: 'file-123', url: 'http://localhost/upload' }, + ], + createdAssets: [{ tempId: rootNodeId, assetId: 'file-123' }], + }), + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any + }, + ) + + mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch.mockResolvedValue({ + ok: true, + // We use any here because we are mocking the hono client response shape in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + const mockRes = { + statusCode: 200, + resume: vi.fn(), + } + let mockReqCallback: ((res: { statusCode: number; resume: () => void }) => void) | null = null + const mockReq = { + on: vi.fn().mockImplementation(() => { + return mockReq + }), + write: vi.fn(), + end: vi.fn().mockImplementation(() => { + if (mockReqCallback) { + mockReqCallback(mockRes) + } + }), + destroy: vi.fn(), + } + + vi.mocked(http.request).mockImplementation((( + _options: unknown, + callback: (res: { statusCode: number; resume: () => void }) => void, + ) => { + mockReqCallback = callback + return mockReq + // We use any here because we are mocking the http request function in a unit test context + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any) + + await upload(tempFile, 'folder-123') + + expect(mockClient.api.folders[':folderId'].$get).toHaveBeenCalledWith({ + param: { folderId: 'folder-123' }, + }) + expect(mockClient.api.projects[':projectId'].$get).toHaveBeenCalledWith({ + param: { projectId: 'p123' }, + }) + expect(mockClient.api.teams[':teamId'].upload.tasks.$post).toHaveBeenCalled() + expect(mockClient.api.teams[':teamId'].upload.tasks[':taskId'].$patch).toHaveBeenCalledWith({ + param: { teamId: 't123', taskId: 'task123' }, + json: { fileId: 'file-123' }, + }) + + try { + fs.unlinkSync(tempFile) + } catch { + // Ignore if file doesn't exist + } + }) + }) }) diff --git a/apps/cli/src/commands/upload.ts b/apps/cli/src/commands/upload.ts index 3ea668da..41b1dbef 100644 --- a/apps/cli/src/commands/upload.ts +++ b/apps/cli/src/commands/upload.ts @@ -1,5 +1,7 @@ import fs from 'node:fs' import fsPromises from 'node:fs/promises' +import http from 'node:http' +import https from 'node:https' import path from 'node:path' import { ulid } from 'ulid' import { getClient } from '../client' @@ -87,6 +89,8 @@ class ProgressTracker { if (this.isTty) { console.log(`${name.padEnd(30)} [${'░'.repeat(20)}] 0%`) this.linesPrinted++ + console.log('') + this.linesPrinted++ } } @@ -96,7 +100,7 @@ class ProgressTracker { item.uploadedBytes = uploadedBytes if (this.isTty) { - process.stdout.write(`\x1B[${this.linesPrinted}A`) + process.stdout.write('\x1B[' + this.linesPrinted + 'A') this.linesPrinted = 0 for (const upload of this.uploads.values()) { const pct = @@ -108,6 +112,8 @@ class ProgressTracker { const bar = '█'.repeat(filledLength) + '░'.repeat(barLength - filledLength) console.log(`${upload.name.padEnd(30)} [${bar}] ${pct}%`) this.linesPrinted++ + console.log('') + this.linesPrinted++ } } else { const pct = item.size > 0 ? Math.min(Math.round((uploadedBytes / item.size) * 100), 100) : 100 @@ -127,42 +133,53 @@ async function uploadFileWithProgress( const stat = fs.statSync(filePath) const totalSize = stat.size - const fileStream = fs.createReadStream(filePath) - let bytesUploaded = 0 + const parsedUrl = new URL(url) + const isHttps = parsedUrl.protocol === 'https:' + const requestModule = isHttps ? https : http - const trackingStream = new ReadableStream({ - start(controller) { - fileStream.on('data', (chunk) => { - bytesUploaded += chunk.length - onProgress(bytesUploaded) - controller.enqueue(chunk) - }) - fileStream.on('end', () => { - controller.close() - }) - fileStream.on('error', (err) => { - controller.error(err) - }) - }, - cancel() { - fileStream.destroy() - }, - }) - - const response = await fetch(url, { + const options = { method: 'PUT', - body: trackingStream, + hostname: parsedUrl.hostname, + port: parsedUrl.port || (isHttps ? 443 : 80), + path: parsedUrl.pathname + parsedUrl.search, headers: { 'Content-Type': contentType, 'Content-Length': totalSize.toString(), }, - // @ts-expect-error - duplex is required for streaming request bodies in modern fetch - duplex: 'half', - }) - - if (!response.ok) { - throw new Error(`Failed to upload to S3: ${response.statusText}`) } + + return new Promise((resolve, reject) => { + const req = requestModule.request(options, (res) => { + res.resume() + if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) { + resolve() + } else { + reject(new Error(`Failed to upload to S3: ${res.statusCode} ${res.statusMessage}`)) + } + }) + + req.on('error', (err) => { + reject(err) + }) + + const fileStream = fs.createReadStream(filePath) + let bytesUploaded = 0 + + fileStream.on('data', (chunk) => { + bytesUploaded += chunk.length + onProgress(bytesUploaded) + req.write(chunk) + }) + + fileStream.on('end', () => { + req.end() + }) + + fileStream.on('error', (err) => { + req.destroy() + reject(err) + }) + }) } export async function upload(localPath: string, parentId: string) { diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts index 9d5df218..96d2e2ff 100644 --- a/packages/api/src/index.ts +++ b/packages/api/src/index.ts @@ -19,7 +19,7 @@ import s3Route from './s3' import shareRoute from './share' import skillRoute from './skill' import teamRoute from './team' -import uploadRoute from './upload' +import uploadRoute, { localUploadRoute } from './upload' import versionStackRoute from './versionStack' type User = Prisma.UserGetPayload> @@ -31,6 +31,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>() .route('/', authnRoute) .route('/', publicInviteRoute) .route('/', publicShareRoute) + .route('/', localUploadRoute) // Selected routes supporting API token authentication .use('/projects', tokenAuthMiddleware) diff --git a/packages/api/src/upload.ts b/packages/api/src/upload.ts index f9c5ac6a..8cbbdb75 100644 --- a/packages/api/src/upload.ts +++ b/packages/api/src/upload.ts @@ -15,8 +15,10 @@ import type { Prisma } from '@shumai/db' type User = Prisma.UserGetPayload> -const route = new Hono<{ Variables: { user: User } }>() - .put('/upload/local', zValidator('query', localUploadQuerySchema), async (c) => { +export const localUploadRoute = new Hono().put( + '/upload/local', + zValidator('query', localUploadQuerySchema), + async (c) => { const { bucket, key, Signature } = c.req.valid('query') if (!verifyLocalUrlSignature(bucket, key, Signature)) { @@ -46,7 +48,10 @@ const route = new Hono<{ Variables: { user: User } }>() await s3Service.putObject(bucket, key, buffer, size, finalContentType) return c.json({ success: true }) - }) + }, +) + +const route = new Hono<{ Variables: { user: User } }>() .get('/teams/:teamId/upload/tasks', zValidator('query', paginationParamsSchema), async (c) => { const teamId = c.req.param('teamId') const user = c.get('user')