Skip to content

Harden compatible-server parsing and HTTPS download/update guards - #17

Draft
marufmoinuddin wants to merge 12 commits into
smnexstudio:mainfrom
marufmoinuddin:pr/guard-and-parsing
Draft

marufmoinuddin wants to merge 12 commits into
smnexstudio:mainfrom
marufmoinuddin:pr/guard-and-parsing

Conversation

@marufmoinuddin

Copy link
Copy Markdown
Contributor

Summary

  • Read compatible-server replies as arrays, fenced JSON, single objects or translation wrappers; accept text-part content.
  • Retry malformed Custom AI replies with the original input in a self-contained request.
  • Reject duplicate requested IDs, including numeric/string aliases, and reject non-string translation text.
  • Add a model-name size hint without blocking saving.
  • Retain HTTPS-only Custom AI endpoints and required API keys. Refuse cleartext model downloads and guard the production update client against cleartext requests and redirect targets.

Stack and focused review

Depends on #8 and its existing #5/#6 dependency stack. Until those land, GitHub's cumulative diff against main includes their changes. The incremental contribution is commit 2d2b7b769c821075418c3a00c51ce29eba88faa1, on top of the published whole-page-scan branch.

Local review range: whole-page-scan..pr/guard-and-parsing.

Test result

777 tests; zero failures, errors or skipped tests.

Validation and current limitation

Validated on the development VPS using JDK 21, Android SDK platform 35 and the project Gradle wrapper:

./gradlew --no-daemon --console=plain --max-workers=2 assembleDebug testDebugUnitTest :core:model:test

The tested stack is based on upstream commit 1dca622e9f71d9ec4a8d12bc050b160c281c2101 (the 0.3.0-era main). At publication, upstream main is af42e2ca52c4179f38f62202999c74277c01f97d, 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.

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.

This branch has not been deployed

No deployments
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.

1 participant