Skip to content

Commit 2acc15d

Browse files
committed
feat: list in doctor the chats Telegram gives no answer about
A synced chat missing from the dialog list that Telegram refuses to describe stays on: the refusal looks the same as a stale access hash. On one account these were 14 chats, 8 private ones the account had been removed from and 6 with nothing archived; nothing arrives from any of them. doctor now lists them under UNANSWERED (unansweredChats in --json), and channels unwatch --missing turns them all off, as if the user had.
1 parent e62af70 commit 2acc15d

7 files changed

Lines changed: 204 additions & 3 deletions

File tree

‎cli.js‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,9 @@ function buildProgram() {
318318
.command('unwatch')
319319
.description('Unsubscribe a chat from archiving (disable sync)')
320320
.option('--chat <id|username>', 'Channel identifier')
321+
.option('--missing', 'Every chat doctor lists as missing from your dialogs with no answer from Telegram')
321322
.action(withGlobalOptions((globalFlags, options) =>
322-
runChannelsSync(globalFlags, { ...options, disable: true }),
323+
(options.missing ? runChannelsUnwatchMissing(globalFlags, options) : runChannelsSync(globalFlags, { ...options, disable: true })),
323324
));
324325
// Hidden back-compat alias of watch/unwatch via explicit --enable/--disable.
325326
channels
@@ -1871,6 +1872,7 @@ function repairLabel(repair) {
18711872

18721873
const REPAIR_STATUS_ORDER = ['idle', 'in_progress', 'pending', 'skipped', 'error'];
18731874
const REPAIR_STATUS_LINES = 10;
1875+
const DOCTOR_CHAT_LINES = 10;
18741876

18751877
function summarizeRepairs(repairs) {
18761878
const byStatus = {};
@@ -2765,6 +2767,11 @@ async function runDoctor(globalFlags, options = {}) {
27652767
const queue = messageSyncService.getQueueStats();
27662768
const repairSuggested = messageSyncService.isRepairSuggested();
27672769
const leftChats = messageSyncService.getLeftChatCounts();
2770+
const unansweredChats = messageSyncService.listUnansweredChats().map((chat) => ({
2771+
channelId: chat.channel_id,
2772+
title: chat.peer_title ?? null,
2773+
checkedAt: chat.membership_checked_at ? new Date(chat.membership_checked_at).toISOString() : null,
2774+
}));
27682775
const usernameKeys = messageSyncService.listUsernameKeyedChats();
27692776
const update = getUpdateStatus({
27702777
storeDir,
@@ -2783,6 +2790,7 @@ async function runDoctor(globalFlags, options = {}) {
27832790
queue,
27842791
repairSuggested,
27852792
leftChats,
2793+
unansweredChats,
27862794
usernameKeys,
27872795
update,
27882796
};
@@ -2804,6 +2812,15 @@ async function runDoctor(globalFlags, options = {}) {
28042812
if (leftChats.stillJoined) {
28052813
console.log(`DIALOGS: ${leftChats.stillJoined} synced chat(s) are missing from your dialog list, though Telegram says you are still in them; sync stays on.`);
28062814
}
2815+
if (unansweredChats.length) {
2816+
console.log(`UNANSWERED: ${unansweredChats.length} synced chat(s) are missing from your dialog list, and Telegram gives no answer about them (most often a private chat you were removed from), so nothing arrives from them. Turn their sync off with \`tgcli channels unwatch --missing\`.`);
2817+
for (const chat of unansweredChats.slice(0, DOCTOR_CHAT_LINES)) {
2818+
console.log(` ${chat.channelId}${chat.title ? ` ${chat.title}` : ''}`);
2819+
}
2820+
if (unansweredChats.length > DOCTOR_CHAT_LINES) {
2821+
console.log(` … and ${unansweredChats.length - DOCTOR_CHAT_LINES} more; \`tgcli --json doctor\` lists them all.`);
2822+
}
2823+
}
28072824
if (repairSuggested) {
28082825
console.log(`REPAIR: versions before 2.2.5 could lose messages; fill the holes with \`tgcli backfill repair --all\` (the last ${DEFAULT_REPAIR_SINCE} of every synced chat).`);
28092826
}
@@ -2846,6 +2863,20 @@ async function runChannelsShow(globalFlags, options = {}) {
28462863
}
28472864
}
28482865

2866+
async function runChannelsUnwatchMissing(globalFlags, options = {}) {
2867+
if (options.chat) {
2868+
throw new Error('Use either --chat or --missing');
2869+
}
2870+
const { channelIds } = await runOperation(globalFlags, { op: 'channelsUnwatchMissing', args: {} });
2871+
if (globalFlags.json) {
2872+
writeJson({ ok: true, channelIds });
2873+
} else if (channelIds.length) {
2874+
console.log(`Sync disabled for ${channelIds.length} chat(s): ${channelIds.join(', ')}.`);
2875+
} else {
2876+
console.log('No chat is missing from your dialogs without an answer from Telegram.');
2877+
}
2878+
}
2879+
28492880
async function runChannelsSync(globalFlags, options = {}) {
28502881
if (!options.chat) {
28512882
throw new Error('--chat is required');

‎core/operations.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,11 @@ async function channelShow(ctx, args = {}) {
293293
// args: { chat, enable }. Toggle the per-chat archive flag; enabling also makes sure
294294
// a job fetches what arrived while the chat was off. Returns the new sync state plus
295295
// job info.
296+
// The chats doctor lists as missing from the dialog list with no answer from Telegram.
297+
async function channelsUnwatchMissing(ctx) {
298+
return { channelIds: ctx.messageSyncService.unwatchUnansweredChats() };
299+
}
300+
296301
async function channelSetSync(ctx, args = {}) {
297302
const chatId = await ctx.messageSyncService.resolveChatKey(args.chat);
298303
const result = ctx.messageSyncService.setChannelSync(chatId, Boolean(args.enable));
@@ -951,6 +956,7 @@ export const OPERATIONS = {
951956
listChannels,
952957
channelShow,
953958
channelSetSync,
959+
channelsUnwatchMissing,
954960
messagesList,
955961
messagesSearch,
956962
messagesGet,

‎docs/cli.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,11 @@ it. `server restart` switches to the caller's version in any direction. See
197197
- `LEFT:` counts chats whose sync the server turned off because you left them (see
198198
`channels unwatch`), and `DIALOGS:` the synced chats missing from your dialog list
199199
that Telegram says you are still in. With `--json`: `leftChats`.
200+
- `UNANSWERED:` lists synced chats missing from your dialog list that Telegram gives
201+
no answer about, most often a private chat you were removed from (Telegram refuses
202+
it the same way it refuses a stale access hash, so the server does not act on it).
203+
Nothing arrives from them; `channels unwatch --missing` turns them all off. With
204+
`--json`: `unansweredChats`.
200205

201206
## Update notice
202207
Once a day tgcli asks the npm registry for the latest `@kfastov/tgcli` and keeps the
@@ -237,8 +242,9 @@ Update available: tgcli 2.2.5 -> 2.3.0. Run `brew update && brew upgrade tgcli`
237242
- channels show --chat <id|username>
238243
- channels watch --chat <id|username>
239244
- Subscribe a chat for archiving: enables sync and queues a backfill job; run `tgcli backfill --once` or `tgcli backfill --follow` to process it.
240-
- channels unwatch --chat <id|username>
241-
- Unsubscribe a chat from archiving (disables sync).
245+
- channels unwatch --chat <id|username> | --missing
246+
- Unsubscribe a chat from archiving (disables sync). `--missing` does it for every
247+
chat `doctor` lists under `UNANSWERED:`.
242248
- The server does this by itself for a channel or group you left: Telegram sends
243249
nothing from it, so the archive could not keep up. A synced chat missing from the
244250
dialog list is only a reason to ask Telegram, once a day; sync goes off when Telegram

‎message-sync-service.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3297,6 +3297,27 @@ export default class MessageSyncService {
32973297
return channelIds;
32983298
}
32993299

3300+
// Synced chats missing from the dialog list that Telegram gave no answer about: most
3301+
// often a private chat the account was removed from, which Telegram refuses the same way
3302+
// it refuses a stale access hash, so the server leaves them for the user to turn off.
3303+
listUnansweredChats() {
3304+
return this.db.prepare(`
3305+
SELECT channel_id, peer_title, membership_checked_at FROM channels
3306+
WHERE sync_enabled = 1 AND in_dialogs = 0 AND membership = 'unknown'
3307+
ORDER BY channel_id
3308+
`).all();
3309+
}
3310+
3311+
unwatchUnansweredChats() {
3312+
return this.db.prepare(`
3313+
UPDATE channels
3314+
SET sync_enabled = 0, sync_by_user = 0, sync_off_reason = NULL, membership = NULL,
3315+
membership_checked_at = NULL, updated_at = CURRENT_TIMESTAMP
3316+
WHERE sync_enabled = 1 AND in_dialogs = 0 AND membership = 'unknown'
3317+
RETURNING channel_id
3318+
`).all().map((row) => row.channel_id).sort();
3319+
}
3320+
33003321
// What the server did about synced chats missing from the dialog list.
33013322
getLeftChatCounts() {
33023323
return this.db.prepare(`

‎tests/backfill-rename.test.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,17 @@ describe('channels watch / unwatch', () => {
203203
});
204204
});
205205

206+
it('`channels unwatch --missing` routes channelsUnwatchMissing to the server', async () => {
207+
control.invoke.mockResolvedValueOnce({ channelIds: ['-1000000000820'] });
208+
await runProgram(['channels', 'unwatch', '--missing']);
209+
expect(control.invoke).toHaveBeenCalledWith('/tmp/tgcli-test-store', {
210+
op: 'channelsUnwatchMissing',
211+
args: {},
212+
timeoutMs: undefined,
213+
quiet: false,
214+
});
215+
});
216+
206217
it('`channels watch` matches legacy `channels sync --enable` (same op + args)', async () => {
207218
await runProgram(['channels', 'watch', '--chat', '@chan']);
208219
const watchCalls = control.invoke.mock.calls.slice();

‎tests/doctor-unanswered.test.js‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
// `tgcli doctor` lists synced chats missing from the dialog list that Telegram gave no
2+
// answer about. The archive is real, in a temporary store; Telegram is stubbed out.
3+
4+
import fs from 'fs';
5+
import os from 'os';
6+
import path from 'path';
7+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8+
9+
import MessageSyncService from '../message-sync-service.js';
10+
11+
vi.mock('../core/services.js', () => ({
12+
createTelegramClient: vi.fn(() => ({
13+
telegramClient: {
14+
isAuthorized: vi.fn().mockResolvedValue(true),
15+
destroy: vi.fn().mockResolvedValue(undefined),
16+
},
17+
})),
18+
createMessageSyncService: vi.fn((telegramClient, { storeDir }) => ({
19+
messageSyncService: new MessageSyncService(telegramClient, { dbPath: path.join(storeDir, 'messages.db') }),
20+
})),
21+
resolveValidatedConfig: vi.fn(),
22+
}));
23+
24+
vi.mock('../core/update-check.js', async (importOriginal) => ({
25+
...(await importOriginal()),
26+
getUpdateStatus: () => ({ disabledReason: 'CI' }),
27+
}));
28+
29+
const { buildProgram } = await import('../cli.js');
30+
31+
let storeDir;
32+
let stdout;
33+
34+
beforeEach(() => {
35+
storeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tgcli-doctor-unanswered-'));
36+
vi.stubEnv('TGCLI_STORE', storeDir);
37+
stdout = [];
38+
vi.spyOn(console, 'log').mockImplementation((...args) => { stdout.push(args.join(' ')); });
39+
vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { stdout.push(String(chunk)); return true; });
40+
vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
41+
});
42+
43+
afterEach(() => {
44+
vi.restoreAllMocks();
45+
vi.unstubAllEnvs();
46+
process.exitCode = undefined;
47+
fs.rmSync(storeDir, { recursive: true, force: true });
48+
});
49+
50+
function seed(statements) {
51+
const service = new MessageSyncService(null, { dbPath: path.join(storeDir, 'messages.db') });
52+
for (const [sql, ...params] of statements) {
53+
service.db.prepare(sql).run(...params);
54+
}
55+
service.close();
56+
}
57+
58+
async function doctor(...flags) {
59+
stdout.length = 0;
60+
const program = buildProgram();
61+
program.exitOverride();
62+
await program.parseAsync(['node', 'cli.js', ...flags, 'doctor']);
63+
expect(process.exitCode).toBeUndefined();
64+
return stdout.join('\n');
65+
}
66+
67+
const chat = (id, { membership = 'unknown', inDialogs = 0, sync = 1, title = null } = {}) => [
68+
'INSERT INTO channels (channel_id, peer_title, sync_enabled, in_dialogs, membership, membership_checked_at) VALUES (?, ?, ?, ?, ?, ?)',
69+
id, title, sync, inDialogs, membership, Date.parse('2026-11-06T12:00:00Z'),
70+
];
71+
72+
describe('doctor unanswered chats', () => {
73+
it('says nothing when Telegram answered about every missing chat', async () => {
74+
seed([chat('-1000000000801', { membership: 'member' }), chat('-1000000000802', { membership: 'left', sync: 0 })]);
75+
76+
expect(await doctor()).not.toContain('UNANSWERED');
77+
expect(JSON.parse(await doctor('--json')).unansweredChats).toEqual([]);
78+
});
79+
80+
it('lists them, ten at most, with the command that turns them off', async () => {
81+
seed([
82+
...Array.from({ length: 12 }, (_, index) => chat(String(-1000000000810 - index), { title: index === 0 ? 'Closed group' : null })),
83+
chat('-1000000000899', { inDialogs: 1, membership: null }),
84+
chat('-1000000000898', { sync: 0 }),
85+
]);
86+
87+
const lines = (await doctor()).split('\n');
88+
89+
expect(lines.find((line) => line.startsWith('UNANSWERED:'))).toContain('UNANSWERED: 12 synced chat(s) are missing from your dialog list');
90+
expect(lines.find((line) => line.startsWith('UNANSWERED:'))).toContain('`tgcli channels unwatch --missing`');
91+
expect(lines.filter((line) => /^ -100/.test(line))).toHaveLength(10);
92+
expect(lines).toContain(' -1000000000810 Closed group');
93+
expect(lines).toContain(' … and 2 more; `tgcli --json doctor` lists them all.');
94+
95+
const { unansweredChats } = JSON.parse(await doctor('--json'));
96+
expect(unansweredChats).toHaveLength(12);
97+
expect(unansweredChats[0]).toEqual({ channelId: '-1000000000810', title: 'Closed group', checkedAt: '2026-11-06T12:00:00.000Z' });
98+
});
99+
});
100+
101+
describe('turning off the unanswered chats', () => {
102+
it('turns off only those, as if the user had, and leaves them off when they come back', async () => {
103+
const service = new MessageSyncService(null, { dbPath: path.join(storeDir, 'messages.db') });
104+
for (const [sql, ...params] of [
105+
chat('-1000000000820'),
106+
chat('-1000000000821'),
107+
chat('-1000000000822', { membership: 'member' }),
108+
chat('-1000000000823', { inDialogs: 1, membership: null }),
109+
]) {
110+
service.db.prepare(sql).run(...params);
111+
}
112+
113+
expect(service.unwatchUnansweredChats()).toEqual(['-1000000000820', '-1000000000821']);
114+
const rows = Object.fromEntries(service.db.prepare('SELECT channel_id, sync_enabled, sync_off_reason FROM channels').all()
115+
.map((row) => [row.channel_id, [row.sync_enabled, row.sync_off_reason]]));
116+
expect(rows).toEqual({
117+
'-1000000000820': [0, null],
118+
'-1000000000821': [0, null],
119+
'-1000000000822': [1, null],
120+
'-1000000000823': [1, null],
121+
});
122+
expect(service.listUnansweredChats()).toEqual([]);
123+
service.close();
124+
});
125+
});

‎tests/doctor-update.test.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ vi.mock('../core/services.js', () => ({
2424
getQueueStats: () => ({ pending: 0, in_progress: 0, idle: 0, error: 0, gaps: 0 }),
2525
isRepairSuggested: () => false,
2626
getLeftChatCounts: () => ({ syncOff: 0, stillJoined: 0 }),
27+
listUnansweredChats: () => [],
2728
listUsernameKeyedChats: () => [],
2829
close: vi.fn().mockResolvedValue(undefined),
2930
},

0 commit comments

Comments
 (0)