Skip to content

feat(messages): filter messages list by --type, --since and --until - #180

Merged
neoromantic merged 30 commits into
neoromantic:mainfrom
ertembiyik:ertembiyik/NO-TASK/list-filters
Nov 22, 2026
Merged

neoromantic merged 30 commits into
neoromantic:mainfrom
ertembiyik:ertembiyik/NO-TASK/list-filters

Conversation

@ertembiyik

@ertembiyik ertembiyik commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What and why

tg messages list can now be narrowed by message type (--type voice,round) and by date (--since, --until), so "every voice note in this chat" and "this chat since Monday" are one command each. A filtered page reads only the cache, and says with complete whether the cache holds all of it and what to run when it doesn't.

Before: to find the voice notes and round videos of a chat, agents left the normal commands and called the raw API once per type, with a hand-built peer and filter (this is the form they used; not run here):

tg api messages.search --json '{"peer":…,"q":"","filter":{"_":"inputMessagesFilterVoice"},"limit":100}'
tg api messages.search --json '{"peer":…,"q":"","filter":{"_":"inputMessagesFilterRoundVideo"},"limit":100}'

To read "the last week" they paged backwards by hand until a date passed, because only messages search had --since and --until.

After (real output from the e2e fixtures, items trimmed to three fields):

$ tg messages list --chat @pierclub --type voice,round --since 2025-10-12T00:00Z --until 2025-10-14T00:00Z
{"items":[{"messageId":7,"messageType":"video","attachment":{"kind":"round"}},
          {"messageId":5,"messageType":"voice","attachment":{"kind":"voice"}}],
 "nextBefore":5,"nextAfter":7,"source":"cache",
 "complete":true,"missingBefore":null,"suggestion":null}

When the cache has a gap, the page says so instead of looking complete. Here messages 61 and 62 arrived live, outside any recorded history range:

$ tg messages list --chat @dockclub --type voice
{"items":[…60, 55, 50, 45…],"source":"cache",
 "complete":false,"missingBefore":63,
 "suggestion":"The cache may lack messages of this page: fetch the missing history with tg messages list --chat -1001555000004 --before 63 --limit 100 (repeat with its nextBefore while this stays incomplete), or turn on history sync with tg chats sync -1001555000004. Then run this command again."}

The flags:

  • --type takes one or more values, comma-separated or repeated: text photo video round animation document sticker voice audio poll contact location venue game invoice webpage dice service unknown. Round video notes are stored as video, so round and animation match on the attachment kind; video still covers both.
  • --since and --until take the forms messages search takes. Their parser moved out of search.ts into src/commands/messages/filters.ts, so both commands share one copy.
  • Paging works as before: nextBefore and nextAfter page through the filtered list, and no matches is an empty page.
  • tg messages search --type came almost free, since the type condition is shared. Search now prints filters.type (null without the flag): one extra key there.

What complete means: one recorded history_ranges run covers the whole ID span the page vouches for, from the window's newest message down to its oldest, or to the last item when the page is full. --type is also incomplete while the messages_raw_json_v2 migration is unfinished, because older rows are typed document until it runs; the suggestion then says tg db migrate. The three keys appear only with a filter: without the new flags, messages list prints exactly what it printed.

Decisions you may want to change:

  • Cache only, no automatic fetch. While the daemon runs, an active chat's newest messages sit outside any range, so a filtered read of that chat is often complete: false until one unfiltered newest page is fetched (the suggestion names the command). The alternative is one automatic getHistory at the page anchor, as the unfiltered list makes: about ten lines, but it gives filtered reads a network and credentials path. I'd add it if you prefer fewer complete: false answers.
  • --fresh with a filter is INVALID_ARGS. Server-side filtering is Search media on the server, beyond the cached history #105's job: Telegram's search filters don't line up one to one with the cache's types, and a server-filtered page records no range.
  • Cached matches beyond a gap are still listed, with complete: false, not cut at the gap.
  • Completeness assumes dates rise with message IDs, so imported history could break the date bounds. Documented.

Rework after the review comment (6a5a00f..ebc6a83)

Where this section and the sections above disagree, this one is current.

The contract for a filtered read

  1. It reads only the cache and never fetches. Resolving --chat and the allowedChats check read the cache too when it knows the chat (an ID or a cached @username), so no credentials are needed.
  2. The page vouches for a span of message IDs: from the chat's newest known message (the highest of the newest cached message, the dialog list's top and the sync state's top; with --before, the message below it) down to message 1 or the one above --after. A full page vouches only down to its last item.
  3. complete: true only when one recorded range covers that span and, with --type, every row in it has its type. An empty complete page is a real zero.
  4. Rows, ranges, the known top and the type state are read in one SQLite read transaction.
  5. missing: ["history" | "types"] says why a page is incomplete. missingBefore is the --before that fills the newest gap, null when the gap reaches the newest message or only types are missing.
  6. next on an incomplete page: the fill commands first (tg messages list … --fresh without filters, and/or tg db migrate), then the same page again, all with --account. On a complete page it is the next page, so next never steps over a gap.
  7. next carries --since and --until resolved to UTC, for list and search.
  8. search --type promises nothing about history; it adds typesPending when the type data is still being prepared.

Your cases, each a failing offline test first: the dialog top above the covered range; the race between rows and coverage; suggestions that lost --account; an offline read by @username, allowedChats included; a relative window shifting on a later next; zeros that meant a pending migration or a row awaiting its raw message; --query '--type=voice' read as a flag; out-of-order dates; a confirmed empty chat and the largest ID; --until with milliseconds. Not changed: filtered list still rejects --fresh, and search has no --fresh at all (citty ignores the unknown flag); the docs say so.

What a user of the earlier revision would notice: the new missing; missingBefore: null for a gap at the top; suggestion is one sentence and the commands are in next; search has typesPending; next shows ISO UTC bounds instead of 7d. On main's behaviour: --since/--until with milliseconds round up, allowedChats resolves a cached @username offline, and flagValues no longer reads the value of another flag as a flag (it now takes the command's argument table).

Checks: bun run check clean (Knip included), bun run test 2068 pass, bun run test:e2e 474 pass, 0 fail. Read-only on a real cache: a filtered list answered with complete: false, missing: ["history","types"] and three next commands.

Update: main merged in (5443e73)

  • main moved to oxfmt and oxlint with the landmines rules, and moved every test beside its code. This branch follows: the same behaviour and output, the code restyled, prose comments and explicit return types removed.
  • Tests moved with main's layout: src/test/messages.e2e.test.ts, src/test/next-commands.e2e.test.ts, and messages-filters.test.ts and messages-list-coverage.test.ts in src/commands/messages/. No case was lost; none duplicates one main kept.
  • After the merge: bun run check clean (format, lint, types, Knip), bun run test 1227 pass, bun run test:e2e 356 pass, 0 fail. Totals are lower than before because main merged and removed many tests.

How I checked it

  • E2E on seeded fixtures (12 tests): all voice notes of a chat, voice and round together, a date window, type and date together, paging both ways with the cursors, no matches, a partly cached chat, no new keys without a filter, and the argument errors.

  • Unit tests for the parsing, nine filtered-read and coverage cases (a gap, the live tail, a date window, a full page, forward paging, an empty cache, a pending migration) and search --type.

  • Without the new flags, six messages list commands on the same fixture give byte-identical output on main and on this branch.

  • Not run against real Telegram: the fill commands in the suggestion are existing paths, and that they merge ranges is covered by existing unit tests.

  • bun run check: clean. bun run test: 2320 pass, 0 fail. bun run test:e2e: 443 pass, 0 fail.

  • Tests pass locally and use made-up data only

  • README, docs and affected demos follow the product content standard (docs/cli-commands.md, docs/caching.md, docs/media.md, README, CHANGELOG)

  • Title follows the repo's commit style: Conventional Commits (feat: …, fix: …) unless AGENTS.md says otherwise

Update: second code review (1b87323)

A second, independent review of this branch. Each point below was first shown by a failing test, then fixed.

  • --no-since, --no-until and a bound no date can hold (--since=1000000000d) are INVALID_ARGS (exit 3); they were a raw TypeError and a TELEGRAM_ERROR. tg messages search reads its bounds through the same code and gets the same fix.
  • A deleted media row whose raw message is missing no longer keeps a result missing: ["types"] with a refetch that cannot recover it: the check uses the page's own deleted and date conditions.
  • A gap from a time the account took no part in a group is no longer offered as a fill: the cache would skip those messages again. complete stays false, next is the next page, and suggestion says why.
  • The one-snapshot test now fails when the item query leaves the transaction (the writer fires right after it returns).
  • Known and left for you: a fill with --before=N --fresh can be suggested again after it ran, when Telegram has no messages between the covered range and N. recordPage in src/db/history-ranges.ts extends a range to before - 1 only when a cached row exists at or above before; that function is on main and the daemon uses it, so this PR does not change it. One way: let it also trust a known top of the chat (chats_cache.last_message_id) at or above before.

After these commits: bun run check clean, bun run test 1230 pass, bun run test:e2e 356 pass, 0 fail.

Update: main merged in (649eef9)

Two conflicts with #220.

  • src/commands/access.ts: fix: act on the checked target, refuse undeclared flags, keep done calls done #220 makes the allowedChats check hand its resolved chat to the command, so the check needs the whole chat. This branch had switched the check to an ID-only lookup from the cache. I took main's version: the file is now identical to main. With allowedChats set, a chat cached without an access hash needs credentials to be checked again, as on main; without allowedChats a filtered page still reads it offline. The changelog entry and the doc sentence about it are removed, and the e2e test no longer runs with allowedChats.
  • CHANGELOG.md: both sides kept.

After the merge: bun run check clean, bun run test 1241 pass, bun run test:e2e 357 pass, 0 fail.

Update: main merged in (853a651)

main up to 0.15.1 and #232 merged in. Conflicts: CHANGELOG.md (the entries of this PR now sit under the new ## [Unreleased]) and the import lines of src/commands/send.ts. No behaviour change. The review of 19 November is not addressed in this merge.

After the merge: bun run check clean, bun run test 1253 pass, bun run test:e2e 383 pass, 0 fail.

Update: review of 19 November (feb15c8 to b1372c4)

Each point has an offline test that failed before its fix.

  • One fetch settles an empty gap; a later arrival leaves it open (feb15c8). recordPage no longer looks for a cached row at or above before when it writes. The caller reads the chat's newest known message before it sends the request (HistoryRanges.knownTop: the highest of the cached messages, the dialog's top, the sync state's top and the recorded ranges) and passes it in. A page of the newest messages below before, or a short forward page, covers up to min(before - 1, knownTop); a page of the chat's newest messages covers up to knownTop. Telegram gives a later message a higher ID than any it had, so none can land in that span, and a message cached during the request no longer vouches for it. tg messages list --fresh and the daemon's backward job pass it; the daemon's initial load, its catch-up and the fetch around one message record what they did before. A page with a message kept out by the group participation rule still records nothing.
  • Empty histories (feb15c8). A chat whose newest page came back empty is stored as the range 1 to 0, so the fill is not suggested again. This is a new value in history_ranges; docs/database-schema.md describes it.
  • The e2e block "Messages List filters, filled from Telegram" runs the suggested fill command and then the repeat command against the fake client for: the dialog knowing message 30, only the sync state knowing it, a server that holds only 30, an empty chat, and a dialog that reported 30 when the chat now ends at 10. After one fill the page is complete and next has no fill.
  • Date filters (fd49188). A date bound narrows the span only where every ID beyond it is cached or inside a range, so the date of a missing row is never guessed. A date window next to a gap is complete: false more often than before; one existing e2e expectation changed with it.
  • search --type (ef206bd). next suggests tg db migrate only while the migration is pending. For a matching message cached without its raw message it suggests tg messages list --chat=<id> --before=<id+1> --limit=100 --fresh, and why names the message.
  • Offline reads with allowedChats (bcf6014). COMMAND_ACCESS has cacheOnly, set for tg messages list with --type, --since or --until and for tg messages search. For those reads the guard resolves --chat and the allowedChats entries from the cache alone. It still pins args.account and hands the chat it checked to the command (checkedChat); writes still resolve an @username through Telegram. A name the cache can't resolve is INVALID_ARGS with details.chat and says to pass the numeric ID or cache the chat first. This replaces what the merge section of 649eef9 says about credentials.
  • search --fresh (b1372c4) is a declared flag that is always refused with INVALID_ARGS, the reason and the tg messages list --chat <chat> --fresh to run first.

Yours to decide:

  • With allowedChats set, tg messages search fails with INVALID_ARGS when an @name entry is not in the cache, where main would resolve it through Telegram. It fails closed: an unresolved entry can't be compared with --chat.
  • tg messages search --help now lists --fresh, described as refused. Without the declaration the shared guard already refuses it as an unknown option, with no reason.

Not verified: real Telegram and a running daemon; all of it is offline tests on made-up data.

bun run check clean, bun run test 1266 pass, bun run test:e2e 393 pass, 0 fail.

Update: main merged in (ac85803)

main up to 0.15.2 (#234) merged in. One conflict: CHANGELOG.md. The entries of this PR stay under ## [Unreleased], and the Windows download fix keeps its own 0.15.2 section. No behaviour change.

Update: review of 21 November (3cd07e8 to f0ce80d)

Each case has a test that failed before its fix for the reason given in the review.

  • A filtered page stays incomplete while a candidate in its date window has no type (3cd07e8). The type check ran only inside the span the date bounds had narrowed, which assumes that dates follow IDs. It now runs over the page's ID bounds, pagination cutoff included, and checks each message's own date. The date bounds narrow the span for the history gap only. Test: IDs 1 to 3 with dates 180, 120 and 100, where ID 1 has media and empty raw data; --type=round --since and the --until mirror both answer complete: false, missing: ["types"].
  • Search reads its rows, the count and the type state in one read transaction (674f6ce, readSearchPage). The test runs the real type migration from a second connection after the first row read. The raced read answers no rows, count 0 and a pending migration; the read after it answers the message, count 1 and no pending migration. Without the transaction the test gives the review's results: [], count: 1, typesPending: false.
  • No endless refetch (f0ce80d), the simple option. Neither command puts the refetch of an untyped message in next. suggestion names the tg messages list --chat=<id> --limit=100 --before=<id+1> --fresh and says to run it once, since a message Telegram no longer returns keeps its type unknown. The type stays unknown and the page incomplete. The e2e test runs the suggested command against a fake server that no longer has the message, then repeats the search and the filtered list: no fill in next before or after. A stopping point derived from stored facts was not possible: history_ranges.updated_at changes whenever ranges merge, so it does not show that a fetch covered one ID. This replaces the search --type point of the section above.

Yours to decide, new: tg messages search gains a suggestion key, null unless a matching message waits for its raw message. Filtered list already has it; without it search has no place for the retry. The alternative is to drop the hint from search and keep only typesPending and the docs.

The two interface decisions of the section above are unchanged and still open.

Not verified: real Telegram and a running daemon; all of it is offline tests on made-up data.

bun run check clean, bun run test 1269 pass, bun run test:e2e 394 pass, 0 fail.

Update: live check against real Telegram (f0ce80d)

Run from this branch with an isolated data directory against the Saved Messages of a real account, about 1,800 messages, with an empty cache at the start. Reads only, except one test message that was deleted afterwards. A running daemon was not part of it.

  • Empty cache. --type photo --limit 5 answers complete: false, missing: ["history"]. After the suggested --fresh fetch of 100 the same page has its 5 items and complete: true.
  • Several rounds. --type voice --limit 5 needed three fetches. Each next carried a lower --before, the page was complete after the third, and the three ranges merged into one. No run was offered the same fetch twice.
  • A message from another client. Sent after the fetch, it is not in the filtered page or in search until a --fresh page of the newest messages is read; then both show it and the range ends at it. Until then the filtered page says complete: true: it vouches for the messages the cache has heard of.
  • Date windows. --since seven weeks back returned its 34 messages at once and stayed complete: false through eight more fetches of older history. Another window became complete only on the fetch that reached the start of the chat, 18 fetches of 100 in all. This is the rule of 19 November on a real chat: with a lower bound, every ID below the window can still hold a match, so the page is complete only once the history below it is cached.

🤖 Generated with Claude Code

tg messages list takes --type (one or more message types; round and
animation match on the attachment kind) and --since/--until, with the
parser tg messages search already had. A filtered page reads only the
cache and says with complete whether a recorded history range covers
everything it vouches for; when it doesn't, missingBefore and suggestion
name the unfiltered page that fills the gap. tg messages search takes
--type too. Without the flags, messages list prints what it printed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
ertembiyik and others added 3 commits November 18, 2026 14:24
list.ts, search.ts: --type, --since and --until moved into the shared argument tables neoromantic#185 added, so next carries them; a repeated --type goes into next as one comma list, with tests. CHANGELOG: both sides' entries kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#179 (neoromantic#188). No conflict.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main is now the 0.14.0 release (neoromantic#189). This PR's changelog entries move
back under Unreleased: a plain merge left them in the released section.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@neoromantic

Copy link
Copy Markdown
Owner

The main question for me is when a caller can trust an empty result. If I ask for voice notes and the CLI says the page is complete, I’ll stop looking. I found a case where it says exactly that even though the daemon already knows there are newer messages it hasn’t read. And if I do follow a suggestion to fill a gap, it can run against a different account.

Could you propose how you’d like this to work when some history is missing? In particular, should the caller follow next to see older cached matches, or fill the gap and repeat the current page first? A local-only filter seems useful in its own right. I’d like to understand what it can promise before adding an automatic fetch.

I reproduced these cases offline on 15e1da2 with made-up chats:

  • A page marked complete can skip a message. Cache ID 1, record coverage for 1, and set the known dialog top to 3. list --after 1 --type voice returns items: [], complete: true. There’s also a race: start with IDs 1 and 3 in separate ranges, then let a second SQLite connection insert matching ID 2 and join the ranges between the two reads. The answer is [3, 1] with complete: true. Could the check use the known dialog top and read the rows and their coverage in one SQLite snapshot? history.ts
  • The suggested commands lose the account. With account 1 active, a filtered read on --account 2 suggested tg messages list --chat -45 --before 8 --limit 100. Copying that reads account 1. The suggested chats sync can also change account 1’s sync settings, and db migrate targets its cache. The regular paging command does preserve an explicit account. history.ts
  • An offline read can ask for Telegram credentials. With a cached username, a full history range and no access hash, listing by numeric ID returned the voice note. Listing the same chat by username required TELEGRAM_API_ID. If the promise is “works offline,” resolving the chat and checking allowedChats are part of it too. list.ts
  • Following next later changes the time window. On an unchanged cache, the next page of list --since 60s --limit 1 returned ID 1 immediately and nothing three seconds later. With search --until 60s --limit 1, the delayed second page repeated ID 2. Putting the resolved UTC bounds in next would preserve the original window. Search already had this behavior. list.ts
  • A zero count can mean the type data is still being prepared. On an older cache, the same search --type voice --count went from 0 to 1 after db migrate, with no new messages. For list --type round, a video row awaiting a refetch of its raw data gave an empty, complete page even after the type migration had finished. How should a caller tell those cases from a genuine zero?
Smaller cases for regression tests
  • Searching for the literal string --type=voice gives different results with --query '--type=voice' and --query=--type=voice. Both return the same data.query, but the first also silently applies the voice filter.
  • With synthetic out-of-order timestamps, IDs 1 and 3 dated 100 and 50 seconds gave [1], complete: true for a lower bound of 80. Filling the gap with ID 2 dated 90 changed the answer to [2, 1]. This exercises the date-order assumption mentioned in the PR.
  • A confirmed empty chat keeps suggesting a history fetch, even for --before 1. At the opposite end, an uncovered ID 2147483647 produces a suggested --before 2147483648, which the CLI rejects.
  • A message at 00:01:40Z is excluded by --until 00:01:40.500Z on the same date. The shared parser rounds the bound down.
  • Filtered list rejects --fresh, while search --type voice --fresh succeeds with cached results. It would help to make the intended behavior explicit.

ertembiyik and others added 8 commits November 18, 2026 20:38
main now has neoromantic#175 (neoromantic#194), neoromantic#174 and neoromantic#155. history.ts and two test files: imports of both sides. CHANGELOG: both sides kept. Fixture groups take part in the tests: main caches a group's new messages only while the account writes there (neoromantic#155).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
main now has neoromantic#195: Knip in bun run check, and long as a runtime dependency. No conflict; the check is clean.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
flagValues skips the value of another string flag, so --query '--type=voice'
searches for that text in both spellings. --since and --until round a bound
with milliseconds up: message dates are whole seconds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n message

The rows, ranges, newest known message and type state are read in one read
transaction. complete is bounded by the dialog top and sync state, a date bound
that cached dates contradict is not trusted, and rows still waiting for their
raw message make --type incomplete. missing says why a page is incomplete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pages offline

A filtered list page that lacks history or types suggests in next the command
that fills it (an unfiltered --fresh page, or tg db migrate) and then the same
page again, all with --account; a complete page suggests the next one. next
carries --since and --until as resolved UTC bounds, for list and search. A
cached @username resolves without credentials, in allowedChats too. search
--type reports typesPending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed repro. Before changing anything I looked at how other partially synced stores answer the same question (a chat timeline with explicit gaps and a fill token per gap, a mail cache compared against the server's high-water mark, a normalized cache that returns complete: false with what is missing, search engines that flag partial results and pin a point in time across pages). The common rule: completeness is measured against a known high-water mark, a gap is data with its own fill step, and a relative time is resolved once.

Proposed contract for filtered reads, now implemented:

  • They stay cache-only. Resolving --chat and allowedChats use the cache too when it knows the chat.
  • complete: true means one recorded range covers the page's span up to the chat's newest known message (the max of the cache, the dialog list and the sync state), and with --type every row in it has its type. Rows, ranges, top and type state are read in one SQLite transaction.
  • An incomplete page says why in missing (history, types). Its next fills first (tg messages list … --fresh, or tg db migrate), then repeats the same page, all with --account. next moves to older matches only from a complete page, so it never steps over a gap. So to your question: fill the gap and repeat first; nextBefore is still there for a caller who wants older cached matches on purpose.
  • next carries --since/--until resolved to UTC, for list and search.

All your cases have offline regression tests and are fixed; the description lists them. search --type gets typesPending for the migration and refetch zeros.

Open for you: should search reject --fresh (today citty ignores it)? Should date narrowing stay (it assumes dates rise with IDs unless the cache shows otherwise)? Is missing a good name?

ertembiyik and others added 5 commits November 19, 2026 12:40
The conflicts in the list, search, history, args and cache code took this branch's changes in main's oxfmt format, without prose comments or explicit return types; the moved history, search, args, time-bounds and e2e tests got their changes at main's new paths, and the two new unit tests moved beside src/commands/messages. Console spies observe without mockImplementation, as main's landmines rules require.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

One known gap I left for you: a fill with --before=N --fresh can be suggested again after it ran, when Telegram has no messages between the covered range and N. recordPage in src/db/history-ranges.ts extends a range to before - 1 only when a cached row exists at or above before. It is on main and the daemon uses it, so I didn't change it here. One option: also trust a known top of the chat (chats_cache.last_message_id) at or above before. Should I do it in this PR or separately?

…st-filters

# Conflicts:
#	CHANGELOG.md
#	src/commands/access.ts
@neoromantic

Copy link
Copy Markdown
Owner

Yes, please finish this in #180, including the fix to recordPage. Keeping the filters local and pinning the dates in next makes sense.

The behavior I’d like is simple. If I follow “fetch the missing history” and Telegram confirms there’s nothing there, I should be able to move on. And if a new message arrives while I’m fetching, the CLI should only tell me the page is complete once it can account for everything in that page. Today I can get stuck asking for the same page, or get a “complete” answer that skips a message.

Here are the two offline cases I’d use to decide whether the fix works. They were reproduced on 1b87323. I checked the merge at 517e399; it kept the same range-writing logic.

  1. One fetch should settle an empty gap. The server has messages 1, 10 and 30. The cache holds 1 and 10 and knows from the dialog that 30 exists. Run tg messages list --chat=42 --account=2 --type=text --before=21, follow its suggested --fresh command, then repeat the original command. The fetch returns 10 and 1. That answers the question about IDs 11–20. Currently the saved range stays at 1–10 and the CLI suggests the same fetch again, even after a second successful try. Expected: coverage reaches 20, the page is complete, and the fill disappears. Please cover the case where only the sync state knows about 30, too.
  2. A later arrival must leave the gap open. Start with 1 and 10. The server selects them for a request below 21. Before the CLI saves the response, messages 15 and 30 arrive on the server, and the daemon caches 30. The CLI currently returns [10, 1] with complete: true. A second server read returns [15, 10, 1]. Expected: the first response leaves the page incomplete. My suggestion is to capture the highest ID already known before sending the request, using the cached messages, dialog and sync state for that account and chat. Using the value at write time is what lets 30 incorrectly vouch for 15. Range writer
Other cases to validate and answers to the open questions
  • Empty histories. Try a server with only ID 30 and a request below 21. Then try a newest-page fetch with no cursor, both for a genuinely empty chat and for a dialog that last reported 30 but now ends at 10. All three currently repeat a successful fetch. Please run the generated fill and repeat commands in the tests. Since the daemon shares the writer, keep coverage conservative on partial pages and when the account skips messages under its group participation rules.
  • Date filters. Keep the date filter for choosing items. For complete, a gap can still contain a match even when the cached dates look ordered. In a synthetic case, IDs 1 and 3 have timestamps 100 and 130. With since=150, the CLI returns an empty, complete page. Filling ID 2 with timestamp 180 changes the answer. I’d keep the page incomplete wherever proving a zero depends on guessing the date of a missing row.
  • Search while media details are missing. With migrations finished and a cached video still missing its raw data, search --type round --count correctly reports typesPending: true. Its suggested db migrate processes zero rows and gets suggested again. Please suggest migration only when one is pending, and explain when the missing step is fetching the message again.
  • Offline reads and allowed chats. In the latest merge, a cached username without an access hash can need credentials again when allowedChats is set. Please restore that offline case while preserving the account and chat identity checked by the access guard. For a name the local cache cannot resolve, explain the miss and let the caller supply a numeric ID. A filtered read should work without a Telegram connection.
  • CLI contract. missing is clear. Please reject search --fresh explicitly so someone asking for current server results can’t mistake a cached answer for one.

ertembiyik and others added 5 commits November 20, 2026 20:20
…st-filters

# Conflicts:
#	CHANGELOG.md
#	src/commands/send.ts
recordPage extended a page to `before - 1` only when a cached row at or
above `before` existed at write time. A fill that Telegram answered with
nothing new then never settled its gap, and a message the daemon cached
while the request ran could vouch for a page that missed a message sent
meanwhile.

The CLI and the daemon now read the chat's newest known message
(knownTop: cached messages, dialog top, sync state top, ranges) before
sending the request. A page of the newest messages below `before`, or a
short forward page, covers up to `before - 1` or that message, whichever
is lower; a page of the chat's newest messages covers up to it, and an
empty one records the chat as empty (range 1-0). Pages with a message
kept out by the participation rule still record nothing.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…d it

A filtered page with --since or --until ended its span at the first
cached message outside the window when the cached dates looked ordered,
so a gap beyond it could hide a match whose date was out of order: IDs 1
and 3 sent at 100 and 130 gave an empty, complete page for since=150
until ID 2 sent at 180 was cached.

The span now ends at such a message only when every message ID beyond it
is cached or inside a recorded range (HistoryRanges.holdsEvery).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…s pending

With the migration done and a matching media message still waiting for
its raw message, search --type suggested tg db migrate, which processes
nothing and is suggested again. It now suggests that only while the
migration is pending; otherwise next fetches the newest such message,
and the messages below it, again with tg messages list --fresh, and says
why.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… the cache

Since main's access guard resolves the chat with resolveHistoryChat, a
filtered tg messages list (and tg messages search) of a chat cached by
@username without an access hash needed credentials again once
allowedChats was set.

COMMAND_ACCESS now marks such reads cacheOnly; the guard then resolves
the chat and the list with resolveCachedChat, still pins args.account
and stores the chat it checked, which list acts on. Writes keep
resolving @username through Telegram. A name the cache can't resolve is
INVALID_ARGS (ChatNotCachedError) that asks for the numeric ID.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Search reads only the cache. --fresh was refused only as an unknown
option, which doesn't tell someone asking for current server results
why; it is now a declared flag that is INVALID_ARGS with that reason and
the tg messages list --fresh to run first.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

All points are done in feb15c8 to b1372c4; the description has them one by one. Each has an offline test that failed before its fix, and the e2e block for the fills runs the generated fill and repeat commands against the fake client.

  • The range writer takes the chat's newest known message, read before the request is sent (cached messages, dialog, sync state, recorded ranges). A page of the newest messages below before covers up to min(before - 1, knownTop), so one fetch settles an empty gap and a message that arrives during the request leaves it open. The daemon's backward job passes it too; its initial load and catch-up record what they did before.
  • An empty chat is stored as the range 1 to 0. That is a new value in history_ranges.
  • A date bound narrows the span only where every ID beyond it is cached or in a range, so windows next to a gap are incomplete more often.
  • search --type suggests db migrate only while it is pending, otherwise the list --fresh that refetches the message.
  • Filtered list and search check --chat and allowedChats from the cache alone; the guard still pins the account and hands over the chat it checked.

Two things are yours to decide. With allowedChats set, search now fails with INVALID_ARGS when an @name entry is not in the cache, where main would ask Telegram: it fails closed, since an unresolved entry can't be compared with --chat. And search --help now lists --fresh, described as refused; without the declaration the shared guard refuses it as an unknown option with no reason.

Not verified against real Telegram or a running daemon. bun run check clean, bun run test 1266 pass, bun run test:e2e 393 pass.

@neoromantic

Copy link
Copy Markdown
Owner

The history fix works in my offline runs. Following the suggested fetch once settled the old gap, including in an empty chat. When a message arrived during the fetch, the page stayed incomplete until the next read picked it up.

I found three remaining cases on b1372c4. One list says “complete” and misses a video note. One search says it found one match and shows none. And when Telegram no longer returns an old message, following the suggested command can keep sending the same request. Please address these in #180.

How to reproduce each case and what the user should see
  1. List can miss a video note and say the page is complete. Cache the entire ID range 1–3. Give the three messages timestamps 180, 120, 100 (Unix seconds). ID 1 is an old video with has_media=1 and raw_json='{}', so the cache cannot tell whether it is a round video. Let the type migration be finished. Run tg messages list --chat=42 --type=round --since=1970-01-01T00:02:30Z. I got items: [], complete: true, missing: []. Restoring only ID 1’s raw video-note data made the same command return ID 1. I reproduced the mirror case with --until too. Until the type is known, the first answer should have complete: false, missing: ["types"]. The range can prove that history was fetched. For missing types, check each candidate’s own date inside the page’s ID bounds, including its pagination cutoff. Date cutoff and type check

  2. Search can contradict its own count. Seed one old message with the searchable text orbit, a video note in its raw data, and no attachment row yet. Run tg messages search --query=orbit --type=round --count on the first page. Using a second SQLite connection, I let the real type migration finish immediately after the search read its rows. That response had results: [], count: 1, typesPending: false. Running it again returned ID 1. Please read the results, optional count and type status in one SQLite read transaction, as filtered list already does. A test can commit the migration between those reads to check that the response is internally consistent on either side of the commit. Rows and type status · Count

  3. An unavailable message can keep producing the same fetch. Cache IDs 1–3 with complete history, all migrations done. ID 2 has text orbit, a video type and empty raw data. The fake server now has IDs 1 and 3. Search for orbit --type=round, then run its suggested tg messages list --chat=42 --limit=100 --before=3 --fresh --account=1. It succeeds and returns ID 1. After two fetches, search still offers exactly that command, and filtered list offers it too. Keeping the type unknown is correct. Please give callers a stopping point when a successful fetch cannot recover it. A simple option, if recording individual attempts is too much for this PR, is to explain the one-time manual retry in the message instead of continually offering it as executable next. The regression test should run the proposed recovery and repeat the original query. Search suggestion · List suggestion

I also reproduced both CLI behaviors you asked about. With allowedChats=42,@unknownharbor, even an explicit --chat=42 gets exit 3; changing the unknown entry to its numeric ID in allowedChats fixes it. And search --help shows why --fresh is refused. Those two interface decisions are still open.

The current main also added a Windows download fix in the same Unreleased changelog section. Please keep both entries when updating the branch.

ertembiyik and others added 4 commits November 21, 2026 22:43
…ndow has no type

The date cutoff of a filtered page assumed dates follow message IDs, so an
untyped media row inside the window could fall outside the narrowed span
and the page said complete. The type check now uses the page's ID bounds
and pagination cutoff and checks each candidate's own date.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Search read its rows, the optional count and the type migration status in
separate reads, so a migration committing between them gave results: [],
count: 1, typesPending: false. readSearchPage reads all three in one read
transaction, as the filtered list does.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…less next

A media message cached without its raw message made search and the
filtered list offer the same tg messages list --fresh as next after every
fetch, even when Telegram no longer returns the message, so following next
never stopped. The cache can't tell that a fetch covered the message after
its row was written, so both commands now name that fetch in suggestion,
to run once, and keep the type unknown.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@ertembiyik

Copy link
Copy Markdown
Contributor Author

All three are fixed in 3cd07e8 to f0ce80d, on top of a merge of main at 0.15.2; the description has them one by one. Each has a test that was red for the reason you gave.

  • List. The type check runs over the page's ID bounds, cutoff included, and tests each message's own date; the date bounds narrow the history gap only. Your case and its --until mirror answer complete: false, missing: ["types"].
  • Search. Rows, count and type state come from one read transaction. The test runs the real migration from a second connection between the reads and checks both sides of the commit.
  • Refetch. I took the simple option. Neither command offers the refetch in next; suggestion names the command and says to run it once. The e2e test runs it against a fake server that no longer has the message and repeats both queries. I looked for a stopping point in stored facts first: history_ranges.updated_at moves whenever ranges merge, so it can't show that a fetch covered one ID.

One new thing for you to decide: search gains a suggestion key, null unless a matching message waits for its raw message. Filtered list already has it, and without it search has no place for the retry. The two interface decisions from last time are unchanged.

The changelog keeps both: this PR's entries under Unreleased and the Windows fix in its 0.15.2 section.

Not verified against real Telegram or a running daemon. bun run check clean, bun run test 1269 pass, bun run test:e2e 394 pass.

@ertembiyik

Copy link
Copy Markdown
Contributor Author

Live check on a real account's Saved Messages (about 1,800 messages, empty cache at the start); the description has the runs. The fills work as in the offline tests: one fetch settles the newest page, a rarer type takes three rounds with a lower --before each, and no fetch is offered twice.

One thing you may want to weigh. With the rule from 19 November, a --since page is complete only once all history below the window is cached. Here a window of seven weeks returned its 34 messages at once and stayed complete: false for eight more fetches; reaching the start of the chat took 18 fetches of 100. On a chat of 100,000 messages that is about a thousand. The items are right from the first answer; only complete waits. If that cost is fine, nothing to change.

@neoromantic

Copy link
Copy Markdown
Owner

I reran the three cases on f0ce80d. Both date bounds now flag a video note whose type is unknown. Search results and the count agree even when the migration finishes during the read. And when Telegram no longer returns a message, I can try the manual fetch once and stop. All three original examples pass.

One case remains in messages list: when an incomplete page already has enough known matches to reach the limit, its next command can skip a video note. Please fix this in #180.

  1. Cache the complete history of a made-up chat 42 with IDs 1, 2 and 3. IDs 1 and 2 are known video notes. ID 3 is a cached video with no raw data yet. All migrations have finished.
  2. Run tg messages list --chat=42 --type=round --limit=1. It returns ID 2 and correctly says complete: false, missing: ["types"]. But it also offers the next page with --before=2. Following it returns ID 1.
  3. Restore ID 3’s raw data as a video note. Repeating the original command now returns ID 3. The suggested next page still returns ID 1. A caller following that cursor has already passed ID 3.

Please keep the one-time manual suggestion and omit the automatic next-page command when a missing type is all that keeps this page incomplete. The caller can still choose to use nextBefore or nextAfter explicitly. The current regression test uses an empty result, so it misses the full-page branch. I also reproduced this going forward with --after=0, ID 1 unresolved and IDs 2 and 3 known: the CLI offers --after=2 and skips ID 1. Next-page branch · Documented behavior

I also reproduced the cost you reported for --since. In a synthetic 310-message chat, the first fetch returned all three matching IDs. The same three IDs appeared after every subsequent fetch, with complete becoming true only on the fourth. That is a separate question about the guarantee and its cost.

@neoromantic
neoromantic merged commit 8f5432e into neoromantic:main Nov 22, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants