feat: pass JID on connect; extract startAccount() helper; poll 30s for new accounts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-29 11:44:54 +05:30
parent e8aaae4188
commit 952a0e9b49
5 changed files with 58 additions and 18 deletions
+36 -13
View File
@@ -45,19 +45,10 @@ async function bootstrap() {
indexWorker.on('completed', (job) => logger.info({ jobId: job.id }, 'Index job completed'));
indexWorker.on('failed', (job, err) => logger.error({ jobId: job?.id, err }, 'Index job failed'));
const accounts = await prisma.account.findMany({
where: { status: 'ACTIVE', platform: 'whatsapp' },
});
if (accounts.length === 0) {
logger.warn('No active WhatsApp accounts found — seed one in the Account table (see docs)');
}
const groupMaps = new Map<string, Map<string, string>>();
for (const account of accounts) {
async function startAccount(account: { id: string; sessionPath: string }) {
groupMaps.set(account.id, new Map());
try {
await pool.add(
account.id,
@@ -129,13 +120,13 @@ async function bootstrap() {
}).catch((err) => logger.error({ accountId, err }, 'Failed to store QR in DB'));
logger.info({ accountId }, 'QR code updated');
},
async (status, accountId) => {
async (status, accountId, jid?) => {
if (status === 'connected') {
await prisma.account.update({
where: { id: accountId },
data: { qrCode: null, status: 'ACTIVE' },
data: { qrCode: null, status: 'ACTIVE', ...(jid ? { jid } : {}) },
}).catch((err) => logger.error({ accountId, err }, 'Failed to update account status'));
logger.info({ accountId }, 'Account connected — QR cleared');
logger.info({ accountId, jid }, 'Account connected — QR cleared');
} else if (status === 'logged_out') {
await prisma.account.update({
where: { id: accountId },
@@ -150,8 +141,40 @@ async function bootstrap() {
}
}
// Load ACTIVE and DISCONNECTED accounts at startup (DISCONNECTED ones need re-auth)
const accounts = await prisma.account.findMany({
where: { status: { in: ['ACTIVE', 'DISCONNECTED'] }, platform: 'whatsapp' },
select: { id: true, sessionPath: true },
});
if (accounts.length === 0) {
logger.warn('No WhatsApp accounts found — add one via the dashboard');
}
for (const account of accounts) {
await startAccount(account);
}
logger.info({ accountCount: accounts.length }, 'Tower worker ready');
// Poll every 30s for accounts added via the dashboard while worker is running
setInterval(async () => {
try {
const all = await prisma.account.findMany({
where: { status: { in: ['ACTIVE', 'DISCONNECTED'] }, platform: 'whatsapp' },
select: { id: true, sessionPath: true },
});
for (const account of all) {
if (!pool.get(account.id)) {
logger.info({ accountId: account.id }, 'New account detected — starting session');
await startAccount(account);
}
}
} catch (err) {
logger.error({ err }, 'Error polling for new accounts');
}
}, 30_000);
const shutdown = async () => {
logger.info('Shutting down...');
await pool.closeAll();