Skip to content

Commit 53e36c1

Browse files
committed
🐛 fix: resolve undefined when plugin is not in LobeChat
1 parent c94b081 commit 53e36c1

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/client/lobeChat.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,21 @@ class LobeChat {
2525
resolve(undefined as any);
2626
return;
2727
}
28+
29+
const timer = setTimeout(() => {
30+
resolve(undefined as any);
31+
// eslint-disable-next-line @typescript-eslint/no-use-before-define
32+
window.removeEventListener('message', receiverData);
33+
}, 1000);
34+
2835
const receiverData = (e: MessageEvent) => {
2936
if (e.data.type === PluginChannel.initStandalonePlugin) {
3037
// TODO: drop e.data.props in v2
3138
const payload: PluginRequestPayload = e.data.payload || e.data.props;
3239
const func = payload.apiName;
3340
const args = JSON.parse(payload.arguments || '{}');
41+
clearTimeout(timer);
42+
3443
resolve({
3544
arguments: args,
3645
name: func,

tests/client/lobeChat.test.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ describe('lobeChat', () => {
9191
});
9292
});
9393

94-
describe('fetchPluginPayload', () => {
94+
describe('getPluginPayload', () => {
9595
it('should resolve undefined when window is undefined', async () => {
9696
const originalWindow = global.window;
9797
global.window = undefined as any;
@@ -172,6 +172,25 @@ describe('lobeChat', () => {
172172
expect.any(Function),
173173
);
174174
});
175+
176+
it('should resolve undefined if message is not received within timeout', async () => {
177+
vi.useFakeTimers();
178+
179+
const promise = lobeChat.getPluginPayload();
180+
181+
// Fast-forward until all timers have been executed
182+
vi.runAllTimers();
183+
184+
const result = await promise;
185+
186+
expect(result).toBeUndefined();
187+
expect(global.window.removeEventListener).toHaveBeenCalledWith(
188+
'message',
189+
expect.any(Function),
190+
);
191+
192+
vi.useRealTimers();
193+
});
175194
});
176195

177196
describe('fetchPluginSettings', () => {

0 commit comments

Comments
 (0)