Add debug package and related types for improved logging

- Added the `debug` package to enhance logging capabilities across the application.
- Included `@types/debug` for TypeScript support, ensuring type safety in logging implementations.
- Updated package-lock and yarn.lock files to reflect these changes.

This update aims to facilitate better debugging and monitoring of the Telegram MCP system.
This commit is contained in:
Steven Enamakel
2026-01-31 00:54:58 +05:30
parent 95e06bc54a
commit 32488245be
6 changed files with 49 additions and 6303 deletions
+9 -9
View File
@@ -43,24 +43,24 @@ Cross-platform crypto community communication platform built with **Tauri v2** (
```bash
# Frontend dev server only (port 1420)
npm run dev
yarn dev
# Desktop dev with hot-reload (starts Vite + Tauri)
npm run tauri dev
yarn tauri dev
# Production build (TypeScript compile + Vite build + Tauri bundle)
npm run tauri build
yarn tauri build
# Debug build with .app bundle (required for deep link testing on macOS)
npm run tauri build -- --debug --bundles app
yarn tauri build --debug --bundles app
# Android
npm run tauri android dev
npm run tauri android build
yarn tauri android dev
yarn tauri android build
# iOS
npm run tauri ios dev
npm run tauri ios build
yarn tauri ios dev
yarn tauri ios build
# Rust checks
cargo check --manifest-path src-tauri/Cargo.toml
@@ -202,7 +202,7 @@ Key updates from recent commits:
- **Modal System**: Settings modal uses `createPortal` pattern with URL-based routing. Clean white design (not glass morphism) for system settings. Navigate with `/settings` and `/settings/connections` paths.
- **Component Reuse**: Connection management reuses `connectOptions` array and components from onboarding flow. Maintains consistent UX patterns across features.
- **Redux Integration**: Settings modal integrates with existing slices - auth for logout, user for profile display, telegram for connection status. No new state management needed.
- **Node polyfills**: Vite config (`vite.config.ts`) polyfills `buffer`, `process`, `util`, `os`, `crypto`, `stream` for the `telegram` npm package which requires Node APIs.
- **Node polyfills**: Vite config (`vite.config.ts`) polyfills `buffer`, `process`, `util`, `os`, `crypto`, `stream` for the `telegram` package which requires Node APIs.
- **Telegram IDs**: Use `big-integer` library, not native JS numbers (Telegram IDs exceed `Number.MAX_SAFE_INTEGER`).
- **MCP tool files**: Each tool in `src/lib/mcp/telegram/tools/` exports a handler conforming to `TelegramMCPToolHandler` interface. Tool names are typed in `src/lib/mcp/telegram/types.ts`.
- **Tauri IPC**: Frontend calls Rust via `invoke()` from `@tauri-apps/api/core`. Rust commands are registered in `generate_handler![]` macro.
-6237
View File
File diff suppressed because it is too large Load Diff
+6 -3
View File
@@ -4,15 +4,18 @@
*/
import type { Socket } from "socket.io-client";
import createDebug from "debug";
import { TelegramMCPServer } from "./server";
const log = createDebug("app:telegram:mcp");
let telegramMCPInstance: TelegramMCPServer | undefined;
export function initTelegramMCPServer(
socket: Socket | null | undefined,
): TelegramMCPServer {
telegramMCPInstance = new TelegramMCPServer(socket);
console.log("[MCP] Telegram MCP server initialized");
log("Telegram MCP server initialized");
return telegramMCPInstance;
}
@@ -25,14 +28,14 @@ export function updateTelegramMCPServerSocket(
): void {
if (telegramMCPInstance) {
telegramMCPInstance.updateSocket(socket);
console.log("[MCP] Telegram MCP server socket updated");
log("Telegram MCP server socket updated");
}
}
export function cleanupTelegramMCPServer(): void {
if (telegramMCPInstance) {
telegramMCPInstance = undefined;
console.log("[MCP] Telegram MCP server cleaned up");
log("Telegram MCP server cleaned up");
}
}
+4 -1
View File
@@ -17,7 +17,10 @@ import { selectTelegramUserState } from "../../store/telegramSelectors";
import { ErrorCategory, logAndFormatError } from "../mcp/errorHandler";
import { ValidationError } from "../mcp/validation";
import { SocketIOMCPTransportImpl } from "../mcp/transport";
import createDebug from "debug";
import { mcpLog } from "../mcp/logger";
const log = createDebug("app:telegram:mcp");
import {
enforceRateLimit,
resetRequestCallCount,
@@ -68,7 +71,7 @@ export class TelegramMCPServer {
tools: toolsList,
});
} catch (error) {
console.error("[MCP] Failed to list tools", error);
log("Failed to list tools %O", error);
this.transport.emit("listToolsResponse", { requestId, tools: [] });
}
});
+25 -49
View File
@@ -10,7 +10,10 @@
import { Api } from "telegram/tl";
import { Raw } from "telegram/events";
import bigInt from "big-integer";
import createDebug from "debug";
import { mtprotoService } from "../../../services/mtprotoService";
const log = createDebug("app:telegram:sync");
import { updateManager } from "../../../services/updateManager";
import { store } from "../../../store";
import {
@@ -46,7 +49,6 @@ const MESSAGE_LIST_SLICE_MOBILE = 40;
const SYNC_SAFETY_TIMEOUT = 15_000; // 15s safety timeout
const INFINITE_LOOP_MARKER = 100; // max iterations for chat loading
const LOG_PREFIX = "[TelegramSync]";
function getMessageSlice(): number {
return typeof window !== "undefined" && window.innerWidth < 768
@@ -76,15 +78,15 @@ class TelegramSyncService {
*/
async startSync(userId: string): Promise<void> {
if (this.isSyncing) {
console.log(LOG_PREFIX, "Sync already in progress, skipping");
log( "Sync already in progress, skipping");
return;
}
if (this.isSynced && this.userId === userId) {
console.log(LOG_PREFIX, "Already synced for this user, skipping");
log( "Already synced for this user, skipping");
return;
}
console.log(LOG_PREFIX, "Starting sync for user", userId);
log( "Starting sync for user", userId);
this.userId = userId;
this.isSyncing = true;
this.isSynced = false;
@@ -94,10 +96,7 @@ class TelegramSyncService {
// Safety timeout: release isSyncing if stuck
this.safetyTimeout = setTimeout(() => {
if (this.isSyncing) {
console.warn(
LOG_PREFIX,
"Safety timeout reached — releasing sync lock"
);
log("Safety timeout reached — releasing sync lock");
this.isSyncing = false;
store.dispatch(setSyncStatus({ userId, isSyncing: false }));
}
@@ -120,18 +119,18 @@ class TelegramSyncService {
store.dispatch(
setSyncStatus({ userId, isSyncing: false, isSynced: true })
);
console.log(LOG_PREFIX, "Initial sync complete — UI ready");
log( "Initial sync complete — UI ready");
// Background tasks (non-blocking)
this.loadAllChats("archived").catch((e) =>
console.warn(LOG_PREFIX, "Archived chat load failed:", e)
log( "Archived chat load failed:", e)
);
this.preloadTopChatMessages().catch((e) =>
console.warn(LOG_PREFIX, "Top chat preload failed:", e)
log( "Top chat preload failed:", e)
);
});
} catch (error) {
console.error(LOG_PREFIX, "Sync failed:", error);
log( "Sync failed:", error);
this.isSyncing = false;
clearTimeout(this.safetyTimeout);
store.dispatch(setSyncStatus({ userId, isSyncing: false }));
@@ -142,7 +141,7 @@ class TelegramSyncService {
* Stop sync and clean up resources.
*/
stopSync(): void {
console.log(LOG_PREFIX, "Stopping sync");
log( "Stopping sync");
clearTimeout(this.safetyTimeout);
// Remove update handler from client
@@ -183,7 +182,7 @@ class TelegramSyncService {
qts: state.qts,
};
console.log(LOG_PREFIX, "Update state:", commonBoxState);
log( "Update state:", commonBoxState);
// Store in Redux
store.dispatch(setCommonBoxState({ userId, commonBoxState }));
@@ -200,10 +199,7 @@ class TelegramSyncService {
};
client.addEventHandler(this.boundProcessUpdate);
console.log(
LOG_PREFIX,
"Update manager initialized, event handler registered"
);
log("Update manager initialized, event handler registered");
}
// -------------------------------------------------------------------------
@@ -230,7 +226,7 @@ class TelegramSyncService {
let offsetPeer: any = new Api.InputPeerEmpty();
let iterations = 0;
console.log(LOG_PREFIX, `Loading ${listType} chats...`);
log( `Loading ${listType} chats...`);
// Also fetch pinned dialogs on first active batch
if (!isArchived) {
@@ -242,7 +238,7 @@ class TelegramSyncService {
this.processDialogsResult(pinned, userId, true);
}
} catch (e) {
console.warn(LOG_PREFIX, "Failed to fetch pinned dialogs:", e);
log( "Failed to fetch pinned dialogs:", e);
}
}
@@ -264,10 +260,7 @@ class TelegramSyncService {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dialogs: any[] = (result as any).dialogs ?? [];
if (dialogs.length === 0) {
console.log(
LOG_PREFIX,
`${listType} chats fully loaded (${iterations} batches)`
);
log(`${listType} chats fully loaded (${iterations} batches)`);
break;
}
@@ -289,10 +282,7 @@ class TelegramSyncService {
break;
}
if (dialogs.length < CHAT_LIST_LOAD_SLICE) {
console.log(
LOG_PREFIX,
`${listType} chats fully loaded (last batch < slice)`
);
log(`${listType} chats fully loaded (last batch < slice)`);
break;
}
@@ -336,7 +326,7 @@ class TelegramSyncService {
}
if (iterations >= INFINITE_LOOP_MARKER) {
console.warn(LOG_PREFIX, `${listType} chat loading hit loop guard`);
log( `${listType} chat loading hit loop guard`);
}
}
@@ -438,17 +428,14 @@ class TelegramSyncService {
const selectedChatId = userState?.selectedChatId;
if (!selectedChatId) {
console.log(LOG_PREFIX, "No chat selected, skipping message load");
log( "No chat selected, skipping message load");
return;
}
const slice = getMessageSlice();
try {
console.log(
LOG_PREFIX,
`Loading ${slice} messages for chat ${selectedChatId}`
);
log(`Loading ${slice} messages for chat ${selectedChatId}`);
const result = await mtprotoService.invoke(
new Api.messages.GetHistory({
@@ -471,16 +458,9 @@ class TelegramSyncService {
);
}
console.log(
LOG_PREFIX,
`Loaded ${messages.length} messages for chat ${selectedChatId}`
);
log(`Loaded ${messages.length} messages for chat ${selectedChatId}`);
} catch (error) {
console.warn(
LOG_PREFIX,
`Failed to load messages for chat ${selectedChatId}:`,
error
);
log(`Failed to load messages for chat ${selectedChatId}: %O`, error);
}
}
@@ -538,16 +518,12 @@ class TelegramSyncService {
preloaded++;
} catch (error) {
console.warn(
LOG_PREFIX,
`Failed to preload messages for chat ${chatId}:`,
error
);
log(`Failed to preload messages for chat ${chatId}: %O`, error);
// Continue with next chat
}
}
console.log(LOG_PREFIX, `Preloaded messages for ${preloaded} chats`);
log( `Preloaded messages for ${preloaded} chats`);
}
}
+5 -4
View File
@@ -8,7 +8,10 @@
*/
import { Api } from "telegram/tl";
import createDebug from "debug";
import { store } from "../../../store";
const log = createDebug("app:telegram:sync");
import {
addMessage,
updateMessage,
@@ -17,7 +20,6 @@ import {
} from "../../../store/telegram";
import { buildMessage, buildPeerId } from "./entityBuilders";
const LOG_PREFIX = "[TelegramSync]";
/**
* Handle a single update from the UpdateManager.
@@ -35,9 +37,8 @@ export function handleUpdate(
// Force sync signal from UpdateManager
// -------------------------------------------------------------------------
if (update && update._ === "forceSync") {
console.log(
LOG_PREFIX,
"Force sync requested",
log(
"Force sync requested %s",
update.channelId ? `for channel ${update.channelId}` : "(full)"
);
return;