Skip to content

🀯 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.

⚑️ perf(upload): hash large files off the main thread (#19065)

Innei226c04ca59ee
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index b3fa7af506d..b3026c823ab 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -762,6 +762,24 @@ a dev server started by another session can point somewhere else entirely. Re-se
round-trip), and re-run `setup-auth.sh web-seed` because the SPA's client-side auth
gate still redirects to `/signin` after the row is recreated.
+### L-S20 β€” Bootstrapping the isolated stack with the script's default DB port hits another project's Postgres
+
+**Wrong approach:** run `init-dev-env.sh setup-db` / `seed-user` / `dev` from a fresh
+worktree and trust "database migration pass" plus a started server.
+
+**Why it fails:** the script defaults to `DB_PORT=5433` / `REDIS_PORT=6380`, but on a
+machine where those ports were already taken the managed containers were created on
+5434 / 6381 (`docker ps` shows `lobehub-agent-testing-postgres` β†’ `0.0.0.0:5434`). The
+default then dials whatever owns 5433 β€” another project's Postgres β€” and fails with
+`password authentication failed` (`routine: 'auth_failed'`), or worse, succeeds against
+a database that is not ours. The dev server started in that state serves a healthy page
+whose every tRPC write fails far from the cause.
+
+**Correct approach:** read the managed containers' host ports from `docker ps` first and
+pass them explicitly to every subcommand and to the backgrounded `dev`
+(`DB_PORT=5434 REDIS_PORT=6381 init-dev-env.sh …`). Treat a `migrate` that fails with
+`auth_failed` as a port mismatch, never as a credentials problem.
+
### L-S8 β€” Reading a first-boot renderer crash as a defect of the change under test
**Wrong approach:** treat the Electron dev instance's first renderer boot as
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 11933238af5..7c8483e7021 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -513,6 +513,34 @@ there the auto-attach to the current conversation is exactly what you want.
### Driving the UI
+#### Driving a 衄源库 upload with agent-browser: use the Add-menu input, and a same-build A/B for the hashing thread
+
+**Situation:** uploading a multi-GB fixture through the resource library (`/resource`)
+to verify the upload/hash pipeline without a real drag-and-drop.
+
+**Doesn't work:** `agent-browser upload` on the first `input[type=file][multiple]` the
+page exposes. That input belongs to another surface; `dockUploadFileList` stays empty
+and nothing errors, which reads as "the upload never started".
+
+**Works:** open the header `Add` menu first (`find role button click --name "Add"`),
+then upload into the antd input it mounts:
+`agent-browser upload '.ant-upload input[type=file][multiple]' <file>`. Poll
+`window.__LOBE_STORES.file().dockUploadFileList` for `status` / `uploadState.progress`;
+the hash phase is `pending` with a climbing `progress`, upload is `uploading`, and the
+row auto-clears \~3 s after `success`, so screenshot on the first `success` sample.
+Note the `eval` output is a JSON-encoded string β€” `\"status\":\"success\"` β€” so a
+`rg` trigger must not assume bare quotes (`'status.{2,6}success'`).
+
+To prove the hash left the main thread without checking out old code, run the same
+file twice in the same build: once after `window.Worker = undefined` (the shared
+`hashFile` then falls back to its inline streaming path, byte-for-byte the pre-worker
+behaviour) and once untouched. A 16 ms `setInterval` sampler's longest gap is the
+stall metric (measured: 16.4 s vs 61 ms for 1.1 GB); wrap `window.Worker` to record
+the constructed script URL and `window.fetch` to timestamp `file.checkFileHash`, which
+marks the end of hashing. A re-upload of the same file still hashes and then dedups
+(only `checkFileHash` + `createFile`), so it is a cheap way to re-capture the progress
+UI without another transfer.
+
#### The composer's slash menu needs real key events β€” `keyboard type` never opens it
**Situation:** driving the chat composer's `/` slash menu (or anything else gated on
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 3fff1aa68b2..d3a712f1343 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -1,4 +1,5 @@
-import { constants } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { constants, createReadStream } from 'node:fs';
import { access, readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
@@ -12,6 +13,7 @@ import {
type GlobFilesResult,
type GrepContentParams,
type GrepContentResult,
+ type HashLocalFileParams,
type ListLocalFileParams,
type LocalFilePreviewResult,
type LocalFilePreviewUrlParams,
@@ -440,6 +442,13 @@ export default class LocalFileCtr extends ControllerModule {
return results;
}
+ @IpcMethod()
+ async hashLocalFile({ path: filePath }: HashLocalFileParams): Promise<string> {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk);
+ return hash.digest('hex');
+ }
+
@IpcMethod()
async readFile(params: LocalReadFileParams): Promise<LocalReadFileResult> {
logger.debug('Starting to read file:', {
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.hashLocalFile.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.hashLocalFile.test.ts
new file mode 100644
index 00000000000..d0e848c5f5f
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.hashLocalFile.test.ts
@@ -0,0 +1,55 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import { mkdir, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type App } from '@/core/App';
+
+import LocalFileCtr from '../LocalFileCtr';
+
+vi.mock('electron', () => ({
+ dialog: { showOpenDialog: vi.fn(), showSaveDialog: vi.fn() },
+ ipcMain: { handle: vi.fn() },
+ shell: { openPath: vi.fn() },
+}));
+
+vi.mock('execa', () => ({ execa: vi.fn() }));
+vi.mock('@/utils/net-fetch', () => ({ netFetch: vi.fn() }));
+vi.mock('@/utils/file-system', () => ({ makeSureDirExist: vi.fn() }));
+
+const mockApp = {
+ appStoragePath: '/mock/app/storage',
+ getService: vi.fn(),
+ toolDetectorManager: { getBestTool: vi.fn(() => null) },
+} as unknown as App;
+
+describe('LocalFileCtr β€” hashLocalFile', () => {
+ const tmpDir = path.join(os.tmpdir(), 'localfilectr-hash-test-' + process.pid);
+
+ beforeEach(async () => {
+ await mkdir(tmpDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ });
+
+ it('returns the sha256 hex of the file content', async () => {
+ const filePath = path.join(tmpDir, 'blob.bin');
+ const content = Buffer.alloc(3 * 1024 * 1024, 7);
+ await writeFile(filePath, content);
+
+ const hash = await new LocalFileCtr(mockApp).hashLocalFile({ path: filePath });
+
+ expect(hash).toBe(createHash('sha256').update(content).digest('hex'));
+ });
+
+ it('rejects when the file does not exist', async () => {
+ await expect(
+ new LocalFileCtr(mockApp).hashLocalFile({ path: path.join(tmpDir, 'missing') }),
+ ).rejects.toThrow();
+ });
+});
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 9b862f25030..1cc803c9588 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -88,6 +88,10 @@ export interface RenameLocalFileResult {
success: boolean;
}
+export interface HashLocalFileParams {
+ path: string;
+}
+
export interface LocalReadFileParams {
/** Working directory a relative `path` resolves against. See {@link ListLocalFileParams.cwd}. */
cwd?: string;
diff --git a/src/components/DragUploadZone/useLocalDragUpload.ts b/src/components/DragUploadZone/useLocalDragUpload.ts
index 637bbe33960..4876a7208ea 100644
--- a/src/components/DragUploadZone/useLocalDragUpload.ts
+++ b/src/components/DragUploadZone/useLocalDragUpload.ts
@@ -1,6 +1,8 @@
import debug from 'debug';
import { useCallback } from 'react';
+import { getElectronLocalFilePath } from '@/utils/electron/localFilePath';
+
const log = debug('lobe-client:drag-upload:local');
export type DragContentKind = 'files' | 'folders' | 'mixed' | 'none';
@@ -16,30 +18,6 @@ export interface PartitionedDroppedLocalPaths {
localPaths: DroppedLocalPath[];
}
-/**
- * Resolve the absolute filesystem path of a dropped File in Electron.
- * Returns null when not running under Electron or the path cannot be resolved.
- */
-const resolveElectronFilePath = (file: File): string | null => {
- const webUtils = (
- globalThis as unknown as {
- window?: { electron?: { webUtils?: { getPathForFile?: (file: File) => string } } };
- }
- ).window?.electron?.webUtils;
- if (!webUtils?.getPathForFile) {
- log('webUtils.getPathForFile unavailable on window.electron β€” local path cannot be resolved');
- return null;
- }
- try {
- const result = webUtils.getPathForFile(file);
- if (!result) log('webUtils.getPathForFile returned empty for %s', file.name);
- return result || null;
- } catch (error) {
- log('webUtils.getPathForFile threw for %s: %O', file.name, error);
- return null;
- }
-};
-
const safeGetEntry = (item: DataTransferItem): FileSystemEntry | null => {
try {
return item.webkitGetAsEntry();
@@ -149,7 +127,7 @@ export const partitionDroppedItemsAsLocalPaths = async (
const entry = safeGetEntry(item);
const topLevelFile = item.getAsFile();
- const path = topLevelFile ? resolveElectronFilePath(topLevelFile) : null;
+ const path = topLevelFile ? getElectronLocalFilePath(topLevelFile) : null;
if (path) {
localPaths.push({
diff --git a/src/features/ResourceManager/components/UploadDock/Item.tsx b/src/features/ResourceManager/components/UploadDock/Item.tsx
index 4a877e19c8d..e037fe36017 100644
--- a/src/features/ResourceManager/components/UploadDock/Item.tsx
+++ b/src/features/ResourceManager/components/UploadDock/Item.tsx
@@ -77,6 +77,7 @@ const UploadItem = memo<UploadItemProps>(({ error, errorCode, id, file, status,
return (
<Text style={{ fontSize: 12 }} type={'secondary'}>
{formatSize(size)} Β· {t('uploadDock.body.item.pending')}
+ {uploadState?.progress ? ` ${uploadState.progress}%` : ''}
</Text>
);
}
diff --git a/src/services/__tests__/upload.test.ts b/src/services/__tests__/upload.test.ts
index 742cd94ab46..4b36002e7ca 100644
--- a/src/services/__tests__/upload.test.ts
+++ b/src/services/__tests__/upload.test.ts
@@ -4,7 +4,8 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { fileEnv } from '@/envs/file';
import { lambdaClient } from '@/libs/trpc/client';
-import { hashFile, UPLOAD_NETWORK_ERROR, uploadService } from '../upload';
+import { hashFile } from '../hashFile';
+import { UPLOAD_NETWORK_ERROR, uploadService } from '../upload';
const { mockHashHex, mockHashUpdate } = vi.hoisted(() => ({
mockHashHex: vi.fn(() => 'streamed-hash'),
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 8def3249eda..485c9511d08 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -14,6 +14,7 @@ import {
type GlobFilesResult,
type GrepContentParams,
type GrepContentResult,
+ type HashLocalFileParams,
type KillCommandParams,
type KillCommandResult,
type ListLocalFileParams,
@@ -187,6 +188,10 @@ class LocalFileService {
return ensureElectronIpc().localSystem.readFile(params);
}
+ async hashLocalFile(params: HashLocalFileParams): Promise<string> {
+ return ensureElectronIpc().localSystem.hashLocalFile(params);
+ }
+
async readLocalFiles(params: LocalReadFilesParams): Promise<LocalReadFileResult[]> {
return ensureElectronIpc().localSystem.readFiles(params);
}
diff --git a/src/services/hashFile/hash.worker.ts b/src/services/hashFile/hash.worker.ts
new file mode 100644
index 00000000000..5c18a8b136b
--- /dev/null
+++ b/src/services/hashFile/hash.worker.ts
@@ -0,0 +1,20 @@
+import { hashFileStream } from './stream';
+
+export type HashWorkerRequest = { file: File };
+export type HashWorkerResponse =
+ | { type: 'progress'; progress: number }
+ | { type: 'done'; hash: string }
+ | { type: 'error'; message: string };
+
+const post = (message: HashWorkerResponse) => self.postMessage(message);
+
+self.addEventListener('message', async (event: MessageEvent<HashWorkerRequest>) => {
+ try {
+ const hash = await hashFileStream(event.data.file, undefined, (progress) =>
+ post({ progress, type: 'progress' }),
+ );
+ post({ hash, type: 'done' });
+ } catch (error) {
+ post({ message: error instanceof Error ? error.message : String(error), type: 'error' });
+ }
+});
diff --git a/src/services/hashFile/index.test.ts b/src/services/hashFile/index.test.ts
new file mode 100644
index 00000000000..17d42b6e649
--- /dev/null
+++ b/src/services/hashFile/index.test.ts
@@ -0,0 +1,111 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { hashFile } from './index';
+
+const { mockHashLocalFile, mockHashFileStream, desktopFlag } = vi.hoisted(() => ({
+ desktopFlag: { value: false },
+ mockHashFileStream: vi.fn(async () => 'stream-hash'),
+ mockHashLocalFile: vi.fn(async () => 'main-hash'),
+}));
+
+vi.mock('@lobechat/const', () => ({
+ get isDesktop() {
+ return desktopFlag.value;
+ },
+}));
+
+vi.mock('@/services/electron/localFileService', () => ({
+ localFileService: { hashLocalFile: mockHashLocalFile },
+}));
+
+vi.mock('./stream', () => ({ hashFileStream: mockHashFileStream }));
+
+class FakeWorker extends EventTarget {
+ static instances: FakeWorker[] = [];
+ static script: (worker: FakeWorker, data: { file: File }) => void = () => {};
+ terminate = vi.fn();
+
+ constructor() {
+ super();
+ FakeWorker.instances.push(this);
+ }
+
+ postMessage(data: { file: File }) {
+ queueMicrotask(() => FakeWorker.script(this, data));
+ }
+
+ emit(data: unknown) {
+ this.dispatchEvent(new MessageEvent('message', { data }));
+ }
+}
+
+const file = new File(['abc'], 'a.bin');
+
+describe('hashFile', () => {
+ const originalWorker = globalThis.Worker;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ FakeWorker.instances = [];
+ desktopFlag.value = false;
+ (globalThis as any).Worker = FakeWorker;
+ });
+
+ afterEach(() => {
+ (globalThis as any).Worker = originalWorker;
+ delete (globalThis as any).window.electron;
+ });
+
+ it('hashes in a worker on web and relays progress', async () => {
+ const onProgress = vi.fn();
+ FakeWorker.script = (worker) => {
+ worker.emit({ progress: 50, type: 'progress' });
+ worker.emit({ hash: 'worker-hash', type: 'done' });
+ };
+
+ await expect(hashFile(file, undefined, onProgress)).resolves.toBe('worker-hash');
+
+ expect(onProgress).toHaveBeenCalledWith(50);
+ expect(FakeWorker.instances[0].terminate).toHaveBeenCalledOnce();
+ expect(mockHashFileStream).not.toHaveBeenCalled();
+ });
+
+ it('rejects worker errors', async () => {
+ FakeWorker.script = (worker) => worker.emit({ message: 'boom', type: 'error' });
+
+ await expect(hashFile(file)).rejects.toThrow('boom');
+ });
+
+ it('terminates the worker when aborted', async () => {
+ const controller = new AbortController();
+ FakeWorker.script = () => controller.abort();
+
+ await expect(hashFile(file, controller.signal)).rejects.toThrow();
+ expect(FakeWorker.instances[0].terminate).toHaveBeenCalled();
+ });
+
+ it('falls back to inline streaming without Worker support', async () => {
+ (globalThis as any).Worker = undefined;
+
+ await expect(hashFile(file)).resolves.toBe('stream-hash');
+ });
+
+ it('hashes in the Electron main process when a local path resolves', async () => {
+ desktopFlag.value = true;
+ (globalThis as any).window.electron = { webUtils: { getPathForFile: () => '/abs/a.bin' } };
+
+ await expect(hashFile(file)).resolves.toBe('main-hash');
+
+ expect(mockHashLocalFile).toHaveBeenCalledWith({ path: '/abs/a.bin' });
+ expect(FakeWorker.instances).toHaveLength(0);
+ });
+
+ it('uses the worker on Electron for in-memory files without a path', async () => {
+ desktopFlag.value = true;
+ (globalThis as any).window.electron = { webUtils: { getPathForFile: () => '' } };
+ FakeWorker.script = (worker) => worker.emit({ hash: 'worker-hash', type: 'done' });
+
+ await expect(hashFile(file)).resolves.toBe('worker-hash');
+ expect(mockHashLocalFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/hashFile/index.ts b/src/services/hashFile/index.ts
new file mode 100644
index 00000000000..a35cd84be50
--- /dev/null
+++ b/src/services/hashFile/index.ts
@@ -0,0 +1,59 @@
+import { isDesktop } from '@lobechat/const';
+
+import { localFileService } from '@/services/electron/localFileService';
+import { getElectronLocalFilePath } from '@/utils/electron/localFilePath';
+
+import type { HashWorkerRequest, HashWorkerResponse } from './hash.worker';
+import { hashFileStream, type HashProgress } from './stream';
+
+const cancelledError = (signal: AbortSignal) =>
+ signal.reason ?? new Error('Upload cancelled by user');
+
+const hashFileInWorker = (file: File, signal?: AbortSignal, onProgress?: HashProgress) =>
+ new Promise<string>((resolve, reject) => {
+ if (signal?.aborted) return reject(cancelledError(signal));
+
+ const worker = new Worker(new URL('hash.worker.ts', import.meta.url), { type: 'module' });
+ const abort = () => {
+ worker.terminate();
+ reject(cancelledError(signal!));
+ };
+ const finish = (settle: () => void) => {
+ signal?.removeEventListener('abort', abort);
+ worker.terminate();
+ settle();
+ };
+
+ signal?.addEventListener('abort', abort, { once: true });
+ worker.addEventListener('message', (event: MessageEvent<HashWorkerResponse>) => {
+ const data = event.data;
+ if (data.type === 'progress') onProgress?.(data.progress);
+ else if (data.type === 'done') finish(() => resolve(data.hash));
+ else finish(() => reject(new Error(data.message)));
+ });
+ worker.addEventListener('error', (event) =>
+ finish(() => reject(event.error ?? new Error(event.message))),
+ );
+ worker.postMessage({ file } satisfies HashWorkerRequest);
+ });
+
+const hashFileInElectronMain = async (path: string, signal?: AbortSignal) => {
+ const hash = await localFileService.hashLocalFile({ path });
+ if (signal?.aborted) throw cancelledError(signal);
+ return hash;
+};
+
+export const hashFile = async (
+ file: File,
+ signal?: AbortSignal,
+ onProgress?: HashProgress,
+): Promise<string> => {
+ if (isDesktop) {
+ const path = getElectronLocalFilePath(file);
+ if (path) return hashFileInElectronMain(path, signal);
+ }
+
+ if (typeof Worker === 'undefined') return hashFileStream(file, signal, onProgress);
+
+ return hashFileInWorker(file, signal, onProgress);
+};
diff --git a/src/services/hashFile/stream.ts b/src/services/hashFile/stream.ts
new file mode 100644
index 00000000000..75aef585d6f
--- /dev/null
+++ b/src/services/hashFile/stream.ts
@@ -0,0 +1,31 @@
+import { sha256 } from 'js-sha256';
+
+const HASH_BUFFER_SIZE = 4 * 1024 * 1024;
+
+export type HashProgress = (progress: number) => void;
+
+export const hashFileStream = async (
+ file: File,
+ signal?: AbortSignal,
+ onProgress?: HashProgress,
+): Promise<string> => {
+ const hasher = sha256.create();
+ const reader = file.stream().getReader({ mode: 'byob' });
+ let buffer = new ArrayBuffer(HASH_BUFFER_SIZE);
+ let loaded = 0;
+
+ try {
+ while (true) {
+ if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
+
+ const { done, value } = await reader.read(new Uint8Array(buffer));
+ if (done) return hasher.hex();
+ hasher.update(value);
+ loaded += value.byteLength;
+ onProgress?.(file.size > 0 ? Math.min(99, Math.floor((loaded / file.size) * 100)) : 0);
+ buffer = value.buffer as ArrayBuffer;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+};
diff --git a/src/services/upload.ts b/src/services/upload.ts
index 83a9963fd02..e5864c5925e 100644
--- a/src/services/upload.ts
+++ b/src/services/upload.ts
@@ -2,39 +2,20 @@ import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lob
import { parseDataUri } from '@lobechat/model-runtime/utils/uriParser';
import { uuid } from '@lobechat/utils';
import dayjs from 'dayjs';
-import { sha256 } from 'js-sha256';
import { fileEnv } from '@/envs/file';
import { lambdaClient } from '@/libs/trpc/client';
import type { FileMetadata, UploadBase64ToS3Result } from '@/types/files';
import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';
+import { hashFile } from './hashFile';
+
export const UPLOAD_NETWORK_ERROR = 'NetWorkError';
const MAX_MULTIPART_PARTS = 10_000;
-const HASH_BUFFER_SIZE = 4 * 1024 * 1024;
const MULTIPART_PART_SIZE = 32 * 1024 * 1024;
const MULTIPART_UPLOAD_THRESHOLD = 64 * 1024 * 1024;
-export const hashFile = async (file: File, signal?: AbortSignal): Promise<string> => {
- const hasher = sha256.create();
- const reader = file.stream().getReader({ mode: 'byob' });
- let buffer = new ArrayBuffer(HASH_BUFFER_SIZE);
-
- try {
- while (true) {
- if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
-
- const { done, value } = await reader.read(new Uint8Array(buffer));
- if (done) return hasher.hex();
- hasher.update(value);
- buffer = value.buffer as ArrayBuffer;
- }
- } finally {
- reader.releaseLock();
- }
-};
-
/**
* Generate file storage path metadata for S3-compatible storage
* @param originalFilename - Original filename
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index 4b047b19556..57099abe4c9 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -4,7 +4,8 @@ import { t } from 'i18next';
import { handleFileUploadError } from '@/business/client/handleFileUploadError';
import { fileService } from '@/services/file';
-import { hashFile, uploadService } from '@/services/upload';
+import { hashFile } from '@/services/hashFile';
+import { uploadService } from '@/services/upload';
import type { StoreSetter } from '@/store/types';
import type { UploadFileItem } from '@/types/files';
import { getAudioDuration } from '@/utils/client/audioDuration';
@@ -160,7 +161,13 @@ export class FileUploadActionImpl {
const dimensions = await getImageDimensions(normalizedFile);
// 2. check file hash
- const hash = await hashFile(normalizedFile, abortController?.signal);
+ const hash = await hashFile(normalizedFile, abortController?.signal, (progress) => {
+ onStatusUpdate?.({
+ id: statusId,
+ type: 'updateFile',
+ value: { status: 'pending', uploadState: { progress, restTime: 0, speed: 0 } },
+ });
+ });
const checkStatus = await fileService.checkFileHash(hash);
let metadata: ExistingFileMetadata;
diff --git a/src/utils/electron/localFilePath.ts b/src/utils/electron/localFilePath.ts
new file mode 100644
index 00000000000..b92ae6c4cf7
--- /dev/null
+++ b/src/utils/electron/localFilePath.ts
@@ -0,0 +1,23 @@
+import debug from 'debug';
+
+const log = debug('lobe-client:electron:local-file-path');
+
+export const getElectronLocalFilePath = (file: File): string | null => {
+ const webUtils = (
+ globalThis as unknown as {
+ window?: { electron?: { webUtils?: { getPathForFile?: (file: File) => string } } };
+ }
+ ).window?.electron?.webUtils;
+ if (!webUtils?.getPathForFile) {
+ log('webUtils.getPathForFile unavailable on window.electron β€” local path cannot be resolved');
+ return null;
+ }
+ try {
+ const result = webUtils.getPathForFile(file);
+ if (!result) log('webUtils.getPathForFile returned empty for %s', file.name);
+ return result || null;
+ } catch (error) {
+ log('webUtils.getPathForFile threw for %s: %O', file.name, error);
+ return null;
+ }
+};