Repository navigation
feat(messages): filter messages list by --type, --since and --until - #180
Conversation
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]>
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]>
|
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 I reproduced these cases offline on
Smaller cases for regression tests
|
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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 Proposed contract for filtered reads, now implemented:
All your cases have offline regression tests and are fixed; the description lists them. Open for you: should |
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]>
…LID_ARGS Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…'t take part Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
One known gap I left for you: a fill with |
…st-filters # Conflicts: # CHANGELOG.md # src/commands/access.ts
|
Yes, please finish this in #180, including the fix to 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
Other cases to validate and answers to the open questions
|
…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]>
|
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.
Two things are yours to decide. With Not verified against real Telegram or a running daemon. |
|
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 How to reproduce each case and what the user should see
I also reproduced both CLI behaviors you asked about. With The current |
…st-filters # Conflicts: # CHANGELOG.md
…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]>
|
All three are fixed in 3cd07e8 to f0ce80d, on top of a merge of
One new thing for you to decide: search gains a 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. |
|
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 One thing you may want to weigh. With the rule from 19 November, a |
|
I reran the three cases on One case remains in
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 I also reproduced the cost you reported for |
What and why
tg messages listcan 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 withcompletewhether 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):
To read "the last week" they paged backwards by hand until a date passed, because only
messages searchhad--sinceand--until.After (real output from the e2e fixtures, items trimmed to three fields):
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:
The flags:
--typetakes 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 asvideo, soroundandanimationmatch on the attachment kind;videostill covers both.--sinceand--untiltake the formsmessages searchtakes. Their parser moved out ofsearch.tsintosrc/commands/messages/filters.ts, so both commands share one copy.nextBeforeandnextAfterpage through the filtered list, and no matches is an empty page.tg messages search --typecame almost free, since the type condition is shared. Search now printsfilters.type(nullwithout the flag): one extra key there.What
completemeans: one recordedhistory_rangesrun 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.--typeis also incomplete while themessages_raw_json_v2migration is unfinished, because older rows are typeddocumentuntil it runs; the suggestion then saystg db migrate. The three keys appear only with a filter: without the new flags,messages listprints exactly what it printed.Decisions you may want to change:
complete: falseuntil one unfiltered newest page is fetched (the suggestion names the command). The alternative is one automaticgetHistoryat 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 fewercomplete: falseanswers.--freshwith a filter isINVALID_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.complete: false, not cut at the gap.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
--chatand theallowedChatscheck read the cache too when it knows the chat (an ID or a cached@username), so no credentials are needed.--before, the message below it) down to message 1 or the one above--after. A full page vouches only down to its last item.complete: trueonly 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.missing: ["history" | "types"]says why a page is incomplete.missingBeforeis the--beforethat fills the newest gap,nullwhen the gap reaches the newest message or only types are missing.nexton an incomplete page: the fill commands first (tg messages list … --freshwithout filters, and/ortg db migrate), then the same page again, all with--account. On a complete page it is the next page, sonextnever steps over a gap.nextcarries--sinceand--untilresolved to UTC, forlistandsearch.search --typepromises nothing about history; it addstypesPendingwhen 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,allowedChatsincluded; a relative window shifting on a laternext; 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;--untilwith milliseconds. Not changed: filteredliststill rejects--fresh, andsearchhas no--freshat all (citty ignores the unknown flag); the docs say so.What a user of the earlier revision would notice: the new
missing;missingBefore: nullfor a gap at the top;suggestionis one sentence and the commands are innext;searchhastypesPending;nextshows ISO UTC bounds instead of7d. Onmain's behaviour:--since/--untilwith milliseconds round up,allowedChatsresolves a cached@usernameoffline, andflagValuesno longer reads the value of another flag as a flag (it now takes the command's argument table).Checks:
bun run checkclean (Knip included),bun run test2068 pass,bun run test:e2e474 pass, 0 fail. Read-only on a real cache: a filtered list answered withcomplete: false,missing: ["history","types"]and threenextcommands.Update:
mainmerged in (5443e73)mainmoved 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.main's layout:src/test/messages.e2e.test.ts,src/test/next-commands.e2e.test.ts, andmessages-filters.test.tsandmessages-list-coverage.test.tsinsrc/commands/messages/. No case was lost; none duplicates onemainkept.bun run checkclean (format, lint, types, Knip),bun run test1227 pass,bun run test:e2e356 pass, 0 fail. Totals are lower than before becausemainmerged 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 listcommands on the same fixture give byte-identical output onmainand 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: …) unlessAGENTS.mdsays otherwiseUpdate: 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-untiland a bound no date can hold (--since=1000000000d) areINVALID_ARGS(exit 3); they were a rawTypeErrorand aTELEGRAM_ERROR.tg messages searchreads its bounds through the same code and gets the same fix.missing: ["types"]with a refetch that cannot recover it: the check uses the page's own deleted and date conditions.completestaysfalse,nextis the next page, andsuggestionsays why.--before=N --freshcan be suggested again after it ran, when Telegram has no messages between the covered range andN.recordPageinsrc/db/history-ranges.tsextends a range tobefore - 1only when a cached row exists at or abovebefore; that function is onmainand 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 abovebefore.After these commits:
bun run checkclean,bun run test1230 pass,bun run test:e2e356 pass, 0 fail.Update:
mainmerged 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 theallowedChatscheck 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 tookmain's version: the file is now identical tomain. WithallowedChatsset, a chat cached without an access hash needs credentials to be checked again, as onmain; withoutallowedChatsa filtered page still reads it offline. The changelog entry and the doc sentence about it are removed, and the e2e test no longer runs withallowedChats.CHANGELOG.md: both sides kept.After the merge:
bun run checkclean,bun run test1241 pass,bun run test:e2e357 pass, 0 fail.Update:
mainmerged in (853a651)mainup 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 ofsrc/commands/send.ts. No behaviour change. The review of 19 November is not addressed in this merge.After the merge:
bun run checkclean,bun run test1253 pass,bun run test:e2e383 pass, 0 fail.Update: review of 19 November (feb15c8 to b1372c4)
Each point has an offline test that failed before its fix.
recordPageno longer looks for a cached row at or abovebeforewhen 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 belowbefore, or a short forward page, covers up tomin(before - 1, knownTop); a page of the chat's newest messages covers up toknownTop. 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 --freshand 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.history_ranges;docs/database-schema.mddescribes it.nexthas no fill.complete: falsemore often than before; one existing e2e expectation changed with it.search --type(ef206bd).nextsuggeststg db migrateonly while the migration is pending. For a matching message cached without its raw message it suggeststg messages list --chat=<id> --before=<id+1> --limit=100 --fresh, andwhynames the message.allowedChats(bcf6014).COMMAND_ACCESShascacheOnly, set fortg messages listwith--type,--sinceor--untiland fortg messages search. For those reads the guard resolves--chatand theallowedChatsentries from the cache alone. It still pinsargs.accountand hands the chat it checked to the command (checkedChat); writes still resolve an@usernamethrough Telegram. A name the cache can't resolve isINVALID_ARGSwithdetails.chatand 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 withINVALID_ARGS, the reason and thetg messages list --chat <chat> --freshto run first.Yours to decide:
allowedChatsset,tg messages searchfails withINVALID_ARGSwhen an@nameentry is not in the cache, wheremainwould resolve it through Telegram. It fails closed: an unresolved entry can't be compared with--chat.tg messages search --helpnow 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 checkclean,bun run test1266 pass,bun run test:e2e393 pass, 0 fail.Update:
mainmerged in (ac85803)mainup 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.
--type=round --sinceand the--untilmirror both answercomplete: false, missing: ["types"].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'sresults: [], count: 1, typesPending: false.next.suggestionnames thetg messages list --chat=<id> --limit=100 --before=<id+1> --freshand 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 innextbefore or after. A stopping point derived from stored facts was not possible:history_ranges.updated_atchanges whenever ranges merge, so it does not show that a fetch covered one ID. This replaces thesearch --typepoint of the section above.Yours to decide, new:
tg messages searchgains asuggestionkey,nullunless a matching message waits for its raw message. Filteredlistalready has it; without it search has no place for the retry. The alternative is to drop the hint from search and keep onlytypesPendingand 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 checkclean,bun run test1269 pass,bun run test:e2e394 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.
--type photo --limit 5answerscomplete: false, missing: ["history"]. After the suggested--freshfetch of 100 the same page has its 5 items andcomplete: true.--type voice --limit 5needed three fetches. Eachnextcarried 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.searchuntil a--freshpage of the newest messages is read; then both show it and the range ends at it. Until then the filtered page sayscomplete: true: it vouches for the messages the cache has heard of.--sinceseven weeks back returned its 34 messages at once and stayedcomplete: falsethrough 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