Skip to content

Commit 5a3ccd6

Browse files
committed
fix(twitch): fence connection startup after account shutdown
1 parent b1b26be commit 5a3ccd6

2 files changed

Lines changed: 105 additions & 4 deletions

File tree

‎extensions/twitch/src/twitch-client.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
*/
1111

1212
import { expectDefined } from "@openclaw/normalization-core";
13+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
1314
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
1415
import { resolveTwitchToken } from "./token.js";
1516
import { TwitchClientManager } from "./twitch-client.js";
@@ -297,6 +298,94 @@ describe("TwitchClientManager", () => {
297298
expect(mockQuit).toHaveBeenCalledTimes(2);
298299
});
299300

301+
it.each(["account", "all"] as const)(
302+
"does not create a client when %s disconnect completes during authentication setup",
303+
async (scope) => {
304+
const authentication = createDeferred<string>();
305+
mockAddUserForToken.mockImplementationOnce(() => authentication.promise);
306+
const account = {
307+
...testAccount,
308+
clientSecret: "test-client-secret",
309+
refreshToken: "test-refresh-token",
310+
};
311+
manager.onMessage(account, vi.fn());
312+
const connection = manager.getClient(account);
313+
314+
expect(mockAddUserForToken).toHaveBeenCalledOnce();
315+
if (scope === "account") {
316+
await manager.disconnect(account);
317+
} else {
318+
await manager.disconnectAll();
319+
}
320+
authentication.resolve("123456");
321+
322+
await expect(connection).rejects.toThrow("Twitch connection cancelled");
323+
expect(mockConnect).not.toHaveBeenCalled();
324+
expect(managerState(manager).clients.size).toBe(0);
325+
expect(managerState(manager).messageHandlers.has(manager.getAccountKey(account))).toBe(
326+
false,
327+
);
328+
},
329+
);
330+
331+
it("keeps a restarted account connection when stale authentication resolves afterward", async () => {
332+
const authentication = createDeferred<string>();
333+
mockAddUserForToken.mockImplementationOnce(() => authentication.promise);
334+
const account = {
335+
...testAccount,
336+
clientSecret: "test-client-secret",
337+
refreshToken: "test-refresh-token",
338+
};
339+
const staleConnection = manager.getClient(account);
340+
const staleOutcome = staleConnection.then(
341+
() => "connected" as const,
342+
() => "cancelled" as const,
343+
);
344+
345+
await manager.disconnect(account);
346+
const currentConnection = manager.getClient(account);
347+
348+
try {
349+
expect(mockAddUserForToken).toHaveBeenCalledTimes(2);
350+
const activeClient = await currentConnection;
351+
authentication.resolve("123456");
352+
353+
expect(await staleOutcome).toBe("cancelled");
354+
expect(managerState(manager).clients.get(manager.getAccountKey(account))).toBe(
355+
activeClient,
356+
);
357+
expect(mockConnect).toHaveBeenCalledOnce();
358+
} finally {
359+
authentication.resolve("123456");
360+
await Promise.allSettled([staleConnection, currentConnection]);
361+
}
362+
});
363+
364+
it("keeps another account connected when cancelling an authentication-pending account", async () => {
365+
const authentication = createDeferred<string>();
366+
mockAddUserForToken.mockImplementationOnce(() => authentication.promise);
367+
const account = {
368+
...testAccount,
369+
clientSecret: "test-client-secret",
370+
refreshToken: "test-refresh-token",
371+
};
372+
const staleConnection = manager.getClient(account);
373+
const staleOutcome = staleConnection.then(
374+
() => "connected" as const,
375+
() => "cancelled" as const,
376+
);
377+
const activeClient = await manager.getClient(testAccount2);
378+
379+
await manager.disconnect(account);
380+
authentication.resolve("123456");
381+
382+
expect(await staleOutcome).toBe("cancelled");
383+
expect(managerState(manager).clients.get(manager.getAccountKey(testAccount2))).toBe(
384+
activeClient,
385+
);
386+
expect(mockConnect).toHaveBeenCalledOnce();
387+
});
388+
300389
it("should create separate clients for different accounts", async () => {
301390
await manager.getClient(testAccount);
302391
await manager.getClient(testAccount2);

‎extensions/twitch/src/twitch-client.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,13 @@ export class TwitchClientManager {
125125
return pending;
126126
}
127127

128-
const connection = this.createConnectedClient(key, account, cfg, accountId);
128+
const connection: Promise<ChatClient> = this.createConnectedClient(
129+
key,
130+
account,
131+
() => this.connectionPromises.get(key) === connection,
132+
cfg,
133+
accountId,
134+
);
129135
this.connectionPromises.set(key, connection);
130136
try {
131137
return await connection;
@@ -139,6 +145,7 @@ export class TwitchClientManager {
139145
private async createConnectedClient(
140146
key: string,
141147
account: TwitchAccountConfig,
148+
ownsConnection: () => boolean,
142149
cfg?: OpenClawConfig,
143150
accountId?: string,
144151
): Promise<ChatClient> {
@@ -163,6 +170,9 @@ export class TwitchClientManager {
163170
const normalizedToken = normalizeToken(tokenResolution.token);
164171

165172
const authProvider = await this.createAuthProvider(account, normalizedToken);
173+
if (!ownsConnection()) {
174+
throw new Error(`Twitch connection cancelled for ${account.username}`);
175+
}
166176

167177
const client = new ChatClient({
168178
authProvider,
@@ -373,20 +383,22 @@ export class TwitchClientManager {
373383
const key = this.getAccountKey(account);
374384
const client = this.clients.get(key);
375385
const pendingClient = this.pendingClients.get(key);
386+
const pendingConnection = this.connectionPromises.delete(key);
376387

377388
if (pendingClient) {
378389
pendingClient.quit();
379390
this.pendingClients.delete(key);
380-
this.connectionPromises.delete(key);
381-
this.clearMessageHandler(key);
382391
}
383392

384393
if (client) {
385394
client.quit();
386395
this.clients.delete(key);
387-
this.clearMessageHandler(key);
388396
this.logger.info(`Disconnected ${key}`);
389397
}
398+
399+
if (pendingConnection || pendingClient || client) {
400+
this.clearMessageHandler(key);
401+
}
390402
}
391403

392404
/**

0 commit comments

Comments
 (0)