Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(gateway): isolate telegram session routing by chat thread
Jiayuan Zhang0e54c4118c65
diff --git a/apps/gateway/migrations/telegram-users.sql b/apps/gateway/migrations/telegram-users.sqlindex 376f86cefe..e67cc1bd7e 100644--- a/apps/gateway/migrations/telegram-users.sql+++ b/apps/gateway/migrations/telegram-users.sql@@ -1,6 +1,7 @@-- Telegram users table for Gateway-- Run this manually before starting the Gateway with Telegram enabled.+DROP TABLE IF EXISTS telegram_thread_routes;DROP TABLE IF EXISTS telegram_users;CREATE TABLE telegram_users (@@ -16,3 +17,18 @@ CREATE TABLE telegram_users (telegram_last_name VARCHAR(255),INDEX idx_device_id (device_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;++CREATE TABLE telegram_thread_routes (+ telegram_user_id VARCHAR(64) NOT NULL,+ chat_id VARCHAR(64) NOT NULL,+ thread_id VARCHAR(64) NOT NULL DEFAULT '0',+ conversation_id VARCHAR(64) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,+ PRIMARY KEY (telegram_user_id, chat_id, thread_id),+ INDEX idx_conversation_id (conversation_id),+ CONSTRAINT fk_telegram_thread_routes_user+ FOREIGN KEY (telegram_user_id)+ REFERENCES telegram_users(telegram_user_id)+ ON DELETE CASCADE+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;diff --git a/apps/gateway/telegram/message-context-queue.ts b/apps/gateway/telegram/message-context-queue.tsindex fd630bb73b..323a477c36 100644--- a/apps/gateway/telegram/message-context-queue.ts+++ b/apps/gateway/telegram/message-context-queue.ts@@ -14,32 +14,32 @@ export class MessageContextQueue {private readonly pending = new Map<string, MessageContext[]>();private readonly active = new Map<string, MessageContext>();- enqueue(deviceId: string, context: MessageContext): void {- const queue = this.pending.get(deviceId);+ enqueue(contextKey: string, context: MessageContext): void {+ const queue = this.pending.get(contextKey);if (queue) {queue.push(context);return;}- this.pending.set(deviceId, [context]);+ this.pending.set(contextKey, [context]);}/*** Bind the next pending context to the active run for this device.* If a run is already active, keep it unchanged.*/- activate(deviceId: string): MessageContext | undefined {- const current = this.active.get(deviceId);+ activate(contextKey: string): MessageContext | undefined {+ const current = this.active.get(contextKey);if (current) return current;- const queue = this.pending.get(deviceId);+ const queue = this.pending.get(contextKey);if (!queue || queue.length === 0) return undefined;const next = queue.shift();if (queue.length === 0) {- this.pending.delete(deviceId);+ this.pending.delete(contextKey);}if (next) {- this.active.set(deviceId, next);+ this.active.set(contextKey, next);}return next;}@@ -48,11 +48,11 @@ export class MessageContextQueue {* Get the context to use for outbound sends.* Prefer active run context; otherwise fall back to oldest pending.*/- peekForSend(deviceId: string): MessageContext | undefined {- const current = this.active.get(deviceId);+ peekForSend(contextKey: string): MessageContext | undefined {+ const current = this.active.get(contextKey);if (current) return current;- const queue = this.pending.get(deviceId);+ const queue = this.pending.get(contextKey);return queue?.[0];}@@ -60,19 +60,19 @@ export class MessageContextQueue {* Release one context after a run completes/errors.* Prefer active context; if none active, release oldest pending.*/- release(deviceId: string): MessageContext | undefined {- const current = this.active.get(deviceId);+ release(contextKey: string): MessageContext | undefined {+ const current = this.active.get(contextKey);if (current) {- this.active.delete(deviceId);+ this.active.delete(contextKey);return current;}- const queue = this.pending.get(deviceId);+ const queue = this.pending.get(contextKey);if (!queue || queue.length === 0) return undefined;const next = queue.shift();if (queue.length === 0) {- this.pending.delete(deviceId);+ this.pending.delete(contextKey);}return next;}diff --git a/apps/gateway/telegram/telegram-user.store.ts b/apps/gateway/telegram/telegram-user.store.tsindex 075e0b91ad..66012e037f 100644--- a/apps/gateway/telegram/telegram-user.store.ts+++ b/apps/gateway/telegram/telegram-user.store.ts@@ -27,15 +27,31 @@ interface TelegramUserRow extends RowDataPacket {telegram_last_name: string | null;}+interface TelegramThreadRouteRow extends RowDataPacket {+ telegram_user_id: string;+ chat_id: string;+ thread_id: string;+ conversation_id: string;+}++interface LocalStoreFileShape {+ users?: Record<string, TelegramUser>;+ threadRoutes?: Record<string, Record<string, string>>;+}+const LOCAL_STORE_DIR = join(DATA_DIR, "gateway");const LOCAL_STORE_PATH = join(LOCAL_STORE_DIR, "telegram-users.json");+const DEFAULT_THREAD_ID = "0";@Injectable()export class TelegramUserStore {private readonly logger = new Logger(TelegramUserStore.name);/** Local file-backed store, keyed by telegramUserId */private localStore = new Map<string, TelegramUser>();+ /** Local per-thread conversation routes, keyed by telegramUserId -> routeKey(chatId:threadId) -> conversationId */+ private localThreadRoutes = new Map<string, Map<string, string>>();private localStoreLoaded = false;+ private warnedMissingThreadTable = false;constructor(@Inject(DatabaseService) private readonly db: DatabaseService) {}@@ -45,6 +61,17 @@ export class TelegramUserStore {return maybe.code === "ER_BAD_FIELD_ERROR" && (maybe.message ?? "").includes("conversation_id");}+ private hasMissingThreadRoutesTableError(err: unknown): boolean {+ if (!err || typeof err !== "object") return false;+ const maybe = err as { code?: string; message?: string };+ if (maybe.code === "ER_NO_SUCH_TABLE") return true;+ return maybe.code === "ER_BAD_FIELD_ERROR" && (maybe.message ?? "").includes("telegram_thread_routes");+ }++ private getThreadRouteKey(chatId: string, threadId?: string): string {+ return `${chatId}:${threadId?.trim() || DEFAULT_THREAD_ID}`;+ }+/** Find user by Telegram user ID */async findByTelegramUserId(telegramUserId: string): Promise<TelegramUser | null> {if (!this.db.isAvailable()) {@@ -80,6 +107,76 @@ export class TelegramUserStore {return this.rowToUser(rows[0]!);}+ async getThreadConversation(+ telegramUserId: string,+ chatId: string,+ threadId?: string,+ ): Promise<string | null> {+ const routeKey = this.getThreadRouteKey(chatId, threadId);++ if (!this.db.isAvailable()) {+ await this.ensureLocalStoreLoaded();+ const routes = this.localThreadRoutes.get(telegramUserId);+ return routes?.get(routeKey) ?? null;+ }++ try {+ const rows = await this.db.query<TelegramThreadRouteRow[]>(+ `SELECT conversation_id+ FROM telegram_thread_routes+ WHERE telegram_user_id = ? AND chat_id = ? AND thread_id = ?+ LIMIT 1`,+ [telegramUserId, chatId, threadId?.trim() || DEFAULT_THREAD_ID],+ );+ return rows[0]?.conversation_id ?? null;+ } catch (err) {+ if (!this.hasMissingThreadRoutesTableError(err)) throw err;+ if (!this.warnedMissingThreadTable) {+ this.warnedMissingThreadTable = true;+ this.logger.warn(+ "telegram_thread_routes table missing; per-thread conversation routing will fall back to default conversation",+ );+ }+ return null;+ }+ }++ async setThreadConversation(+ telegramUserId: string,+ chatId: string,+ conversationId: string,+ threadId?: string,+ ): Promise<void> {+ const routeKey = this.getThreadRouteKey(chatId, threadId);++ if (!this.db.isAvailable()) {+ await this.ensureLocalStoreLoaded();+ const routes = this.localThreadRoutes.get(telegramUserId) ?? new Map<string, string>();+ routes.set(routeKey, conversationId);+ this.localThreadRoutes.set(telegramUserId, routes);+ await this.saveLocalStore();+ return;+ }++ try {+ await this.db.execute(+ `INSERT INTO telegram_thread_routes (+ telegram_user_id, chat_id, thread_id, conversation_id+ ) VALUES (?, ?, ?, ?)+ ON DUPLICATE KEY UPDATE conversation_id = VALUES(conversation_id), updated_at = CURRENT_TIMESTAMP`,+ [telegramUserId, chatId, threadId?.trim() || DEFAULT_THREAD_ID, conversationId],+ );+ } catch (err) {+ if (!this.hasMissingThreadRoutesTableError(err)) throw err;+ if (!this.warnedMissingThreadTable) {+ this.warnedMissingThreadTable = true;+ this.logger.warn(+ "telegram_thread_routes table missing; per-thread conversation routing will not persist in DB",+ );+ }+ }+ }+/** Create or update a Telegram user */async upsert(data: TelegramUserCreate): Promise<TelegramUser> {if (!this.db.isAvailable()) {@@ -198,13 +295,28 @@ export class TelegramUserStore {try {const data = await readFile(LOCAL_STORE_PATH, "utf-8");- const records = JSON.parse(data) as Record<string, TelegramUser>;+ const parsed = JSON.parse(data) as LocalStoreFileShape | Record<string, TelegramUser>;+ const records = (parsed as LocalStoreFileShape).users+ ?? (parsed as Record<string, TelegramUser>);+ const threadRoutes = (parsed as LocalStoreFileShape).threadRoutes ?? {};+for (const [key, user] of Object.entries(records)) {// Restore Date objects from JSON stringsuser.createdAt = new Date(user.createdAt);user.updatedAt = new Date(user.updatedAt);this.localStore.set(key, user);}++ for (const [userId, routes] of Object.entries(threadRoutes)) {+ const map = new Map<string, string>();+ for (const [routeKey, conversationId] of Object.entries(routes)) {+ if (!routeKey || !conversationId) continue;+ map.set(routeKey, conversationId);+ }+ if (map.size > 0) {+ this.localThreadRoutes.set(userId, map);+ }+ }this.logger.log(`Loaded ${this.localStore.size} Telegram user(s) from ${LOCAL_STORE_PATH}`);} catch {// File doesn't exist or is invalid — start fresh@@ -217,8 +329,16 @@ export class TelegramUserStore {for (const [key, user] of this.localStore) {obj[key] = user;}+ const threadRoutes: Record<string, Record<string, string>> = {};+ for (const [userId, routes] of this.localThreadRoutes) {+ threadRoutes[userId] = Object.fromEntries(routes.entries());+ }await mkdir(LOCAL_STORE_DIR, { recursive: true });- await writeFile(LOCAL_STORE_PATH, JSON.stringify(obj, null, 2), "utf-8");+ await writeFile(+ LOCAL_STORE_PATH,+ JSON.stringify({ users: obj, threadRoutes }, null, 2),+ "utf-8",+ );}/** Upsert to local file store */diff --git a/apps/gateway/telegram/telegram.service.ts b/apps/gateway/telegram/telegram.service.tsindex 473dccde06..f32d9f46f6 100644--- a/apps/gateway/telegram/telegram.service.ts+++ b/apps/gateway/telegram/telegram.service.ts@@ -211,6 +211,56 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {@Inject(TelegramUserStore) private readonly userStore: TelegramUserStore,) {}+ private makeConversationContextKey(deviceId: string, conversationId?: string): string {+ return `${deviceId}:${conversationId ?? "default"}`;+ }++ private getThreadRoute(ctx: Context): { chatId: string; threadId: string } | null {+ const chatId = ctx.chat?.id;+ if (chatId === undefined || chatId === null) return null;+ const maybeMsg = ctx.message as { message_thread_id?: number } | undefined;+ const threadId = maybeMsg?.message_thread_id != null ? String(maybeMsg.message_thread_id) : "0";+ return { chatId: String(chatId), threadId };+ }++ private async resolveConversationForContext(user: TelegramUser, ctx: Context): Promise<string> {+ const fallbackConversationId = user.conversationId ?? user.agentId;+ const threadRoute = this.getThreadRoute(ctx);+ if (!threadRoute) return fallbackConversationId;++ const mappedConversationId = await this.userStore.getThreadConversation(+ user.telegramUserId,+ threadRoute.chatId,+ threadRoute.threadId,+ );+ if (mappedConversationId) {+ return mappedConversationId;+ }++ await this.userStore.setThreadConversation(+ user.telegramUserId,+ threadRoute.chatId,+ fallbackConversationId,+ threadRoute.threadId,+ );+ return fallbackConversationId;+ }++ private async bindConversationToContext(+ user: TelegramUser,+ ctx: Context,+ conversationId: string,+ ): Promise<void> {+ const threadRoute = this.getThreadRoute(ctx);+ if (!threadRoute) return;+ await this.userStore.setThreadConversation(+ user.telegramUserId,+ threadRoute.chatId,+ conversationId,+ threadRoute.threadId,+ );+ }+// ── Lifecycle ──async onModuleInit(): Promise<void> {@@ -703,7 +753,6 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {if (user) {// ACK: 👀 reaction on the original messageawait this.addReaction(msg.chat.id, msg.message_id, "👀");- this.storeMessageContext(user.deviceId, msg.chat.id, msg.message_id);// Prepend reply context if user is replying to a specific messageconst replyContext = extractReplyContext(ctx);const content = replyContext ? `${replyContext}\n${text}` : text;@@ -804,11 +853,12 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {telegramFirstName: user.telegramFirstName,telegramLastName: user.telegramLastName,});+ await this.bindConversationToContext(user, ctx, created.id);await ctx.reply(`<b>\u2705 New session created</b>\n\n` +`Session: <code>${created.id}</code>\n\n` +- `All next messages in this Telegram chat will use this session.`,+ `All next messages in this Telegram thread will use this session.`,{ parse_mode: "HTML" },);} catch (error) {@@ -842,7 +892,7 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {return;}- const current = user.conversationId ?? user.agentId;+ const current = await this.resolveConversationForContext(user, ctx);const lines = sessions.slice(0, 20).map((id) => {const marker = id === current ? "\u2022 current" : "";return `<code>${id}</code>${marker ? ` ${marker}` : ""}`;@@ -870,7 +920,7 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {}const target = input.trim();- const current = user.conversationId ?? user.agentId;+ const current = await this.resolveConversationForContext(user, ctx);if (!target) {await ctx.reply(`<b>Current session</b>\n\n` +@@ -911,6 +961,7 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {telegramFirstName: user.telegramFirstName,telegramLastName: user.telegramLastName,});+ await this.bindConversationToContext(user, ctx, target);await ctx.reply(`<b>\u2705 Session switched</b>\n\n` +@@ -950,7 +1001,6 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {// ACK: 👀 reactionawait this.addReaction(msg.chat.id, msg.message_id, "👀");- this.storeMessageContext(user.deviceId, msg.chat.id, msg.message_id);// Process media → text description (async, may take a few seconds)const processedText = await this.processMedia({ ...media, caption: caption ?? undefined });@@ -1055,7 +1105,7 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {* Send text to a Telegram user/group by deviceId.* Applies Markdown → HTML formatting, text chunking, and reply-to.*/- async sendToTelegram(deviceId: string, text: string): Promise<void> {+ async sendToTelegram(deviceId: string, text: string, conversationId?: string): Promise<void> {if (!this.bot) return;const user = await this.userStore.findByDeviceId(deviceId);@@ -1065,7 +1115,8 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {}// Use chatId from message context (supports groups); fall back to user ID (private chat)- const context = this.messageContexts.peekForSend(deviceId);+ const contextKey = this.makeConversationContextKey(deviceId, conversationId);+ const context = this.messageContexts.peekForSend(contextKey);const chatId = context?.telegramChatId ?? Number(user.telegramUserId);const chunks = chunkText(text);@@ -1118,13 +1169,15 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {type: string,caption?: string,filename?: string,+ conversationId?: string,): Promise<void> {if (!this.bot) return;const user = await this.userStore.findByDeviceId(deviceId);if (!user) return;- const context = this.messageContexts.peekForSend(deviceId);+ const contextKey = this.makeConversationContextKey(deviceId, conversationId);+ const context = this.messageContexts.peekForSend(contextKey);const chatId = context?.telegramChatId ?? Number(user.telegramUserId);const inputFile = new InputFile(data, filename);@@ -1210,10 +1263,10 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {// ── Typing indicators ──- private startTyping(deviceId: string): void {- if (this.typingTimers.has(deviceId)) return;+ private startTyping(contextKey: string): void {+ if (this.typingTimers.has(contextKey)) return;- const context = this.messageContexts.peekForSend(deviceId);+ const context = this.messageContexts.peekForSend(contextKey);if (!context) return;const chatId = context.telegramChatId;@@ -1222,41 +1275,41 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {};send();const interval = setInterval(send, 5000);- this.typingTimers.set(deviceId, interval);+ this.typingTimers.set(contextKey, interval);// Safety timeout: auto-stop if no message_end/agent_error arrivessetTimeout(() => {- if (this.typingTimers.get(deviceId) === interval) {- this.stopTyping(deviceId);+ if (this.typingTimers.get(contextKey) === interval) {+ this.stopTyping(contextKey);}}, TYPING_TIMEOUT_MS);}- private stopTyping(deviceId: string): void {- const timer = this.typingTimers.get(deviceId);+ private stopTyping(contextKey: string): void {+ const timer = this.typingTimers.get(contextKey);if (timer) {clearInterval(timer);- this.typingTimers.delete(deviceId);+ this.typingTimers.delete(contextKey);}}// ── Message context tracking ──- private storeMessageContext(deviceId: string, chatId: number, messageId: number): void {- this.messageContexts.enqueue(deviceId, {+ private storeMessageContext(contextKey: string, chatId: number, messageId: number): void {+ this.messageContexts.enqueue(contextKey, {telegramChatId: chatId,telegramMessageId: messageId,});}/** Bind the oldest pending context to the currently running agent response. */- private activateMessageContext(deviceId: string): MessageContext | undefined {- return this.messageContexts.activate(deviceId);+ private activateMessageContext(contextKey: string): MessageContext | undefined {+ return this.messageContexts.activate(contextKey);}/** Remove context and 👀 reaction for a device after response is sent */- private async clearMessageContext(deviceId: string): Promise<void> {- const context = this.messageContexts.release(deviceId);+ private async clearMessageContext(contextKey: string): Promise<void> {+ const context = this.messageContexts.release(contextKey);if (context) {await this.removeReaction(context.telegramChatId, context.telegramMessageId);}@@ -1336,6 +1389,15 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {telegramFirstName: msg?.from?.first_name,telegramLastName: msg?.from?.last_name,});+ const threadRoute = this.getThreadRoute(ctx);+ if (threadRoute) {+ await this.userStore.setThreadConversation(+ telegramUserId,+ threadRoute.chatId,+ mainConversationId,+ threadRoute.threadId,+ );+ }const successKeyboard = new InlineKeyboard().text("Check status", CB_CHECK_STATUS)@@ -1551,7 +1613,12 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {}// Send message to Hub- const conversationId = user.conversationId ?? user.agentId;+ const conversationId = await this.resolveConversationForContext(user, ctx);+ const msg = ctx.message;+ if (msg) {+ const contextKey = this.makeConversationContextKey(user.deviceId, conversationId);+ this.storeMessageContext(contextKey, msg.chat.id, msg.message_id);+ }const message: RoutedMessage = {id: uuidv7(),uid: null,@@ -1609,11 +1676,13 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {const streamPayload = msg.payload as StreamPayload;const event = streamPayload?.event;if (!event || !("type" in event)) return;+ const conversationId = streamPayload?.conversationId;+ const contextKey = this.makeConversationContextKey(deviceId, conversationId);// Start typing when LLM begins generatingif (event.type === "message_start") {- this.activateMessageContext(deviceId);- this.startTyping(deviceId);+ this.activateMessageContext(contextKey);+ this.startTyping(contextKey);return;}@@ -1631,9 +1700,9 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {.map((c) => c.text!).join("") ?? "";if (narration) {- void this.sendToTelegram(deviceId, narration).then(() => {+ void this.sendToTelegram(deviceId, narration, conversationId).then(() => {// Re-send typing indicator — Telegram clears it when a message is sent- const ctx = this.messageContexts.peekForSend(deviceId);+ const ctx = this.messageContexts.peekForSend(contextKey);if (ctx) {void this.bot?.api.sendChatAction(ctx.telegramChatId, "typing").catch(() => {});}@@ -1642,15 +1711,15 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {return;}- this.stopTyping(deviceId);+ this.stopTyping(contextKey);if (agentMsg?.content) {const textContent = agentMsg.content.filter((c) => c.type === "text" && c.text).map((c) => c.text!).join("");if (textContent) {- void this.sendToTelegram(deviceId, textContent).then(() => {- void this.clearMessageContext(deviceId);+ void this.sendToTelegram(deviceId, textContent, conversationId).then(() => {+ void this.clearMessageContext(contextKey);});}}@@ -1659,8 +1728,8 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {// Stop typing on errorif (event.type === "agent_error") {- this.stopTyping(deviceId);- void this.clearMessageContext(deviceId);+ this.stopTyping(contextKey);+ void this.clearMessageContext(contextKey);return;}@@ -1674,25 +1743,30 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {type?: string;caption?: string;filename?: string;+ conversationId?: string;};if (payload?.data) {+ const contextKey = this.makeConversationContextKey(deviceId, payload.conversationId);void this.sendFileToTelegram(deviceId,Buffer.from(payload.data, "base64"),payload.type ?? "document",payload.caption,payload.filename,+ payload.conversationId,);+ this.activateMessageContext(contextKey);}return;}// Regular message (e.g., "message" action from Hub)if (msg.action === "message") {- const payload = msg.payload as { content?: string; agentId?: string };+ const payload = msg.payload as { content?: string; agentId?: string; conversationId?: string };if (payload?.content) {- void this.sendToTelegram(deviceId, payload.content).then(() => {- void this.clearMessageContext(deviceId);+ const contextKey = this.makeConversationContextKey(deviceId, payload.conversationId);+ void this.sendToTelegram(deviceId, payload.content, payload.conversationId).then(() => {+ void this.clearMessageContext(contextKey);});}return;@@ -1700,11 +1774,12 @@ export class TelegramService implements OnModuleInit, OnModuleDestroy {// Error messagesif (msg.action === "error") {- this.stopTyping(deviceId);- void this.clearMessageContext(deviceId);- const payload = msg.payload as { message?: string; code?: string };+ const payload = msg.payload as { message?: string; code?: string; conversationId?: string };+ const contextKey = this.makeConversationContextKey(deviceId, payload.conversationId);+ this.stopTyping(contextKey);+ void this.clearMessageContext(contextKey);if (payload?.message) {- void this.sendToTelegram(deviceId, `Error: ${payload.message}`);+ void this.sendToTelegram(deviceId, `Error: ${payload.message}`, payload.conversationId);}}},