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.

πŸ› fix(desktop): stop tool_result image upload from crashing the main process (#17837)

Arvin Xuadc8d251f17c
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index c3d77a03f80..ecad0854927 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -1,5 +1,8 @@
+import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePort';
+
import type HeterogeneousAgentImplementation from './HeterogeneousAgentImpl';
import { ControllerModule, IpcMethod } from './index';
+import RemoteServerConfigCtr from './RemoteServerConfigCtr';
type Implementation = HeterogeneousAgentImplementation;
@@ -13,10 +16,27 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
private implementationPromise?: Promise<Implementation>;
+ /**
+ * Resolved on this side of the lazy boundary and handed to the implementation.
+ * This controller lives in the eager main chunk next to `App` and
+ * `RemoteServerConfigCtr`; the implementation is a deferred chunk where the
+ * same `getController` lookup came back `undefined` at runtime and crashed the
+ * main process. Missing controller degrades to "no authed remote server",
+ * which makes the image upload a no-op instead of an unhandled rejection.
+ */
+ private remoteServerAuth: RemoteServerAuth = {
+ getAccessToken: async () => (await this.remoteServerConfigCtr?.getAccessToken()) ?? null,
+ getServerUrl: async () => (await this.remoteServerConfigCtr?.getRemoteServerUrl()) ?? null,
+ };
+
+ private get remoteServerConfigCtr(): RemoteServerConfigCtr | undefined {
+ return this.app.getController(RemoteServerConfigCtr);
+ }
+
private getImplementation = (): Promise<Implementation> => {
this.implementationPromise ??= import('./HeterogeneousAgentImpl')
.then(({ default: Implementation }) => {
- const implementation = new Implementation(this.app);
+ const implementation = new Implementation(this.app, this.remoteServerAuth);
implementation.afterAppReady();
return implementation;
})
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index 6708ac854c0..9b517877066 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -71,7 +71,10 @@ import {
consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
fetchCodexQuota,
} from '@/modules/heterogeneousAgent/codexQuota';
-import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';
+import {
+ createLambdaFileStorePort,
+ type RemoteServerAuth,
+} from '@/modules/heterogeneousAgent/fileStorePort';
import type {
HeterogeneousAgentBuildPlan,
HeterogeneousAgentImageAttachment,
@@ -331,7 +334,27 @@ interface InterventionSlot {
}
export default class HeterogeneousAgentCtr {
- constructor(public app: App) {}
+ /**
+ * Remote-server credentials for the tool_result image upload.
+ *
+ * Injected by the eager `HeterogeneousAgentCtr` wrapper rather than resolved
+ * here: this file is a deferred chunk, and reaching back into the App's
+ * controller registry from it is exactly what broke β€” the lookup resolved to
+ * `undefined`, and the resulting TypeError escaped as an unhandled rejection
+ * that killed the main process. The fallback keeps standalone construction
+ * (tests, future call sites) working and never throws.
+ */
+ private readonly remoteServerAuth: RemoteServerAuth;
+
+ constructor(
+ public app: App,
+ remoteServerAuth?: RemoteServerAuth,
+ ) {
+ this.remoteServerAuth = remoteServerAuth ?? {
+ getAccessToken: async () => (await this.remoteServerConfigCtr?.getAccessToken()) ?? null,
+ getServerUrl: async () => (await this.remoteServerConfigCtr?.getRemoteServerUrl()) ?? null,
+ };
+ }
private sessions = new Map<string, AgentSession>();
/**
@@ -357,7 +380,11 @@ export default class HeterogeneousAgentCtr {
});
private readonly codexQuotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
- private get remoteServerConfigCtr() {
+ /**
+ * Typed as optional on purpose: a deferred chunk cannot assume the registry
+ * hands back the controller it asks for.
+ */
+ private get remoteServerConfigCtr(): RemoteServerConfigCtr | undefined {
return this.app.getController(RemoteServerConfigCtr);
}
@@ -367,10 +394,7 @@ export default class HeterogeneousAgentCtr {
* of heavy base64. Mirrors what `lh hetero exec` does for the gateway path.
*/
private uploadResultImage = createFileStoreImageUploader(() =>
- createLambdaFileStorePort({
- getAccessToken: () => this.remoteServerConfigCtr.getAccessToken(),
- getServerUrl: async () => (await this.remoteServerConfigCtr.getRemoteServerUrl()) ?? null,
- }),
+ createLambdaFileStorePort(this.remoteServerAuth),
);
private resolveSessionCommand(session: AgentSession): string {
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts
index 315c3846959..f36b86740f2 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
+import type { RemoteServerAuth } from '@/modules/heterogeneousAgent/fileStorePort';
import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
@@ -12,8 +13,8 @@ const implementationMocks = vi.hoisted(() => ({
vi.mock('../HeterogeneousAgentImpl', () => ({
default: class MockHeterogeneousAgentImplementation {
- constructor(app: App) {
- implementationMocks.constructor(app);
+ constructor(app: App, remoteServerAuth?: RemoteServerAuth) {
+ implementationMocks.constructor(app, remoteServerAuth);
}
afterAppReady() {
@@ -27,6 +28,10 @@ vi.mock('../HeterogeneousAgentImpl', () => ({
}));
describe('HeterogeneousAgentCtr lazy implementation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
it('defers the heavy implementation and initializes it exactly once on first use', async () => {
const app = {} as App;
const controller = new HeterogeneousAgentCtr(app);
@@ -40,8 +45,32 @@ describe('HeterogeneousAgentCtr lazy implementation', () => {
await (controller as any).startSession({ prompt: 'second' });
expect(implementationMocks.constructor).toHaveBeenCalledOnce();
- expect(implementationMocks.constructor).toHaveBeenCalledWith(app);
+ expect(implementationMocks.constructor).toHaveBeenCalledWith(app, expect.any(Object));
expect(implementationMocks.afterAppReady).toHaveBeenCalledOnce();
expect(implementationMocks.startSession).toHaveBeenCalledTimes(2);
});
+
+ it('injects remote-server auth resolved on the eager side of the lazy boundary', async () => {
+ const remoteServerConfigCtr = {
+ getAccessToken: vi.fn(async () => 'token-1'),
+ getRemoteServerUrl: vi.fn(async () => 'https://cloud.lobehub.com'),
+ };
+ const getController = vi.fn(() => remoteServerConfigCtr as any);
+ const app = { getController } as unknown as App;
+
+ const controller = new HeterogeneousAgentCtr(app);
+ await (controller as any).startSession({ prompt: 'first' });
+
+ const auth = implementationMocks.constructor.mock.calls[0][1] as RemoteServerAuth;
+
+ await expect(auth.getServerUrl()).resolves.toBe('https://cloud.lobehub.com');
+ await expect(auth.getAccessToken()).resolves.toBe('token-1');
+
+ // A registry lookup that comes back empty must degrade to "no authed remote
+ // server" β€” never a throw, which would escape as a fatal unhandled rejection.
+ getController.mockReturnValue(undefined as any);
+
+ await expect(auth.getServerUrl()).resolves.toBeNull();
+ await expect(auth.getAccessToken()).resolves.toBeNull();
+ });
});
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
index 124bef3bd04..35260532464 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts
@@ -38,6 +38,36 @@ describe('createLambdaFileStorePort', () => {
).toBeUndefined();
});
+ it('keeps a sibling rejection handled when an auth callback throws synchronously', async () => {
+ const unhandled: unknown[] = [];
+ const onUnhandledRejection = (reason: unknown) => unhandled.push(reason);
+ process.on('unhandledRejection', onUnhandledRejection);
+
+ try {
+ // Shape of the real failure: `getServerUrl` is async (rejects) while
+ // `getAccessToken` is a plain arrow that throws. Building the `Promise.all`
+ // argument list must not leave the first rejection without a subscriber β€”
+ // in Electron main an unhandled rejection kills the process.
+ await expect(
+ createLambdaFileStorePort({
+ getAccessToken: () => {
+ throw new TypeError("Cannot read properties of undefined (reading 'getAccessToken')");
+ },
+ getServerUrl: async () => {
+ throw new TypeError("Cannot read properties of undefined (reading 'getServerUrl')");
+ },
+ }),
+ ).rejects.toThrow(TypeError);
+
+ // Node reports unhandled rejections once the microtask queue drains.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(unhandled).toEqual([]);
+ } finally {
+ process.off('unhandledRejection', onUnhandledRejection);
+ }
+ });
+
it('POSTs a superjson-serialized input to the lambda procedure and deserializes the result', async () => {
vi.mocked(fetch).mockResolvedValue(trpcOk({ isExist: true, url: 'files/a/b.png' }) as any);
diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts
index a7059e498f1..67fc5dfbeeb 100644
--- a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts
+++ b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts
@@ -75,7 +75,16 @@ const lambdaMutation = async <T>(
export const createLambdaFileStorePort = async (
auth: RemoteServerAuth,
): Promise<FileStorePort | undefined> => {
- const [serverUrl, accessToken] = await Promise.all([auth.getServerUrl(), auth.getAccessToken()]);
+ // Sequential on purpose. Both reads are local (settings store + `safeStorage`
+ // decryption), so there is nothing to win by parallelizing β€” while
+ // `Promise.all([auth.getServerUrl(), auth.getAccessToken()])` is a trap: the
+ // argument list is evaluated first, so a callback that throws *synchronously*
+ // abandons the array before `Promise.all` ever subscribes to its sibling,
+ // orphaning that rejection. In Electron main an unhandled rejection is fatal
+ // (`process-error-handlers` re-throws it), so an injected-callback bug would
+ // kill the app instead of degrading to "no image upload".
+ const serverUrl = await auth.getServerUrl();
+ const accessToken = await auth.getAccessToken();
if (!serverUrl || !accessToken) {
logger.debug('No authed remote server β€” skipping tool_result image upload');