π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): upload local files via `file upload` & shared helper (#15949)
Arvin Xua38437c1da5e
diff --git a/apps/cli/e2e/file.e2e.test.ts b/apps/cli/e2e/file.e2e.test.tsindex 92b2b51aae6..cb81efc942f 100644--- a/apps/cli/e2e/file.e2e.test.ts+++ b/apps/cli/e2e/file.e2e.test.ts@@ -1,4 +1,7 @@import { execSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';import { describe, expect, it } from 'vitest';@@ -77,6 +80,40 @@ describe('lh file - E2E', () => {});});+ // ββ upload (local file) βββββββββββββββββββββββββββββββ++ describe('upload', () => {+ it('should upload a local file passed as a positional argument', () => {+ const tmpFile = path.join(os.tmpdir(), `lh-e2e-upload-${Date.now()}.txt`);+ fs.writeFileSync(tmpFile, 'hello from lh e2e upload');++ try {+ const result = runJson<{ id: string }>(`file upload ${tmpFile} --json id`);+ expect(result).toHaveProperty('id');+ if (result.id) run(`file delete ${result.id} --yes`);+ } finally {+ fs.rmSync(tmpFile, { force: true });+ }+ });++ it('should upload a local file passed via --file', () => {+ const tmpFile = path.join(os.tmpdir(), `lh-e2e-upload-f-${Date.now()}.txt`);+ fs.writeFileSync(tmpFile, 'hello from lh e2e --file upload');++ try {+ const result = runJson<{ id: string }>(`file upload --file ${tmpFile} --json id`);+ expect(result).toHaveProperty('id');+ if (result.id) run(`file delete ${result.id} --yes`);+ } finally {+ fs.rmSync(tmpFile, { force: true });+ }+ });++ it('should error when the local file does not exist', () => {+ expect(() => run('file upload -f /no/such/lh-file.txt')).toThrow();+ });+ });+// ββ recent ββββββββββββββββββββββββββββββββββββββββββββdescribe('recent', () => {diff --git a/apps/cli/src/commands/file.test.ts b/apps/cli/src/commands/file.test.tsindex f0f9927ef07..b571b03925c 100644--- a/apps/cli/src/commands/file.test.ts+++ b/apps/cli/src/commands/file.test.ts@@ -1,3 +1,7 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -17,6 +21,9 @@ const { mockTrpcClient } = vi.hoisted(() => ({removeFiles: { mutate: vi.fn() },updateFile: { mutate: vi.fn() },},+ upload: {+ createS3PreSignedUrl: { mutate: vi.fn() },+ },},}));@@ -38,9 +45,11 @@ describe('file command', () => {exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});mockGetTrpcClient.mockResolvedValue(mockTrpcClient);- for (const method of Object.values(mockTrpcClient.file)) {- for (const fn of Object.values(method)) {- (fn as ReturnType<typeof vi.fn>).mockReset();+ for (const group of [mockTrpcClient.file, mockTrpcClient.upload]) {+ for (const method of Object.values(group)) {+ for (const fn of Object.values(method)) {+ (fn as ReturnType<typeof vi.fn>).mockReset();+ }}}});@@ -205,6 +214,111 @@ describe('file command', () => {expect(mockTrpcClient.file.createFile.mutate).not.toHaveBeenCalled();expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('already exists'));});++ it('should upload a local file passed as a positional argument', async () => {+ const tmpFile = path.join(os.tmpdir(), `lh-upload-${process.pid}.txt`);+ fs.writeFileSync(tmpFile, 'hello world');++ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue({ ok: true, status: 200, statusText: 'OK' } as Response);+ mockTrpcClient.file.checkFileHash.mutate.mockResolvedValue({ isExist: false });+ mockTrpcClient.upload.createS3PreSignedUrl.mutate.mockResolvedValue('https://s3/presigned');+ mockTrpcClient.file.createFile.mutate.mockResolvedValue({+ id: 'f-local',+ url: 'files/x.txt',+ });++ try {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'file', 'upload', tmpFile]);++ expect(mockTrpcClient.upload.createS3PreSignedUrl.mutate).toHaveBeenCalled();+ expect(fetchSpy).toHaveBeenCalledWith(+ 'https://s3/presigned',+ expect.objectContaining({ method: 'PUT' }),+ );+ expect(mockTrpcClient.file.createFile.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'text/plain',+ name: path.basename(tmpFile),+ url: expect.stringContaining('.txt'),+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('File created'));+ } finally {+ fetchSpy.mockRestore();+ fs.rmSync(tmpFile, { force: true });+ }+ });++ it('should upload a local file passed via --file', async () => {+ const tmpFile = path.join(os.tmpdir(), `lh-upload-f-${process.pid}.json`);+ fs.writeFileSync(tmpFile, '{}');++ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue({ ok: true, status: 200, statusText: 'OK' } as Response);+ mockTrpcClient.file.checkFileHash.mutate.mockResolvedValue({ isExist: false });+ mockTrpcClient.upload.createS3PreSignedUrl.mutate.mockResolvedValue('https://s3/presigned');+ mockTrpcClient.file.createFile.mutate.mockResolvedValue({ id: 'f-json' });++ try {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'file', 'upload', '--file', tmpFile]);++ expect(mockTrpcClient.file.createFile.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ fileType: 'application/json' }),+ );+ } finally {+ fetchSpy.mockRestore();+ fs.rmSync(tmpFile, { force: true });+ }+ });++ it('should skip the S3 upload when the local file hash already exists', async () => {+ const tmpFile = path.join(os.tmpdir(), `lh-upload-dedup-${process.pid}.txt`);+ fs.writeFileSync(tmpFile, 'dedup me');++ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ mockTrpcClient.file.checkFileHash.mutate.mockResolvedValue({+ isExist: true,+ url: 'files/2024-01-01/existing.txt',+ });+ mockTrpcClient.file.createFile.mutate.mockResolvedValue({ id: 'f-dedup' });++ try {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'file', 'upload', tmpFile]);++ // No pre-sign and no S3 PUT should happen+ expect(mockTrpcClient.upload.createS3PreSignedUrl.mutate).not.toHaveBeenCalled();+ expect(fetchSpy).not.toHaveBeenCalled();+ // The record reuses the existing url+ expect(mockTrpcClient.file.createFile.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ url: 'files/2024-01-01/existing.txt' }),+ );+ } finally {+ fetchSpy.mockRestore();+ fs.rmSync(tmpFile, { force: true });+ }+ });++ it('should error when local file does not exist', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'file', 'upload', '-f', '/no/such/file.txt']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('File not found'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('should error when no source is provided', async () => {+ const program = createProgram();+ await program.parseAsync(['node', 'test', 'file', 'upload']);++ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('Provide a local file path'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ });});describe('edit', () => {diff --git a/apps/cli/src/commands/file.ts b/apps/cli/src/commands/file.tsindex 02860f0da8b..d046f56c054 100644--- a/apps/cli/src/commands/file.ts+++ b/apps/cli/src/commands/file.ts@@ -4,6 +4,7 @@ import pc from 'picocolors';import { getTrpcClient } from '../api/client';import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';import { log } from '../utils/logger';+import { uploadLocalFile } from '../utils/uploadLocalFile';export function registerFileCommand(program: Command) {const file = program.command('file').description('Manage files');@@ -113,18 +114,20 @@ export function registerFileCommand(program: Command) {// ββ upload βββββββββββββββββββββββββββββββββββββββββββfile- .command('upload <url>')- .description('Upload a file by URL (checks hash first)')- .option('--hash <hash>', 'File hash for deduplication check')- .option('--name <name>', 'File name')- .option('--type <type>', 'File MIME type')- .option('--size <size>', 'File size in bytes')+ .command('upload [source]')+ .description('Upload a file from a local path or a URL')+ .option('-f, --file <path>', 'Local file path to upload')+ .option('--hash <hash>', 'File hash for deduplication check (URL mode)')+ .option('--name <name>', 'File name (URL mode)')+ .option('--type <type>', 'File MIME type (URL mode)')+ .option('--size <size>', 'File size in bytes (URL mode)').option('--parent-id <id>', 'Parent folder ID').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)').action(async (- url: string,+ source: string | undefined,options: {+ file?: string;hash?: string;json?: string | boolean;name?: string;@@ -133,8 +136,47 @@ export function registerFileCommand(program: Command) {type?: string;},) => {+ const isUrl = (value: string) =>+ value.startsWith('http://') || value.startsWith('https://');++ // Resolve the local file path: explicit --file, or a positional that is+ // not a URL (e.g. `lh file upload ./games_list.txt`).+ const localPath = options.file ?? (source && !isUrl(source) ? source : undefined);+const client = await getTrpcClient();+ // ββ Local file upload ββ+ if (localPath) {+ let result;+ try {+ result = await uploadLocalFile(client, localPath, { parentId: options.parentId });+ } catch (error) {+ log.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ return;+ }++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(result, fields);+ return;+ }++ const r = result as any;+ console.log(`${pc.green('β')} File created: ${pc.bold(r.id || '')}`);+ if (r.url) console.log(` URL: ${pc.dim(r.url)}`);+ return;+ }++ // ββ URL upload ββ+ if (!source) {+ log.error('Provide a local file path, --file <path>, or a URL to upload.');+ process.exit(1);+ return;+ }++ const url = source;+// Check hash first if providedif (options.hash) {const check = await client.file.checkFileHash.mutate({ hash: options.hash });diff --git a/apps/cli/src/commands/kb.ts b/apps/cli/src/commands/kb.tsindex f65ad445eb7..1f82719f89b 100644--- a/apps/cli/src/commands/kb.ts+++ b/apps/cli/src/commands/kb.ts@@ -1,14 +1,12 @@-import crypto from 'node:crypto';-import fs from 'node:fs';import path from 'node:path';import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../api/client';-import { getAuthInfo } from '../api/http';import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';import { log } from '../utils/logger';+import { uploadLocalFile } from '../utils/uploadLocalFile';function formatFileType(fileType: string): string {if (!fileType) return '';@@ -324,81 +322,22 @@ export function registerKbCommand(program: Command) {.description('Upload a file to a knowledge base').option('--parent <parentId>', 'Parent folder ID').action(async (knowledgeBaseId: string, filePath: string, options: { parent?: string }) => {- const resolved = path.resolve(filePath);- if (!fs.existsSync(resolved)) {- log.error(`File not found: ${resolved}`);- process.exit(1);- }-- const stat = fs.statSync(resolved);- const fileName = path.basename(resolved);- const fileBuffer = fs.readFileSync(resolved);-- // Compute SHA-256 hash- const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');-- // Detect MIME type from extension- const ext = path.extname(fileName).toLowerCase().slice(1);- const mimeMap: Record<string, string> = {- csv: 'text/csv',- doc: 'application/msword',- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- gif: 'image/gif',- jpeg: 'image/jpeg',- jpg: 'image/jpeg',- json: 'application/json',- md: 'text/markdown',- mp3: 'audio/mpeg',- mp4: 'video/mp4',- pdf: 'application/pdf',- png: 'image/png',- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',- svg: 'image/svg+xml',- txt: 'text/plain',- webp: 'image/webp',- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',- };- const fileType = mimeMap[ext] || 'application/octet-stream';-const client = await getTrpcClient();- const { serverUrl, headers } = await getAuthInfo();-- // 1. Get presigned URL- const date = new Date().toLocaleDateString('en-CA'); // YYYY-MM-DD- const pathname = `files/${date}/${hash}.${ext}`;- const presigned = await client.upload.createS3PreSignedUrl.mutate({ pathname });-- // 2. Upload to S3- const presignedUrl = typeof presigned === 'string' ? presigned : (presigned as any).url;- const uploadRes = await fetch(presignedUrl, {- body: fileBuffer,- headers: { 'Content-Type': fileType },- method: 'PUT',- });- if (!uploadRes.ok) {- log.error(`Upload failed: ${uploadRes.status} ${uploadRes.statusText}`);++ let result;+ try {+ result = await uploadLocalFile(client, filePath, {+ knowledgeBaseId,+ parentId: options.parent,+ });+ } catch (error) {+ log.error(error instanceof Error ? error.message : String(error));process.exit(1);+ return;}- // 3. Create file record- const result = await client.file.createFile.mutate({- fileType,- hash,- knowledgeBaseId,- metadata: {- date,- dirname: '',- filename: fileName,- path: pathname,- },- name: fileName,- parentId: options.parent,- size: stat.size,- url: pathname,- });-console.log(- `${pc.green('β')} Uploaded ${pc.bold(fileName)} β ${pc.bold((result as any).id)}`,+ `${pc.green('β')} Uploaded ${pc.bold(path.basename(filePath))} β ${pc.bold((result as any).id)}`,);});}diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.tsnew file mode 100644index 00000000000..0a7a5d3701a--- /dev/null+++ b/apps/cli/src/utils/uploadLocalFile.ts@@ -0,0 +1,119 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++import type { TrpcClient } from '../api/client';++/**+ * Minimal extension β MIME map for files uploaded from the local filesystem.+ * Unknown extensions fall back to `application/octet-stream`.+ */+const MIME_MAP: Record<string, string> = {+ csv: 'text/csv',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ gif: 'image/gif',+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ json: 'application/json',+ md: 'text/markdown',+ mp3: 'audio/mpeg',+ mp4: 'video/mp4',+ pdf: 'application/pdf',+ png: 'image/png',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ svg: 'image/svg+xml',+ txt: 'text/plain',+ webp: 'image/webp',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+};++/**+ * Detect a MIME type from a file name's extension.+ */+export const detectMimeType = (fileName: string): string => {+ const ext = path.extname(fileName).toLowerCase().slice(1);+ return MIME_MAP[ext] || 'application/octet-stream';+};++export interface UploadLocalFileOptions {+ knowledgeBaseId?: string;+ parentId?: string;+}++/**+ * Read a file from the local filesystem, upload it to S3 via a pre-signed URL,+ * and create the corresponding file record. Shared by `file upload` and+ * `kb upload`.+ *+ * @returns the created file record+ */+export const uploadLocalFile = async (+ client: TrpcClient,+ filePath: string,+ options: UploadLocalFileOptions = {},+) => {+ const resolved = path.resolve(filePath);+ if (!fs.existsSync(resolved)) {+ throw new Error(`File not found: ${resolved}`);+ }++ const stat = fs.statSync(resolved);+ if (!stat.isFile()) {+ throw new Error(`Not a file: ${resolved}`);+ }++ const fileName = path.basename(resolved);+ const fileBuffer = fs.readFileSync(resolved);++ // Compute SHA-256 hash for deduplication+ const hash = crypto.createHash('sha256').update(fileBuffer).digest('hex');++ const ext = path.extname(fileName).toLowerCase().slice(1);+ const fileType = detectMimeType(fileName);++ const date = new Date().toLocaleDateString('en-CA'); // YYYY-MM-DD++ // 1. Dedup: if the same bytes are already stored (and the object still+ // exists), skip the S3 upload entirely and reuse the existing url.+ const existing = (await client.file.checkFileHash.mutate({ hash })) as {+ isExist?: boolean;+ url?: string;+ };++ let pathname: string;+ if (existing?.isExist && existing.url) {+ pathname = existing.url;+ } else {+ // 2. Get a pre-signed upload URL and PUT the bytes to S3+ pathname = ext ? `files/${date}/${hash}.${ext}` : `files/${date}/${hash}`;+ const presigned = await client.upload.createS3PreSignedUrl.mutate({ pathname });++ const presignedUrl = typeof presigned === 'string' ? presigned : (presigned as any).url;+ const uploadRes = await fetch(presignedUrl, {+ body: fileBuffer,+ headers: { 'Content-Type': fileType },+ method: 'PUT',+ });+ if (!uploadRes.ok) {+ throw new Error(`Upload failed: ${uploadRes.status} ${uploadRes.statusText}`);+ }+ }++ // 3. Create the file record+ return await client.file.createFile.mutate({+ fileType,+ hash,+ knowledgeBaseId: options.knowledgeBaseId,+ metadata: {+ date,+ dirname: '',+ filename: fileName,+ path: pathname,+ },+ name: fileName,+ parentId: options.parentId,+ size: stat.size,+ url: pathname,+ });+};