Repository navigation
Retain translated regions across scrolling with bounded memory and storage - #19
Draft
marufmoinuddin wants to merge 32 commits into
Draft
marufmoinuddin wants to merge 32 commits into
marufmoinuddin wants to merge 32 commits into
Conversation
The user names the server's base address and the model in Settings and pastes their key; the app sends a plain text Chat Completions request to <base>/chat/completions and reads the text on the device, so no image ever leaves the phone. - EngineId.CUSTOM (offered, user key, no default model): the user must name both the model and the address. - CustomEndpoint (core:model) reduces an address to its base: a pasted …/chat/completions is stripped, the path the user wrote is kept, no version segment is ever appended, and HTTPS is required. - CustomOpenAiEngine (core:engine) is a standalone LlmEngine: text only, and a server that refuses the optional temperature is asked once more without it. - The base URL lives in DataStore (an address, not a secret); the key stays in the existing SecureKeyStore. - The key sheet gains an address field for this engine only, and one save callback carries the key, the model and the address through a single ViewModel coroutine. Existing engines are untouched.
The user can bring their own LiteRT-LM model: browse the Hugging Face catalogue (or type owner/name to list a repository), download any .litertlm file, import one already on the phone, keep several, delete them, and pick the one the new "Offline model" engine runs. - ModelSpec (core:model) is what the store and the engine need of a model; LocalModel implements it, so the two built-in models behave exactly as before. The download key is unchanged, so a download in progress survives. - UserModel (core:model) is a model of the user's library. Its file name is built from its id, never from a remote path, and its context budget comes from the file's own KV cache (ekv...), clamped to what the runtime runs. - EngineId.LOCAL_USER is the one engine that runs the active model; the built-in models are untouched. - HfCatalog (core:engine) reads the catalogue anonymously and pins a download to the commit it was listed at, so the file's SHA-256 stays valid. Only huggingface.co addresses are ever fetched. - UserModelLibrary (core:engine) adds a model, imports a file (hashing it while it is copied), removes one and picks the active one. - The library lives in DataStore; a corrupt list reads as an empty one. The two built-in models, the Custom AI engine and the planned-engine placeholders are untouched.
The plan of a whole-page scan is pure logic, so it can be tested without a WebView: where to stop (70% of the viewport a step, always the bottom of the page), and what to keep when the patches do not fit in memory (the farthest from the viewport go first). translateViewportOnce is the body of translateViewport, extracted so a scan can run a step without the two follow-up captures (a page that was still loading, a canvas page with no text) that the continuous mode starts on its own. Nothing else changes.
…es it The three-dot menu gets a new item. It scrolls the page by itself, from the top to the bottom, and translates every stop with the machinery that is already there (capture, detect, OCR, translate, patches). The patches stay while the user stays on the page. The plan of the scan is pure logic (PageScanPlan): a step covers 70% of the viewport, so 30% overlaps and a bubble cut by one screenshot's edge is whole in the next; the last stop is always the bottom of the page. While the page is held the usual pruning is replaced by a memory budget of 96 MB of decoded bitmap bytes, so a scan does not lose its results: above the budget the patches farthest from the viewport go first, and those areas are re-made by the continuous mode when the user scrolls there. A scan that needs a key or runs on the device asks first how many screens it will be. Cancel scan keeps the session and the patches and scrolls back to where the scan started; a touch on the page stops it where the user is. Transient failures are retried twice and then counted as gaps; a missing key, an exceeded quota or a missing pack stop the scan at once and leave the failure in the bottom bar, which already offers the fix. Only pages that scroll as a window (vertical readers) are supported: a page that does not scroll is translated only as far as it shows, with a note saying so. No pipeline, detector, OCR, engine or capture code is touched.
…s it The scroll-back sat behind a local flag that was only set at the end of the try block, so a cancel (which leaves the block through the cancellation) never scrolled back: the page stayed wherever the scan had reached. The flag is now the field that cancelScan already sets, so the button scrolls back and a cancel by a touch (the user took over) does not.
…ry, warn about tiny models A server at home is not a hosted provider. It may answer with a bare object instead of an array, with the array inside a code fence, wrapped in a "translations" key, or with the translation under "english" or "translation". It may also put brackets inside the text of a bubble, which a naive cut would mistake for the array. The parser now tries the reply as a whole, then as the outermost array, then as the outermost object, and takes the first that yields a usable list of items. What the reply must still carry is unchanged: every requested id exactly once, nothing invented, nothing reordered. A wrong type anywhere makes the reply unusable rather than throwing, so a bad reply can no longer crash the app with a serialization error instead of saying "malformed". The retry no longer depends on the conversation. Some local servers rewrite a multi-turn history — the original input dropped, the order reversed — so a retry that said "your previous reply was wrong" could never work. The Custom AI engine now sends one fresh request that carries the input and the correction together, and the system prompt shows what a reply looks like when there is a single item. The hosted providers keep the three-turn retry they had. A reply whose content is a list of parts is read, and a reply with empty model/created/usage fields is accepted. The sheet warns when the model name gives away a model of about a billion parameters or less, which usually cannot follow the translation format. The warning does not stop the save.
Comic dialogue is translated cold: the reader sent no earlier line at all, and where context existed it was capped at the last two lines with nobody to say who was speaking. A pronoun had no antecedent and a name was a name only if the model had seen it before. Settings › Translation now has a three-way choice: Off, Standard (six lines) or Deep (twelve). The reader remembers every bubble it translates — the text, the translation, who said it, where it sits on the page — and sends the lines that come just before the new screen. The memory is in RAM and belongs to the page: it is cleared exactly when the screen patches are. The lines are asked for after the regions are known, so the context is "the lines above the first new bubble", which is right whether the reader scrolls up or down. The cloud engines and the user's own server are asked to say who speaks each line, and the earlier lines are shown as "[A] source => translation". The on-device models are not asked: their replies are numbered lines and a label would cost more than it returns. The reader's three-dot menu gains Characters…: the cast of the website being read, one line per character. It goes into the prompt as data, so the model consults it and never obeys it. Off is exactly today's behaviour: the same prompts, the same context, the same cache keys. The golden test holds the six prompts of today byte for byte, and it passes. The cache key now carries the model, the level and the character sheet: a page translated with one model must not be served for another. The first run after the update re-translates the screens of the engines that have a model.
The reader kept three screens of decoded overlays and dropped the rest, so scrolling far down and back re-read and re-translated everything it had already paid for. The distance rule is unchanged; a byte cap now applies as well, and both are the user's to choose. The pruning moves into PatchWindow, a pure function, so it can be tested without a device. The characterization test pins the rule the reader has always used — three viewport heights above and below — and passes before and after. The settings are read from the snapshot the view model already holds, never from disk on the main thread. Zero means Auto: the number of screens and the memory cap then follow the phone's own memory. The log lines say what happens, with counts only: how many patches are retained and how many bytes they use, how many were pruned and why, what a capture ended with, and which of the things that clear the patches happened.
The reader threw away every translation it had paid for as soon as the patch was pruned. This is the disk tier: one file per image, holding the rendered region as WEBP, the box as a fraction of the image's size, and a fingerprint of what the translation was made with. The file names come only from hashes: no part of an image key or a scope is ever a file name. A file that is damaged, truncated, absurd or from a newer version is dropped and the reader carries on. The budget and the time-to-live are arguments of the calls, not state of the store, so a change in the settings takes effect at once. The oldest file goes first when the store is full — and the file that was just written never goes: the reader is holding that translation.
A record is a fraction of the image's own size, so the same bubble comes back on a page laid out at another zoom, or at another width after a rotation. The anchor now carries the image's size, and the record is written from it. A record is skipped when it was made with other settings, when the image's shape has changed, when it lies outside the restore window, when the screen already has that bubble, or when its bytes cannot be decoded. The restore margin is three quarters of the prune distance, so a patch restored at the edge of the window is not pruned again at once. A canvas page is never restored: a paged canvas reader reuses the key for every page, so a record saved for one page would land on another. A picture the page drew itself is never restored either. The test that matters: ten screens of bubbles are saved, the reader walks to the tenth screen, comes back to the first, and the pipeline's own rule says none of the first screen's bubbles may be detected again — so the engine is never called for them.
The reader kept three screens of finished translations in memory and threw the rest away, so scrolling far down and back meant detecting, reading and paying for every bubble a second time. A finished translation is now also kept on disk: the rendered bubble as WEBP, its place on the image as a fraction of the image's size, and a fingerprint of the settings it was made with. Because the box is a fraction, the same bubble comes back on a page laid out at another zoom or at another width after a rotation. On every capture, before the region of interest is built, the saved records of the images now on screen are read and put back. The region of interest is built from the patches on the screen, so a restored bubble is in the "already done" list: the pipeline never detects it, never reads it and never calls the engine for it. The scope is the chapter, the budget and the time-to-live are arguments of the calls rather than state of the store, and a save or a restore that finishes after the page changed is dropped. Settings › Translation memory says how many screens are kept in memory, how much memory they may use, how long the saved ones live and how much disk they may take, and a button empties the store.
The flow notes the three lifetimes now: the decoded overlay in memory, the saved translation on disk, the whole-viewport cache unchanged. The architecture notes the storage and the order the memory is freed in. The testing notes list the new classes and the counts.
The guard read each view model and matched its public functions with a pattern anchored at the start of the text, so only the functions at the very beginning of a file were ever checked. Everything after the first was skipped as a getter, and a feature wired in the second half of a view model looked unreachable, so it was skipped too. With the pattern anchored per line, the guard immediately found what it had been missing: the memory trim had no caller, and two functions in the Studio's import view model had none either. The memory trim is now called from the reader screen's own memory callback, under memory pressure. The two Studio functions are upstream's and are declared as deliberately uncalled rather than deleted. The guard's own regexes are now checked like the feature: a temporary uncalled function in the middle of a view model must make it fail.
A save or a restore that started before onCleared must not outlive the reader and write to a scope that no longer exists.
A restored translation came back the wrong size and slightly to the left, because the save path built its record from the patch's percentages where the CSS pixels belonged: a bubble 20% of the image wide was stored as 20 pixels wide. The geometry now has one owner. The capture's numbers — the viewport's size, the scroll offset and the zoom — are taken once, and the same conversion serves the live placement, the record, the restore and the reanchor. Percentages become view pixels with the snapshot's own size, and view pixels become page CSS with the snapshot's own zoom. Nothing is re-derived from a rounded rectangle. The save also stops happening inside a state update, which may be evaluated more than once, and stops reading the scope and the fingerprint after the fact: a write carries the capture it belongs to. The records of the broken version are quarantined rather than drawn: their sizes are percentages, and neither the WEBP's pixels nor the zoom of today can say what the size was. The same picture twice on one page is now two images: a record says which occurrence it belongs to, so a translation cannot land on the wrong picture. The store's own count is measured again after every mutation that removes files. The cached total survived a clear, so the store believed it held bytes it had deleted, thought it was over its budget and evicted files that were still there. A clear advances the scope's epoch, and the write is refused inside the store's own lock: a write that was already on its way cannot undo a clear that came after it.
A patch was moved by the CSS offset it was made with but never resized, while the restore resized it with the image. The two rules disagreed, and the disagreement showed as a bubble that was suddenly the wrong size and no longer on its text. The anchor now carries the fraction of the image as well as the CSS offset. The reanchor reads both, so a page that was laid out at another width gets its bubbles moved and resized together, and a zoom changes neither. The anchor also says which picture it belongs to. The old code always took the first image with a matching key, so a patch on the second of two identical pictures jumped to the first one.
A reader who scrolls back to a page they have already paid for waited for a capture, and the capture happened only when the movement threshold said so. The saved translations came back inside that capture, so a small scroll brought back nothing at all. The saved translations now come back on their own, first, whenever the page settles: the page is asked where its images are, the records of those images are read, and the ones that match are decoded and published. No screenshot, no detector, no OCR, no engine call. A capture is still made for the bubbles that were never translated. The end of a whole-page scan now waits for the saves it started. The scan used to scroll back to the top while the patches it had produced were still being encoded and written, and the restore there found nothing.
…opened The fingerprint that says what a translation was made with was computed when the page opened. A model changed, a dialogue level changed or a character sheet filled in afterwards was filed under the settings of that earlier moment, and a translation made under one policy could be shown under another. It is now resolved at the start of every capture, before the restore, so the restore matches the policy that is in force. The dialogue level and the character sheet are part of that identity: they change what the engine is told. The sheet is a digest of its text, never the text itself. The log's "patchesBefore" is now sampled before the capture instead of after it, where it counted the patches the capture had just added.
The logs said how many translations came back, and nothing about the ones that did not. A reader whose bubbles stayed missing had no way to tell a fingerprint mismatch from a record of the wrong picture from a blob that would not decode. Every skip now has a reason: a name and a count, never a key, a URL, a line of text or a character's name. The evictions have their reasons too, and the whole-page scan's own eviction rule is said apart from the usual pruning, which it was not before. The counter that says how many bubbles are on the screen is now sampled before the capture, and the restore says how many candidates it found and how many were actually published — the two were the same number, and the first one was not the truth.
A translation is written after it is drawn, on a background thread, so a clear can land while a write is on its way. The tests now hold that order: a write that was on its way does not undo a clear, a clear does not delete what came after it, and a re-translate keeps its own replacement. The write is counted while it is in flight, and the end of a whole-page scan waits for the writes it started. A scan that scrolls back to the top while its patches are still being encoded found nothing when it got there. The settings now say what is true: a translation saved by the older version cannot be reused, and is translated again once.
The flow, the architecture, the testing notes and the changelog now say what is true: the geometry has one owner and the four coordinate spaces are named, the same picture twice is two images, the records of the broken version are kept but never drawn, the store's count is measured again after every change, a clear advances the scope's epoch and a write that was already on its way is refused, and the end of a scan waits for the writes it started. The test counts are the real ones: 781 unit tests in 115 classes.
A re-translate cleared the saved translations on a background thread and started its replacement at once, so the replacement could be refused as a stale write or be deleted by the clear that came after it. The clear is now awaited, and the replacement starts when it is done. The whole-page scan's memory budget now spends itself on the visible bubbles first: they are what the reader is looking at, and the ones far away are dropped before them. The budget is not a promise that the visible ones fit — a page of huge bubbles can exceed it — but the ones that are on screen are the last to go.
A bubble the reader is looking at is the last to go: the byte cap never drops it for a bubble that is further away, and the whole-page scan's budget is spent on the visible bubbles before the far ones.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stack and focused review
Depends on the companion dialogue contribution from
marufmoinuddin:pr/dialogue-context, and transitively guard/parsing and #8/#5/#6. Until dependencies land, GitHub's cumulative diff against main includes them.Incremental review range:
pr/dialogue-context..pr/scroll-retention. This contribution ends at commitd96af3ee0be7efc7448c1b680bc8f80ba07b7f67.Test result
974 tests; zero failures, errors or skipped tests. The first full run found an ambiguous Studio Delete selector; after scoping it to the manga row, the complete validation command passed. No production deletion behavior was changed for that fix.
Validation and current limitation
Validated on the development VPS using JDK 21, Android SDK platform 35 and the project Gradle wrapper:
The tested stack is based on upstream commit
1dca622e9f71d9ec4a8d12bc050b160c281c2101(the 0.3.0-era main). At publication, upstream main isaf42e2ca52c4179f38f62202999c74277c01f97d, four commits later, including Studio background translation and release 0.4.0. Integration with that newer main has NOT been validated. This is intentionally a draft for review, not a claim of merge readiness against 0.4.0.Physical-device testing has not been performed for this recovered version. No NPU/QNN binaries, NPU download scripts or unfinished provider-profile work are included. The original feature branches and dirty checkout have been preserved.