Skip to content

feat: add llama.cpp inference through llamadart - #628

Merged
DenisovAV merged 28 commits into
DenisovAV:mainfrom
leehack:feat/llama-engine
Oct 16, 2026
Merged

DenisovAV merged 28 commits into
DenisovAV:mainfrom
leehack:feat/llama-engine

Conversation

@leehack

@leehack leehack commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds flutter_edge_ai_llama, an opt-in GGUF provider through llamadart. Register LlamaEngineProvider, install ModelFileType.gguf, and use core's chat API. Includes streaming, durable tool history, context trimming, native LoRA recovery, a six-platform example and setup docs. Core gains no mandatory runtime dependency.

Uses core 2.4.0, SDK 0.13.1 and Apple companion 0.13.0. GGUF embeddings are deferred; Web LoRA is unsupported. Runtime artifacts remain SDK-owned.

Type of Change

  • Bug fix
  • New feature
  • Documentation update
  • Refactoring
  • Test addition

Testing

At 711afd2c0 (2026-10-16):

  • Connector analysis, 35 tooling tests, VM/Chrome contracts and 14 example tests pass. Real browser worker/Wasm inference verifies cancellation rollback and immediate retry.
  • CI: all six connector release builds and five native CPU lifecycle lanes pass. Repository-wide tests, all four shared example builds and rendered docs pass.
  • A separate Apple workspace uses source core/connector members, hosted SDK/companion, root hooks and a direct app-member companion dependency. macOS/iOS release builds contain the companion runtime with no hook-bundled duplicate (iOS minimum 16.4). macOS/iOS 26.4 simulator CPU pass three load/chat/recall/trim/cancel/retry cycles with SmolLM2-135M Q8_0, without startup retries.

20 checks pass; 3 fail: two hosted checks await core 2.4.0 publication (pub.dev: 2.3.3), and advisory beta codelabs report existing material.dart deprecations. Gates remain intact.

The maintainer's Galaxy S24 result used an earlier revision/runtime pair.

Checklist

  • Code follows style guidelines
  • Self-review completed
  • Complex behavior documented
  • End-user documentation updated
  • No new analyzer warnings
  • Regression tests added

Before publication: current-pair phone/GPU and oldest-OS qualification, App Store submission, mixed Apple workspaces and package ownership. XML nullable-string decoding remains an SDK limitation; see platform and tool limits.

@leehack

leehack commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

@DenisovAV - as discussed I implemented the plugin. Would you mind reviewing it? 😃

@leehack
leehack marked this pull request as ready for review October 11, 2026 15:12
@DenisovAV

Copy link
Copy Markdown
Owner

Thanks, Jhin. This is a big and careful piece of work, and I especially like that unsupported options throw instead of being silently ignored. Before a line-by-line review, a few structural points. Note that tomorrow's core release, which brings EmbeddingGemma 2, changes the API engines build on (#625, #627), so some of this code will have to move anyway.

  1. A ModelFileType.gguf. Today a GGUF is declared as binary, which MediaPipe also claims, both at priority 0, so registration order decides which engine loads it. Every other engine here is selected by its declared file type alone. I'd add gguf to ModelFileType in that release and have canHandle check only that. On web, core's placeholder spec already carries the declared fileType, so canHandle works there without looking up the active model.
  2. Embeddings: could you split them into a follow-up PR? The embedding API changes in that release, expected tomorrow. It also adds a self-contained model spec, which removes the unused tokenizer companion a GGUF needs today. Things to keep for that PR:
    • priority 0 ties with LiteRT's catch-all backend; ONNX uses 10 for this;
    • useTaskPrefixes defaults to true, which puts EmbeddingGemma's prefixes on any GGUF model, so nomic, e5 or bge would lose quality without an error;
    • does engine.embed return L2-normalized vectors? RAG relies on that.
  3. Restore after restart: restore_model.dart reads core's preferences through ActiveIdentityStore / PreferencesKeys and re-activates the model itself. If core fails to restore an imported (FileSource) model after a restart, that is a core bug. Please share the repro and I'll fix it there, so this file can go.
  4. Web model location: after refactor(core)!: move core internals under lib/src behind five public libraries (EG2 train A — merge on publish day only) #625, core's WebModelSourceResolver (in engine_web.dart) covers both needs publicly: resolveActiveInferenceModel() returns the blob URL and tells an OPFS stream apart, and activeInferenceSpec() returns the real active spec. That replaces the direct WebModelManager use and the web-active / active.bin detection.
  5. flutter_edge_ai: 2.2.0 is an exact pin (2.2.0 is on pub.dev now), which locks users out of every core patch. Please make it ^2.2.0, and consider ^0.11.1 for llamadart unless the exact pin is deliberate.

#625 also moves core's internals under lib/src behind public libraries (engine.dart for providers, engine_web.dart for web helpers), so the core/registry/... imports will move, the same way ours do. I'd keep this PR as a draft until that release lands tomorrow, then rebase the inference part onto it. After that, the full review.

DenisovAV added a commit that referenced this pull request Oct 12, 2026
… uninstall — core 2.2.1, litertlm 1.12.1, mediapipe 1.2.1, builtin_ai 0.3.4, onnx 0.5.7, genkit 0.9.0, genkit_hybrid 0.3.1, embeddings 2.2.3, rag 1.0.1 (#632)

* fix(core): a fromFile model or STT model is active again after a restart — core 2.2.1

A fromFile install is used in place; nothing is copied into core's model directory. The inference and STT restores looked only in that directory, found nothing and started the app with no active model, although the file never moved. They now read the persisted source and, for a FileSource, use its path, as the embedding and TTS restores already did. A FileSource tokenizer also skips the legacy companion migration, which renames files.

file_source_restore_test covers both kinds; the two in-place cases fail on the previous code. Found while reviewing #628, whose restore_model.dart works around it.

* fix(core): never delete an app's fromFile files; follow a persisted source only from the one-key record

Review of the restore fix (Codex), each finding re-checked against the code:

- deleteModelFile resolved a FileSource filename to its external path and deleted the app's original, so uninstallEmbedder/Stt/Tts (and a replace-policy switch) removed files the library never created, while uninstallModel kept them. It now skips a registered external file; whoever drops the model record calls forgetExternalFile, which unregisters the path and the cleanup protection. The restore fix had made this reachable for STT after a restart.
- The per-field identity keys of releases before 2.1.1 can pair one model's filename with another model's source. The inference and STT restores now follow a persisted source only when it comes from the one-key record (ActiveIdentityStore.hasRecord); otherwise they look in core's directory as before.
- file_source_restore_test now installs with fromFile for real and checks isModelInstalled after a restart, the per-field cases, both uninstalls and the deleteModelFile primitive; uninstall_and_introspection_test asserts the new contract.

* fix(core): whose a file is and where it lives come from its own repository record

Full review of #632 (10 reviewers) found that keeping fromFile files on
uninstall broke the restore's "file exists means installed" shortcut, and that
the external-path registry was a poor ownership signal. Reproduced on the
previous head: an uninstalled fromFile model came back active (hasActiveModel
true, getActiveModel "no longer installed"); a repeated deleteModel deleted
the app's file sitting in core's directory; a registration left by a <=2.2.0
uninstall made deleteModel keep core's own download.

- Restore (inference, STT) resolves each file through its repository record,
  keyed by the identity's own filename: no record, not restored; a FileSource
  record, its path or else the same name in core's directory (iOS moves the
  container on update); anything else, core's directory; the file must open,
  not just stat (macOS sandbox, revoked Android grants). The embedding restore
  also requires its records. ActiveIdentityStore.hasRecord is gone.
- An STT tokenizer the app installed with fromFile is never migrated (renamed);
  the migration keeps the original record source instead of writing a
  FileSource for core's renamed copy.
- Uninstall (_uninstallFile): no record, nothing deleted; a FileSource record,
  the app's file is kept; else core's copy is deleted. deleteModelFile decides
  by the record, not the registry. The registration is forgotten
  unconditionally and before the record goes, here and in uninstallModel, so
  a failure leaves a retry. The protected-files registry throws when a write
  does not persist.
- Docs: speech.md and the speech skill no longer say uninstallTts deletes
  fromFile files; getting-started, deleteModel/uninstallEmbedder doc comments,
  preferences_keys, DESKTOP_SUPPORT pin, CHANGELOG wording.

file_source_restore_test: 19 cases, 9 of them failing on the previous head;
each of 11 production mutations turns at least one red. Two older test
fixtures now leave files the way an install does (with records), and one
pre-refactor STT fixture records its download with a network source.

* fix(core): a file's record follows every pick, and a restore takes no file but the recorded one

A second review of the record-based rule found it only as good as the
records and the lookups around them:

- Installers skipped a name already installed, so picking a file from a new
  path under the same name kept the old record, and a restart ran the old
  file. A fromFile request from another path is installed again; network
  installs and a LoRA installed with the model are left as they are.
- The fallback to a file of the same name in core's directory restored a
  stranger: on desktop it reached the user's Documents. It is gone; on iOS a
  path recorded in an earlier app container is moved into the current one.
- An unreadable file was "no model" for the whole process. A restore now
  checks that the file is there; the engine's open reports why it cannot be
  read.
- The legacy tokenizer migration decides by the record under the old name:
  none, nothing to migrate (or finish one an earlier launch left half done);
  the app's file, only its record and registration move; core's copy, renamed.
  It renamed an app's tokenizer for legacy embedders, invented records, and a
  legacy STT tokenizer restored in place was not installed under its new name.
- The embedding restores, atomic and legacy, find their files through their
  records like inference and STT.
- deleteModelFile keeps any name the app installed with fromFile; a
  replace-policy switch cleans up tasks before dropping the records.
- The protected-files registry no longer throws on a write that did not
  persist: the prefs cache already held the value, so a retry wrote nothing.
- Two embedding race tests seed records again, so the lease checks are what
  they test; TTS fromFile and getting-started docs say uninstall keeps files.

* fix(core): every install path keeps a file's record current, and cleanup spares the app's files

A third review found the rule held on the builders' main path only:

- ensureModelReadyFromSpec skipped a fromFile file by its name, so a pick
  from a new path kept the old record and a restart ran the old file. It now
  registers the new path, as the installers do; nothing is downloaded.
- A LoRA is installed by its own record: picked anew it follows, added to a
  model already installed it is installed.
- A download replaced by the app's file is deleted — nothing else would ever
  free it — unless the app's file is that very copy; the same as TTS.
- A fromFile file picked again after it is gone is installed again, so the
  install reports it instead of skipping.
- The tokenizer migration never overwrites a record already under the new
  name, which a newer install may have left; a plain record with the same
  source is an earlier launch's leftover and goes.
- The TTS restore needs its records, like every other restore.
- Orphan cleanup also protects the on-disk name of each fromFile record: an
  app's tokenizer in Documents keeps its own name while its record has the
  namespaced one.
- A file picker's /private/var spelling of this container is not logged as a
  container move.

* feat(core): one install rule for every installer

Installing a name already installed from another source behaved
differently per installer: TTS re-installed on any change and deleted the
copy it replaced, the other builders skipped by name, and the deletion
added for them in this PR compared paths as strings — so a pick of core's
own copy under another spelling deleted the very file just picked, and a
restored spec handed back made core's download the app's.

install_rule.dart is now the one implementation, used by the inference
(with LoRA and ONNX directories), STT, embedding and TTS builders,
ensureModelReadyFromSpec and the legacy calls through it:

- plan (no side effects, every error raised here) → install → activate →
  release;
- skip only when the record names the requested source and the file is
  there: another URL (query, fragment and token aside), another picked
  path or a gone copy is installed again;
- "the same file" by identity — resolveSymbolicLinks, then
  FileSystemEntity.identical — not by path string; core's own copy picked
  with fromFile stays core's;
- a download that would land on a file the app installed with fromFile
  throws ModelStorageException; one replacing the app's file elsewhere
  leaves it and forgets its registration;
- core's earlier copy is released after activation, inside core's model
  directory only, if it is still the journaled file and no record reads
  it; journaled before the record changes, retried at the next start, and
  a failed delete never fails the install.

ensureModelReadyFromSpec now records companions under their namespaced
names. File identity, the iOS container move and stamps live in
utils/local_file*.dart behind a conditional export, so dart:io stays out
of the web build. The helpers this replaces are gone.

* fix(core): the install rule after review — journal lane, three-valued identity, own files kept

A four-agent review of the install rule found defects in it:

- The copy journal lost entries: a release wrote back the journal it had
  read before its deletes, erasing a copy an install journaled meanwhile.
  Journal operations now run one at a time.
- A journaled copy a record still reads, or that could not be told from
  one, was dropped and never released; it now stays for a later release.
  Entries are kept relative to the model directory, so they survive iOS
  moving the app's container; an unreadable entry no longer drops the rest.
- File identity is same / different / unknown. A pick that cannot be told
  from core's copy is installed (it used to be skipped, leaving the old
  model after a restart), and its copy kept; a download whose target cannot
  be told from an app's file is refused with that reason. A path naming
  nothing is never "the same", so an app's file that is gone blocks nothing.
- A pick of a resource the iOS bundle holds stays core's, like a copy.
  Core's copy the app has written a file of its own over (another size) is
  the app's; a copy cut short is downloaded again.
- The collision check runs only for files that are installed, so an
  installed name is not refused for another name the app put on its copy.
  A missing source handler is reported by the plan, before anything changes.
- A registration an older release left under a name core holds is
  forgotten even when the file is skipped.
- A replace-policy switch keeps the spec's own files; it no longer deletes
  core's copy handed back with the spec, then reports it missing.
- ensureModelReadyFromSpec and the calls through it report install failures
  as ModelStorageException again, as they did before the rule.
- Docs say what the rule covers: the builders and ensureModelReadyFromSpec
  on Android, iOS and desktop; a version told apart only by the URL query is
  not; the old copy goes once the new file is active, or at the next start.

* release: core 2.2.1 carries #636, #637 and this fix — no 2.3.0

Nothing after 2.2.0 is published, so the next core release stays a
patch: main's 2.3.0 goes back to 2.2.1 in pubspec, both podspecs and
AGENTS, and the CHANGELOG has one 2.2.1 section with #637's lines,
#636's and this PR's. litertlm 1.12.1, mediapipe 1.2.1, builtin_ai 0.3.4
and onnx 0.5.7 require flutter_edge_ai ^2.2.1; the core install pins and
getting-started's "since" say 2.2.1.

* test(example): the install rule on a device — another spelling of core's copy, a mapped copy, a restored fromFile model that generates

Host tests cannot reach Android's bind mount of the app's data, a
directory link on desktop, deleting a copy a loaded model maps (Windows
refuses), or a fromFile model restored after a restart that then loads and
generates. Model: functiongemma-270M-it.litertlm, staged per platform.

* release: pins, docs and codelab for the 2.2.1 train; embeddings 2.2.3, rag 1.0.1

The release walk over every package found what still pointed at the
previous versions. The READMEs that ship (core, litertlm, genkit, rag) and
the site docs now pin litertlm ^1.12.1, mediapipe ^1.2.1, core ^2.2.1,
embeddings ^2.2.3 and rag ^1.0.1; MIGRATION and DESKTOP_SUPPORT follow.

embeddings and rag READMEs differed from their published archives (the
ONNX embedding backend; the storage pins and SQLite's Flutter 3.47 floor),
so both get a docs-only patch release.

getting-started, the core README and the inference skill describe what
2.2.1 changes for apps: installing a name again from another source
replaces it, a fromFile file is used in place, restored after a restart and
never deleted by core, and with nothing installed getActiveModel throws
NoActiveModelError.

The hybrid Genkit codelab moves to genkit_flutter_edge_ai ^0.9.0 — in 0.x a
minor is breaking, so ^0.8.0 would keep learners on 0.8.x. All 40 codelab
apps analyze and pass their tests against the local packages. The example's
Podfile.lock carries mediapipe 1.2.1.
@leehack
leehack marked this pull request as draft October 12, 2026 11:29
@leehack leehack changed the title feat: add llama.cpp inference and embeddings through llamadart feat: add llama.cpp inference through llamadart Oct 12, 2026
@DenisovAV

Copy link
Copy Markdown
Owner

@leehack thanks for narrowing this to inference on 2.2.1 — the embeddings split, the ^0.11.1 / >=2.2.1 <2.3.0 constraints and dropping restore_model.dart are what I hoped for. Two changes in 2.2.1 touch the connector:

  1. Web: the synthetic web-active / active.bin spec is gone (fix(web): reuse the loaded model while the active model and arguments are unchanged — core 2.2.1 #636). The web shell now passes canHandle / createModel a spec built from the active model — its real name and modelSource, with the modelType / fileType the caller asked for — and keeps the loaded model while those and the arguments stay the same (before, every getActiveModel on web closed the model and loaded it again). So resolveInferenceSpec in model_location_web.dart no longer matches anything and can go: canHandle sees the real .gguf file name directly.
  2. InferenceModel.isClosed (feat: InferenceModel.isClosed; getActiveModel never returns a model that is closing — core 2.3.0 #637). Core reads it to notice a model the app closed without awaiting: it waits for that teardown and builds a new model instead of handing the closing one back. LlamaInferenceModel keeps _closed but doesn't override the getter, so core always sees false. @override bool get isClosed => _closed; is all it needs — your close() already shares the teardown in progress and fires the close listeners after engine.dispose, which is the rest of what core expects.

Still open in core: the inference LoRA companion does not survive a restart (your docs describe it correctly), and ModelFileType.gguf hasn't landed yet, so the file-name check in canHandle stays for now.

@DenisovAV

Copy link
Copy Markdown
Owner

@leehack both core gaps are in #649:

  • LoRA across a restart. The active model now restores its LoRA as spec.loraSource, on mobile and web. A LoRA whose file is gone restores nothing, rather than the model without it.
  • ModelFileType.gguf. canHandle can check the declared type alone, and MediaPipe no longer claims your files. Core passes messages through raw and cleans replies as it does for binary today, so what your engine sees does not change. One side effect: a GGUF's LoRA file is named model__adapter.gguf instead of model.gguf__adapter.gguf.

Once it lands, the restart note in your docs and the .gguf file-name check can go.

@leehack

leehack commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

@DenisovAV I'm waiting the #640 and #649 to be merged. But the work should be almost ready.

DenisovAV added a commit that referenced this pull request Oct 12, 2026
…eType.gguf (#649)

* fix(core): the active inference model keeps its LoRA across a restart

The persisted identity named the model file only, so a restart restored
the model without its LoRA: it loaded with no adapter and no error, and
a connector reading spec.loraSource (llama.cpp, #628) found none.

Mobile and web now persist the LoRA's filename and source with the
model and restore it as loraSource. A LoRA whose file is gone restores
nothing, the way a missing model file does, rather than the model
without it. Identities written before this have no LoRA field and
restore as before.

* feat(core): ModelFileType.gguf, so a llama.cpp engine is chosen by type

A GGUF had to be declared as binary, which MediaPipe also claims at the
same priority, so registration order decided which engine loaded it,
and an engine could tell it apart only by the file name. Every other
engine is selected by its declared file type alone.

gguf: the chat template is the file's own (llama.cpp applies it), so
transformToChatPrompt passes messages through raw; replies are cleaned
as a binary's are, so a trailing end-of-turn marker a template renders
as text is stripped. MediaPipe does not claim it.

* fix(core): .gguf is a supported extension, so storage counts and reclaims GGUF files

Without it the storage scan behind getStorageInfo, getOrphanedFiles and cleanupStorage filtered GGUF files out: a multi-GB model went uncounted and an orphaned one could not be reclaimed. Found by Codex.
@DenisovAV

Copy link
Copy Markdown
Owner

@leehack both are in now: #640 shipped as core 2.3.0 / 2.3.1 on pub.dev, and #649 is merged to main and goes out with the next core patch — until then a git or path override gets you the LoRA restore and ModelFileType.gguf.

For the rebase:

  • Imports. Core's internals moved to lib/src; engines import package:flutter_edge_ai/engine.dart (RuntimeConfig, CloseNotifier, …). MIGRATION.md has the old-to-new table. The >=2.2.1 <2.3.0 constraint moves up with it.
  • Embeddings are reworked too, so the embeddings follow-up can go straight onto the new API. A backend now extends EmbeddingBackendProvider and returns an EmbeddingPassDescriptor(engineTag:, factory:, config:, activeBackend:) from describe(); core builds, hosts and closes the model, so the connector no longer owns an EmbeddingModel. Apps call embed with an EmbeddingInput, and an input that is too long throws EmbeddingInputTooLongException instead of being truncated. The embedding-backend rows in MIGRATION.md cover the rest.

@leehack
leehack marked this pull request as ready for review October 12, 2026 22:20
@leehack

leehack commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@DenisovAV The connector review fixes are pushed in 266a2496 (including upstream main 08dc913). The PR description is rewritten around the current implementation, with earlier qualification records moved into a collapsed historical section.

For the fourteen review items:

  1. Core floor is ^2.3.2; CI/archive and the standalone consumer use hosted core without overrides. Removed the pending-patch setup text.
  2. Results answering committed tool calls survive stop/error and queued cancellation; both rollback and retry paths have regressions.
  3. Omitted output cap uses remaining rendered context. Truncated tool turns and empty completions fail before assistant history is committed.
  4. The Web facade rejects the restored resolver's loraPath, with a getActiveModel regression. Wording now describes the connector's unwired adapter path.
  5. iOS picker gets public.data; all Runner configurations include the two memory entitlements and the Apple guide documents them.
  6. Connector decisions use Dart errors; llamadart runtime failures keep their exceptions.
  7. Local override paths are preflighted before runtime mutation. Installed adapters load once through ModelParams.loras; serialized overrides restore that baseline, with failure-path tests.
  8. Consecutive replayed assistant parts merge into one turn; thinking/text/tool-call replay is tested.
  9. Backend identity comes from getBackendName(), with CPU/Wasm and unknown-name coverage, rather than requested layer count.
  10. Barrel exposes only the provider, projector resolver and two tool types. Loader injection is an explicitly test-only named constructor; demo uses core interfaces.
  11. Docs now require the consumer [llama_cpp] selection beside Flutter Edge AI LiteRT-LM and the direct Apple companion, including the silent iOS wrong-runtime risk. The SDK fix is separate below; the combined macOS setup remains unqualified.
  12. Vulkan default, current support matrix, root AGENTS wording and 0.0.1 changelog are corrected. Web fetch/validation tools ship in the archive and accept an app output directory.
  13. Android uses core URL download instead of the large Java-heap picker. Successful replacement removes only the demo's previous owned files, preserving external inputs.
  14. Native/device/Web lanes require JSON-reported execution and successful completion of the model test; missing/skipped runs fail. Capability fixtures have an explicit runner. Failed smoke output is printed before the nonzero exit propagates.

The package retains core's minimum Flutter/Dart floor, while connector checks pin their tested SDK. Workspace .fvmrc, website workflows and core CONTRIBUTING retain upstream values. Core-only PRs run contracts/package gates; heavy lanes are scoped to llama/shared build changes, nightly or dispatch. The future RuntimeConfig.loraPath seam is left for your core decision. Copyright, bundle IDs and pub.dev ownership remain to settle before first publication.

Local validation: 61 VM contracts, 64 Chrome contracts (five explicit skips), nine demo tests, 24 Python tooling tests; warning-free hosted archive, hosted external-consumer/native lifecycle, real browser worker/Wasm generation, import/Web graph guards and rendered website build passed. Mutation checks fail when queued-result preservation, context budgeting or facade adapter rejection is deleted. All 20 current-head CI checks passed, including hosted Android/iOS three-cycle lifecycle completion. A fresh local iOS 26.4 simulator passed all three CPU lifecycle cycles with normal DDS, unchanged assertions and a successful JSON execution gate. The earlier pre-test stall did not recur; its cause remains unproven. Only task-created simulators were removed.

Native-owner questions are tracked separately: archive digest verification in llamadart #1015, and framework plist deployment metadata in llamadart-native #110. I verified the missing plist key and binary minos 16.4; an App Store rejection has not been reproduced. No runtime artifacts were patched or released.

@leehack

leehack commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

The conditional-default proposal is now implemented separately in llamadart #1021: either Flutter Edge AI engine in the app's dependency closure omits implicit SDK LiteRT-LM; explicitly naming litert_lm beside your LiteRT-LM engine fails before asset emission with the root [llama_cpp] fix. Connector-only explicit selection is preserved, and unrelated apps retain their defaults. The SDK LiteRT Apple companion counts as explicit ownership, including when parent-workspace hook settings already omit LiteRT assets; the documented llama.cpp companion setup remains required.

It also handles parent-workspace hook settings without mistaking unused sibling packages for app dependencies. All 273 hook tests and analysis passed, including production emitted-asset assertions and four-platform explicit rejection. Deleting the selection call makes the regression tests fail. The final SDK head d328e2396 has 28 passing checks and five expected path/deployment skips (including 89.92% Linux line coverage); it remains draft for review and it is not published and does not yet change the 0.11.1 dependency used here.

In #628, the consumer define is therefore still documented as required with your engine, including the duplicate-library and silent-iOS-loader consequences you reproduced. The Apple companion is explicitly required; the conflicting combined macOS recipes remain unqualified. Shared-binary ownership is left for future coordinated work.

@leehack
leehack requested a review from DenisovAV October 13, 2026 17:47

@DenisovAV DenisovAV left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jhin. This round fixes nearly all of the fourteen items: the 2.3.2 floor, tool results surviving a stop, the remaining-context budget, Web LoRA through the facade, Dart error types, the adapter at load time, replay merging, getBackendName(), the trimmed barrel, the docs and the smoke gates. I reran the full review over 266a249. I reproduced every Dart finding below on your _FakeEngine, using a scratch copy of connector_test.dart. I'm happy to share it.

Before merge

  1. A replayed tool pair is committed twice. After clearHistory(replayHistory:) with a call and its result, one successful turn leaves the result in history twice:
    fullHistory → text, toolCall, toolResponse, text, toolResponse
    next request → user, assistant, tool, assistant, tool, user
    
    The success path at llama_inference_session.dart:542-543 commits _pending but doesn't clear it. The finally _commitAnsweredResults() then sees the call as committed and adds its result again. Strict templates reject the stray tool message, and a persisted history no longer replays ("Tool result has no matching unanswered call"). Clearing _pending/_pendingTranscript after the commit fixes it. Please assert fullHistory after the replayed turn, not only the request sent during it.
  2. A stop or an error right after a replay erases the restored conversation. The replay sits in _pending, and the rollback clears it:
    replay [user, model] → add 'next' → stop (or error) → fullHistory: 0 → next request: [user]
    
    The context-budget StateError is the likeliest trigger, and it is most likely right after restoring a long chat. Committing the validated replay at the end of clearHistory (a session-level restore) keeps the rollback to what was staged afterwards.
  3. Replayed tool calls in core's own shape are refused. Core's genai converter and genkit write Message.toolCall as {"name": …, "parameters": …}, or a JSON list of them (genkit_flutter_edge_ai/lib/src/converters/request_converter.dart:598-609). Both throw ArgumentError: Replayed tool calls need declared names…. Genkit replays the whole history into a fresh chat on every request, so every Genkit tool flow on GGUF fails on its second model call. Please also accept the flat shapes, assigning ids and pairing results by name in order. Core has no documented schema for that text, and I'll fix that on my side.
  4. llamadart 0.12.0 is out with your #1021. ^0.11.1 excludes it. Moving to ^0.12.0 with companion 0.0.22 turns the required define into enforcement, and brings the Adreno 750 Vulkan exclusion. The PR body ("not published") and README.md:15 ("0.11.1+") need updating either way. Keeping the define in the docs as defence in depth is fine.

Before publish

  1. Context.
    • maxOutputTokens works as a reservation, not a cap. With 128 and 98 tokens of room the turn throws StateError (:414-418); min(cap, remaining) matches core.
    • The chat overrides generateChatResponseAsync, so core's trimming never runs and tokenBuffer is ignored. A long chat with the example's settings (2048 / 128) dead-ends at about 1920 tokens. Trimming whole turns, never splitting a call from its result, would match the other engines.
    • Audio and image tokens aren't in the count. That is documented.
  2. A poisoned runtime stays in core's cache.
    • After a failed LoRA cleanup the queue is invalid, but isClosed stays false, so getActiveModel keeps returning the model. Every session then fails with "close and reload". Starting close() on invalidation, without awaiting it inside the queued action, lets core evict and rebuild it.
    • A failed forward setLoraSource invalidates even when the restore succeeded. That's an adapter made for another base model, which llama.cpp rejects before touching state. Invalidate only when the restore fails.
    • The catch at :608-609 drops every error while the session is stopped, including that cleanup failure. Keep the cause in invalidate(error, stack) and put it in the StateError.
  3. Smaller Dart items.
    • A tool call with empty arguments ('', which llamadart's parser produces for a no-argument call) fails as "malformed JSON tool arguments". Treat a blank value as {}.
    • createSession/openSession throw synchronously on a closed model. Make _makeSession async.
    • Output-validation failures throw llama.LlamaInferenceException, which the barrel doesn't export or document. genkit maps it to INTERNAL, so genkit_hybrid silently falls back to the cloud branch.
    • backend_config.dart:
      • llama.cpp's OpenCL and HIP map to null, and BLAS maps to null instead of cpu, so an explicit GPU request that lands on BLAS doesn't throw.
      • On web the bridge reports every device, for example WebGPU, CPU, and cpu wins, so WebGPU would report CPU and preferredBackend: gpu would always throw. I read that from the bridge source; I didn't run it.
  4. Public surface. LlamaProjectorResolver still returns llama.ModelSource, so apps import llamadart and juggle two ModelSources. The type also allows URL/HF sources that make llamadart download outside core's installer. Future<String?> wrapped internally would close both. withLoader is still public API; a non-exported src/ factory would hide it. final class on the three exported classes keeps members addable.
  5. Apple.
    • llama.framework's slice plists have no MinimumOSVersion (your llamadart-native #110). Until that's fixed, please say in the README that App Store submission is unvalidated.
    • A pub-workspace member app (the README tells workspace users to put the hooks block in the root) makes the hook treat the root as a non-Flutter package. It then takes the hook path: libllamadart gets plist 13.0 against minos 16.4 (the ITMS-90208 case we shipped once in #286), and the companion's copy is embedded too. Please document that as unqualified, or detect the companion from the member app.
    • On iOS the picker's Inbox copy is never deleted, so a 2.5 GB import costs three copies at peak.
  6. Android.
    • CI runs only the x86_64 emulator, so the arm64 variants phones load never execute. One arm64 run (FTL works) before publish, please.
    • There is no armeabi-v7a bundle and nothing says so; abiFilters in the example plus a line in the docs.
    • On Android the example keeps every downloaded model. Uninstall the previous one after a replacement loads.
    • After a restart, "Load URL" with the restored model's name closes the loaded model, then fails on the non-URL.
  7. Web.
    • Models over about 2 GB have no route: cacheApi and none both buffer one Uint8List, and a streaming install is refused only after the full OPFS download. Please state the ceiling.
    • The mem64 assets ship but index.html never wires them.
    • Threads are fixed at 1 although isolation is mandatory.
    • validate_web_build.py requires byte-identical _headers and cache_api.js, which fails consumer apps that add their own headers.
  8. CI and docs.
    • On schedule, dorny/paths-filter@v3 has no base and probably fails, which would skip every nightly lane; with: base: main avoids it.
    • The llama.cpp archives are still unverified (#1015, not in 0.12.0 either); one line in platforms.md would say so.
    • A floating ^0.11.1 next to the exact companion 0.0.21 can break Apple consumers on a llamadart patch; move them together.
    • llama.md still says "This draft…", talks about historical evidence, and has "import" where Android downloads.
    • doc/deferred_embeddings.md ships with references to a commit that a squash merge drops.
    • Root AGENTS.md:167-169 should go back to main's wording, and line 170 could add the iOS 16.4 / macOS 14 floor.
    • verify.py --core-path is dead code now.
    • The exact 3.47.1 check stops verify.py contracts on the workspace's 3.47.0, which the package AGENTS.md tells agents to run.

A correction to my last review: on Android, Vulkan is bundled but auto resolves to CPU, so "included" is the right word. "Used by default" holds only for Linux and Windows.

On my side

  • One documented Message.toolCall text schema in core (item 3).
  • Stop semantics. Core keeps the user turn and a non-empty partial reply, while this connector drops both. In a voice barge-in the model then loses the question being corrected. I'd like one rule in core's chat contract.
  • An explicit contract for subclassing InferenceChat. Its private history is dead in LlamaInferenceChat, so imageMessageCount is always 0.
  • The LoRA seam. The shells could pass artifactPaths for inference too, which would let the provider drop FlutterEdgeAiPlugin.instance.
  • LICENSE ("Copyright (c) 2024 Jhin Lee"), the example bundle IDs (dev.llamadart / dev.leehack) and pub.dev ownership, as before.

@leehack

leehack commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the connector-owned review at d6147f83c.

  • Fixed durable history/replay, tool argument normalization, persisted pairing/IDs, hidden reasoning, and runtime failure/cleanup handling.
  • Updated Web bridge v0.1.59, example imports/Android replacement/URLs/ABIs, docs and dependency policy.
  • Added startup-only bounded iOS retry with live output, stricter Web validation, and APK/published-file gates.

All 22 checks pass. Regressions reproduce 14 failures on the previous source, plus the trimming/ID edge. Real desktop/Web/mobile CPU runs, the iOS temporary-import regression and default APK validation pass. The picker dialog itself was not automated.

Shared core contracts, merge-time README updates and publication/ownership decisions remain on your side. Ready for re-review.

@leehack
leehack requested a review from DenisovAV October 14, 2026 12:05

@DenisovAV DenisovAV left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jhin. Round 2 is fixed in substance. I reran my seven experiments on your _FakeEngine at 19b7d92, and every one now behaves correctly:

  • a replayed tool pair is committed once;
  • a stop or an error after a restore keeps the restored history;
  • the flat core/Genkit shapes replay;
  • createSession fails through its Future;
  • blank arguments arrive as {};
  • the cap shrinks to the remaining 98 tokens;
  • a failed LoRA cleanup closes the model, with the cause in the peer's error.

Codex found nothing. CI is 20/20, and the merge with main is clean. Moving to llamadart 0.12.0 and companion 0.0.22 was the right call.

The new code paths have a few edges. I reproduced every Dart item below on the same fake, using a scratch copy of connector_test.dart. I'm happy to share it.

Before merge

  1. A no-argument tool call is stored with empty arguments. The call reaches the app as {}, but it is committed with rawJson: '' (llama_inference_session.dart:575).
    • The next turn sends '' back to llamadart. Its generic, Llama 3, Mistral and Gemma 4 handlers fail on that (template_render_context.dart _argumentsToObject), and generic is where a no-argument call comes from.
    • The transcript stores "arguments":"", so clearHistory(replayHistory: fullHistory) throws:
      next turn rawJson: ['']
      stored: {"tool_calls":[{"function":{"name":"search","arguments":""},"id":"a"}]}
      restore → ArgumentError: Replayed tool calls need declared names, unique IDs and JSON object arguments.
      
    • Fix: store '{}' when the arguments are blank, and accept null or blank arguments/parameters on replay. A cloud model's no-argument call in a genkit_hybrid history arrives as parameters: null.
  2. fullHistory no longer means what it means in core. Core's _fullHistory survives a session or model close, and trimming touches only the model-side history (chat.dart:973-999). Here:
    • Close wipes it (_close() clears _transcript):
      before close: 2 → after chat.close: 0 → after model.close: 0
      
      So after the new self-close, the documented recovery ("reload the model" plus clearHistory(replayHistory: oldChat.fullHistory)) has nothing to replay. The same happens after getActiveModel with changed parameters, or with a second createChat.
    • Trimming deletes old turns from it (_dropOldestTranscriptTurn, pinned that way at connector_test.dart:976-986). An app that renders or persists fullHistory loses those turns for good.
    • Fix: keep the transcript whole and across close, and trim only _history.
  3. A session queued behind the turn that self-closes the model gets an empty, successful stream. close() aborts the waiter, EngineQueue.run returns null, and _generate adds no error:
    model.isClosed=true  peer data=0 errors=[] done=true
    
    chat.generateChatResponse() returns TextResponse(''). Fix: when run returns null and the queue is invalid, add the StateError with its cause. More generally, tell "the user stopped" apart from "the model closed underneath".
  4. Hidden reasoning ends up in the persisted transcript. The toolCall entry is jsonEncode(assistant.toJson()), which carries reasoning_content whatever enableThinking says:
    enableThinking: false → {"role":"assistant","reasoning_content":"SECRET","tool_calls":[…]}
    
    That contradicts core's "hidden either way". It also ties every saved history to llamadart's wire format, which the core schema for Message.toolCall (my side) will have to migrate. Fix: emit a minimal {"tool_calls":[{"id","name","arguments"}]}; the replay parser already reads it.
  5. Web runtime skew.
    • Native runs llama.cpp v0.6.0-2. The web bridge is pinned to v0.1.54, whose manifest says llama_cpp_tag: v0.5.0.
    • llamadart 0.12.0's README pairs the SDK with bridge v0.1.59 "for Web/native parity".
    • Please bump the bridge, or say why it stays behind.
  6. website/content/docs/llama.md:127-129 still says the define is required and that builds fail without it. This contradicts lines 100-102 of the same page and llamadart 0.12.0's coexistence code; it should be defence in depth.

Before publish

  1. Self-close.
    • Its close() errors are swallowed (llama_inference_model.dart:35-37). Core's listener clears the cache before closeAndWait could print them, so a failed dispose is invisible while core may load a second model. Print it, as ModelCloseGate does.
    • The rethrow in _generate's outer finally replaces the body's error with the cleanup error, so the native message is lost (:656-680). advanced_usage.md:140 says it is kept.
    • Only LoRA cleanup invalidates. llamadart's own "context unusable after a llama.cpp exception" state leaves isClosed false, so core keeps handing out the dead model.
  2. History edges.
    • Restoring […, user] commits the trailing user turn. If the first generation then fails or is stopped, the next user message makes […, u1, u2], which Gemma and Mistral templates reject on every turn after that. Commit the restore up to the last assistant or tool message.
    • Results answered out of order lose their pairing once persisted: the transcript stores them in answer order, and replay pairs by name.
  3. iOS Inbox cleanup.
    • file_selector_ios opens the picker in .import mode, which copies into tmp/<bundle-id>-Inbox/.
    • removePickerInboxCopy only looks at Documents/Inbox, and the example declares no document types, so that directory never exists. The 2.5 GB copy stays.
    • The unit test builds Documents/Inbox by hand, so it can't see this. Check one pick on a simulator with find "$(xcrun simctl get_app_container booted <id> data)" -name '*.gguf'.
    • A rename from tmp/ into gguf_lab would also avoid the second copy.
  4. Android example.
    • abiFilters += listOf(...) adds to the set Flutter's plugin fills with armeabi-v7a, so a plain flutter build apk still ships a 32-bit slice with no llama libraries; abiFilters.clear() first. CI builds with --target-platform android-arm64, so it never sees this.
    • After a restart, core rehydrates the active model as a FileSource, so the NetworkSource guard never fires and each restart leaves the previous download on disk. uninstallModel already leaves fromFile installs alone, so the guard can go.
    • The URL field shows the internal file path after a restart.
    • http:// passes validation, closes the model, then fails on cleartext.
    • https://host with no path closes the model, then throws No element.
  5. iOS simulator lane. It hung twice in the recent runs, on d13422ac and 8524ca38: "Error waiting for a debug connection", 40 minutes each.
    • Give the flutter test subprocess a per-attempt timeout, reboot the simulator, and retry once. require_smoke_success still gates the passing attempt.
    • Stream the output; today verify.py buffers it until the process exits, so a hang shows nothing.
  6. CI and tooling.
    • concurrency shares one group for schedule, push and dispatch on main with cancel-in-progress, so a core push during the nightly cancels it.
    • verify.py:126 hardcodes 3.47.0 instead of reading .fvmrc.
    • validate_web_build.py passes a page that loads the bridge from a CDN, a Cloudflare ! Cross-Origin-Embedder-Policy detach line, and helper names that appear only in comments.
    • Add the package to tool/check_published_assets.dart, with the two shipped tools and example/web, so a .pubignore slip can't drop what the README tells consumers to copy.
  7. Smaller.
    • An unsatisfiable GPU request on web throws llama.LlamaUnsupportedException (from the SDK), while on native it throws the connector's UnsupportedError.
    • ParallelFunctionCallResponse.calls is a covariant List<LlamaFunctionCallResponse>; type it as <FunctionCallResponse>[…].
    • The [0.12.0, 0.12.1) pin makes every llamadart move a breaking connector release, because the companion version is enforced only at Apple build time. It also caps the workspace's hooks/code_assets at <3.0. Please write that policy into the package AGENTS.md.

On my side

  • A documented Message.toolCall schema in core, and an explicit contract for subclassing InferenceChat. LlamaInferenceChat is its first production subclass, and it relies on the inherited tool loop going only through the overridden members.
  • At merge: a flutter_edge_ai_llama row in the new root README, and the "coming soon" wording in models.md, getting-started.md and (at publish) the inference skill.
  • LICENSE, bundle IDs and pub.dev ownership, as before.

@leehack

leehack commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Connector-owned review fixes are pushed in d6147f83c.

  • Fixed durable history, tool persistence/pairing, and runtime recovery.
  • Updated the Web bridge, examples, docs and dependency policy.
  • Hardened CI retry/output handling and artifact validation.

All 22 checks pass. Added regressions reproduce the previous failures, including tool-ID reuse after trimming.

The iOS import filesystem regression passes; the picker dialog itself wasn’t automated. Shared core contracts, ownership decisions and remaining publication qualification are still outstanding.

Ready for re-review.

@leehack
leehack requested a review from DenisovAV October 14, 2026 16:54

@DenisovAV DenisovAV left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jhin. Round 3 is fixed in substance:

  • blank tool arguments;
  • the reasoning-free transcript;
  • the queued peer's error;
  • the primary error kept over cleanup;
  • the restored trailing user turn;
  • results stored in call order;
  • the bridge at v0.1.59;
  • the abiFilters clear();
  • the iOS lane timeout and retry;
  • the per-event concurrency;
  • .fvmrc;
  • the published-assets entry;
  • the pin policy.

Each fix comes with a test that fails on the old code. CI is 22/22.

I reran the full review over d6147f8. Every item below was reproduced, either on your _FakeEngine (a scratch test file, happy to share it), through llamadart's own ChatTemplateEngine and Glm45Handler, or by running validate_web_build.py.

Before merge

  1. An idle close() drops staged tool results. _close() clears _pendingTranscript without _commitAnsweredResults(), which _generate's finally does call:

    fullHistory: [text, toolCall, toolResponse] → model.close() → [text, toolCall]
    replay into a new model + addQuery → StateError: Answer outstanding tool calls…
    

    It happens on getActiveModel with new parameters, a second createChat, or a model close between the tool result and the next turn. The app may then run the tool again. Core keeps staged messages in _fullHistory.

  2. toolChoice: none refuses any history with tool calls. The model passes no tools for none, so replay can't validate the calls:

    replay [user, toolCall{name,parameters}, toolResponse, user]
    toolChoice auto → OK
    toolChoice none → ArgumentError: Replayed tool calls need declared names…
    

    A Genkit request with toolChoice: 'none' and an earlier tool turn fails this way. Please validate replay against the declared tools whatever toolChoice says, and enforce none only on generated calls (you already do at :614-619).

  3. The live prompt keeps answer order while the transcript is sorted. Parallel calls a, b answered b then a:

    request.tool messages → [b, a]
    fullHistory results   → [A, B]
    

    Templates that render results by position, with no id (Qwen's <tool_response>), show the model the wrong result per call. The live and the restored prompt also differ for the same history. Sorting _pending the same way before commit fixes both.

  4. Generated ids break Mistral templates. replay_N and llama_N fail the official Mistral-Nemo template, which bartowski's and lmstudio's GGUFs carry:

    LlamaInferenceException: The chat template failed to render:
    Tool call IDs should be alphanumeric strings with length 9!
    

    Every replay of id-less calls hits this, which includes every Genkit request with tool history. llamadart's Mistral grammar already uses ^[a-zA-Z0-9]{9}$. Deterministic 9-character alphanumeric ids would fit all templates.

  5. GLM-4.5, Laguna and Hunyuan-V3 lose tool arguments silently. SchemaToolDefinition passes parameters: const [] and overrides only toJsonSchema(). These handlers build the grammar from parameters, and parallelToolCalls: true always takes the Dart grammar path:

    get-u5f-weather-call ::= "get_weather\n"     (no argument rule, "city" absent)
    

    The model can only emit a call with no arguments; the app gets args: {} and no error. Please fill parameters from the top-level schema properties, or reject these formats.

  6. A dead worker leaves the model open. LlamaStateException('The llama.cpp worker exited unexpectedly…') matches neither substring at :738-745, so isClosed stays false. Core's cache then keeps handing out the dead model, and every turn fails. The same gap applies to sizeInTokens and capabilities in _makeSession. Classifying by state rather than message text (any LlamaStateException from the queue-owned action), or a typed signal from llamadart, would cover it.

  7. iOS Inbox (round-3 item 9) is still open on a device. _isPickerInboxCopy compares the Inbox's parent with getTemporaryDirectory(). On iOS that is NSCachesDirectory, i.e. Library/Caches (path_provider_foundation 2.6.0, getTemporaryPath), while the picker writes tmp/<bundle-id>-Inbox/. So on a phone the rename is skipped, a second full copy is made, and the tmp copy stays. Both tests build the Inbox under getTemporaryDirectory(), so they pass by construction. Directory.systemTemp (the container's tmp/ on iOS) is the right parent; a unit-test fake with temp = Library/Caches and the Inbox under tmp would catch it.

  8. Web.

    • A blob: projector, which the docs and the error text promise, always fails: ModelSource.url(blob:…) throws "Only http and https URLs are supported". ModelSource.path accepts it, as for the main model.
    • The context can shrink silently. llamadart's web loader retries at 2048/1024/768/512, and the provider stores getContextSize() as maxTokens:
      RuntimeConfig(maxTokens: 4096), runtime context 512 → model.maxTokens = 512, no error
      
      Please throw, or at least print, when it is smaller than requested. The example's "2,048 context tokens" status should read _model!.maxTokens.
    • example/web/index.html never sets window.__llamadartBridgeAdaptiveSafariGpu. On Safari, llamadart then forces CPU, or throws "these bridge assets run Safari on the CPU" for an explicit GPU request, although v0.1.59 supports the probe.
  9. Move to llamadart 0.12.2. It shipped today with your leehack/llamadart#1039, so its hook checks every llama.cpp archive against a pinned SHA-256 (#1015). Every native archive this workspace fetches is SHA-256-pinned, and with the package in workspace: our CI would otherwise load llama.cpp libraries nobody checked. Please replace '>=0.12.0 <0.12.1' with 0.12.2 and the Apple companion 0.0.22 with 0.0.23, which 0.12.2 pairs with. This also clears the "up-to-date dependencies" deduction on first publish.

Before publish

  1. Errors.
  • llamadart exceptions are part of the API but not exported:

    • native GPU without a device throws LlamaUnsupportedException, while web now throws UnsupportedError;
    • a corrupt GGUF throws LlamaModelFormatException, which Genkit maps to INTERNAL, so genkit_hybrid falls back to the cloud on every request;
    • a tool name a template can't express fails on the first turn.

    Mapping them at the boundary with the cause kept (Error.throwWithStackTrace), and rendering the template once in createChat, would settle it.

  • llama_engine_provider.dart:198-201: a failing dispose() replaces the load or projector error, the pattern item 7 fixed in the session.

  • With enableThinking: false, dropped reasoning bypasses core's one-time release notice. The budget error then says "disable thinking" when it is already disabled.

  1. Web validator.
    • It passes a bootstrap that imports the bridge from a CDN first and falls back to the local copy. llamadart's own chat_app uses exactly that pattern.
    • It passes a _headers file that repeats COOP in a second rule, which Cloudflare joins into same-origin, same-origin, so browsers treat the page as not isolated.
    • It rejects valid setups: COEP credentialless, report-to, a static import, a relative import('./webgpu_bridge/…'), globalThis.crossOriginIsolated.
  2. Android.
    • The consumer setup doesn't say to drop armeabi-v7a. llamadart emits nothing for arm, so a default app bundle installs on 32-bit phones and fails after the model download.
    • abiFilters plus --split-per-abi is an AGP conflict.
    • http://127.0.0.1 passes validation, but Android's cleartext policy blocks it, after the model was already closed.
    • https://host/models/ passes validation and fails in core (pathSegments.last is empty).
    • The APK gate checks only that some "llama" file exists. It does not check the NEEDED closure, a libggml-cpu*.so, or 16 KB alignment.
    • minSdk 24 is unqualified; libggml-vulkan.so needs API 28.
    • The arm64 runtime path never runs in CI. The x86_64 emulator has one libggml-cpu.so, phones choose among seven variants. I can run one arm64 device lane on our DDP phones if you like.
  3. Apple.
    • leehack/llamadart-native#110 is closed, and companion 0.0.23 (native v0.6.0-3) carries the fix, so item 9 picks it up. The README still says pending #110.
    • In the workspace-member case, the companion is never detected from the root: please write "always", not "can".
    • simctl shutdown with check=True aborts the retry when the simulator already died.
    • A passing retry isn't flagged, so an intermittent launch crash ends green.
  4. Desktop.
    • The first Windows x64 build downloads the 737 MB archive (675 MB of it cublasLt64_12.dll) even for CPU-only, with a 10-minute total timeout and no resume. Please document it.
  5. Docs.
    • website/content/docs/models.md and getting-started.md still say the engine is "coming soon", and models.md has no .gguf row.
    • llama.md:120-122 lists fewer unqualified platforms than platforms.md:79-84.
    • The README points at verify.py and fetch_test_model.py, which .pubignore excludes.
    • The root pubspec.yaml comment still says "must".
    • debugPrint at session:772 and model:39: the other engines use edgeAiLog.
    • The PR body still says CI is running and has no dated qualification records, which platforms.md and development.md point to.
  6. Smaller.
    • _commitAnsweredResults() runs in _generate's outer finally before done.complete(); a throw there would hang every waiter.
    • The "closed during generation" branch has no test.
    • Replay rejects a reused id across answered turns (llamadart itself emits call_0 per turn).
    • LlamaToolResponseMessage keeps callId out of ==/copyWith.
    • EngineQueue.invalidationCause is a public mutable field.
    • lastFinishReason/lastTurnCommitted are unused.
    • The web demo never removes the previous download.
    • The example's cache_api.js is a second unchecked copy of core's.
    • The Flutter 3.44 floor is never resolved in CI.
    • There is no publish_to: none while the README says "Unreleased".

On my side

  • InferenceChat as an extension point: a sanctioned seam, or a core test that pins the override set. LlamaInferenceChat is its first production subclass.
  • Tool-call ids and one engine-independent transcript shape in core, including whether Message.thinking belongs in fullHistory.
  • One stop/interrupt rule. Core keeps the user turn and a partial reply; this connector rolls both back, which matters for voice barge-in.
  • The LoRA seam (RuntimeConfig.loraPath or artifactPaths for inference, so the provider can drop FlutterEdgeAiPlugin.instance), and a companion slot for the projector.
  • Our own docs give an abiFilters recipe that does nothing (installation.md:371,381, troubleshooting.md:86). I'll fix that.
  • LICENSE, bundle IDs and pub.dev ownership, as before.

@leehack

leehack commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Connector-owned fixes are pushed in 69924b15f and e3d631ebf, covering history/tool replay, runtime recovery, schema preflight, iOS imports, and platform validation/docs. Updated to llamadart 0.12.2 and Apple companion 0.0.23.

22 checks pass. The advisory beta failure is from existing codelab deprecations; stable passes. Dated qualification results are in the PR body.

Your offered ARM64 device lane would help close the remaining phone qualification gap. The separate SDK schema follow-up doesn’t block this PR.

@DenisovAV DenisovAV left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jhin. I checked round 4 against e3d631e. 15 of your 17 round4 tests fail on d6147f8, as they should. "closed during generation reports failure and releases waiters" passes there too, and the Web one is skipped on the VM. Everything from round 4 is fixed except the README lines of item 13.

Two changes I asked for had side effects I didn't foresee: the XML tool grammars (from item 5) and createChat waiting for a running turn (from item 10). My round-4 note on load errors was also wrong. All three are inline, and I ran each one on both commits. A smaller schema check is inline too.

Phone run. I ran your connector_smoke_test.dart, unchanged, on a DDP Galaxy S24 (SM-S921U, Snapdragon 8 Gen 3, arm64, Android 14). It used the CPU with the default thread count and SmolLM2-135M Q8_0 from your fixture pin, and it passed. All three cycles of load, chat, recall, trimming, cancel and retry took 6.6 s. The APK carried the seven libggml-cpu-android_armv*.so variants. The only change to your example was an instrumentation runner, so DDP could drive it. This was a one-off run, not a CI lane. Vulkan and the oldest supported Android version are still unqualified.

Core 2.4.0. After your push I merged #666 into main. Core 2.4.0 gives Message the fields toolCalls and toolCallId, and gives FunctionCallResponse an id. The connector no longer compiles against main, because LlamaToolResponseMessage.copyWith is no longer a valid override of Message.copyWith. That break is on my side. The connector can now use the core types instead of its own:

  • Return FunctionCallResponse(id: …) instead of LlamaFunctionCallResponse.
  • Pair results by message.toolCallId. The inherited tool loop already sends Message.toolResponse(toolCallId: call.id), so LlamaToolResponseMessage and _RecordedToolResult can go.
  • Read replayed calls with toolCallsOf from engine.dart. It returns a message's toolCalls when it has them and otherwise parses the text, so histories recorded by other engines or by Genkit replay too. Its arguments are frozen, so take a copy.
  • Record calls in fullHistory with Message.toolCall(calls: …), and results with their toolCallId.
  • Alias every supplied id that isn't nine alphanumeric characters. Your generated ids now fit Mistral-Nemo, which closes item 4 as I described it. But with #666, Genkit passes each call's ref as its id, so a genkit_hybrid history with cloud ids (call_…, toolu_…) would reach the Mistral template, which rejects them. Today a supplied id is kept unless it collides (llama_inference_session.dart:258). Results already map through _replayAliases.
  • Raise the floor to flutter_edge_ai: ^2.4.0. minimum-sdk fails until 2.4.0 is on pub.dev.

I did this migration locally on top of your branch to check it. With it, your VM, Chrome and example suites are green. I can send it as a patch if that helps.

return SchemaToolDefinition._(
tool,
schema,
_properties(schema) ?? const [],

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

XML tool grammars lose argument names when one tool is not typable (from my item 5). llamadart builds the XML param-name rule from the union of every tool's parameters (xml_tool_call_format.dart:206-220), and an empty union becomes identifier. This line now fills parameters for typable tools and leaves [] for the rest. In a mixed set, the untyped tool's names therefore drop out, and the grammar forbids them. "Not typable" here means a type list, anyOf/oneOf, $ref, no type, and so on. Nullable fields from Pydantic or zod .nullable() are the common case.

Take get_weather {city: string} and book_table {date: {"type": ["string", "null"]}}: Qwen3CoderXmlHandler().buildGrammar(...) gives param-name ::= "city" (d6147f8 gave identifier). I also ran it on Qwen3.5-0.8B Q4_K_M, which is detected as qwen3CoderXml, on the CPU with toolChoice: required and the prompt "Book a table for 2026-10-20.". The model writes <parameter=city>New York … London … Paris … under book_table until the token limit. With date: string it returns book_table({date: 2026-10-20}). MiniMax-M2, MiniCPM5, Seed-OSS, Apriel 1.5, Xiaomi MiMo and Nemotron-3 use the same builder.

validateTools already refuses GLM-4.5, Laguna and Hunyuan-V3 when a tool requiresFullSchema. So giving every tool parameters: const [] when any one of them is not typable keeps item 5 fixed and restores d6147f8's grammar.

The same tool set failed on d6147f8 too, for a llamadart reason. The model wrote the right call (<tool_call><function=book_table><parameter=date>2026-10-20</parameter>…), and it came back as text. schemaResolvesToString (tool_schema_utils.dart:67-68) treats only type: "string" or an enum as a string. A ["string", "null"] value is JSON-decoded instead, and the unquoted 2026-10-20 fails, which turns the whole call into text. When the schema allows a string, falling back to the raw text would fix it.

if (identical(_session, next)) _session = null;
},
);
await _queue.run(() async {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A replacement chat now waits for the running turn (from my item 10). The template preflight I asked for runs inside _queue.run, before the legacy session is closed. The queue is held by the running generation, so createChat() waits for it to finish instead of stopping it, even with no tools. I probed it over _FakeEngine by calling model.createChat(), without tools, while a chat was generating. On d6147f8 it returned in 3 ms and cancelled the turn. On e3d631e it was still waiting after 3 s, and nothing was cancelled. model.close() awaits _lifecycle first, so a close issued while such a createChat is pending waits for the whole answer too.

The preflight doesn't need the queue. chatTemplate(includeTokenCount: false) renders in Dart over metadata that the running turn has already cached (engine.dart:1884-1899, chat_template_renderer.dart:65-114), and it does not touch the context. Running next.validateTools() outside _queue.run, and skipping it when there are no tools, keeps item 10 without the wait. The supportsToolCalling check can go: it is always true on llama.cpp, and the provider refuses every other runtime at load.

try {
engine = await (_loader ?? _loadGgufEngine)(location, params);
} catch (error, stack) {
Error.throwWithStackTrace(runtimeError(error), stack);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My round-4 note on load errors was wrong. I wrote that a corrupt GGUF throws LlamaModelFormatException. That type only covers a header that contradicts the declared format or extension (model_format_probe.dart). A corrupt file and a load that runs out of memory both reach this line as the same LlamaModelException('Failed to load model from …') (engine.dart:741-757).

Mapping that type to RuntimeStateError does what I asked for a corrupt file. But it also stops genkit_hybrid from falling back to the cloud when a phone lacks memory: Genkit turns the StateError into FAILED_PRECONDITION, which genkit_hybrid treats as permanent. LiteRT-LM throws a plain Exception in both cases, so it falls back. Since llamadart can't tell the two apart, I'd rather match LiteRT-LM:

  • leave load-time LlamaModelException unmapped;
  • keep LlamaModelFormatException → ArgumentError and LlamaUnsupportedException → UnsupportedError.

Sorry for the detour.

final required = schema['required'] ?? const <String>[];
if (required is! List ||
required.any((name) => name is! String || !raw.containsKey(name))) {
throw ArgumentError('Schema required must name declared properties.');

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: valid JSON Schemas are refused on every format. A required key that is missing from properties throws here, and a boolean subschema ("properties": {"x": true}) throws at line 137. d6147f8 accepted both. Generated schemas rarely use either, but Genkit and MCP pass a schema through as written. No template path needs the throw: GLM-4.5, Laguna and Hunyuan-V3 are refused through requiresFullSchema, and the other formats read the full schema. Returning null (untypable) here, and keeping the throws for structurally invalid schemas (properties not an object, required not a list of strings), would cover it.

});

@override
LlamaToolResponseMessage copyWith({

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This override no longer compiles against main. Core 2.4.0 adds toolCalls and toolCallId to Message.copyWith. See the review body.

The LiteRT-LM macOS CocoaPods recipe disables SwiftPM and conflicts with this
companion recipe; that combined setup is not qualified.
App Store submission is **unvalidated** while the native framework slice metadata
is tracked in [llamadart-native #110](https://github.com/leehack/llamadart-native/issues/110).

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 4, item 13. This line still says App Store submission is tracked in llamadart-native#110, while doc/platforms.md says companion 0.0.23 carries the fix. The next line still says "can select", where doc/platforms.md says the companion is always missed.

@leehack

leehack commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the connector comments in dcfa406d2: core 2.4 tool messages/ID aliases, replacement-chat cancellation, mixed XML parameter names, schema checks, load-error preservation and Apple README wording. Updated llamadart and its Apple companion to 0.13.0.

Local contracts, all 18 workspace suites, six regression controls, macOS/iOS CPU lifecycle, browser/Wasm inference and docs pass. 20 CI checks pass. Two hosted checks await core 2.4.0 publication; the advisory beta failure is unchanged. No override or gate bypass was added. XML nullable-string decoding remains a separate SDK issue.

Thanks for the Galaxy S24 run—the dated result is recorded in the PR body, separately from current-pair qualification.

@leehack

leehack commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Updated to llamadart 0.13.1; 20 checks pass. Two hosted checks remain blocked because core 2.4.0 isn’t on pub.dev yet.

Could you publish core 2.4.0 and rerun contracts and Resolve Flutter 3.44 floor? The third failure is the existing advisory beta codelab deprecations.

@DenisovAV DenisovAV left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Jhin. Core 2.4.0 is on pub.dev now. I re-ran contracts and Resolve Flutter 3.44 floor on 711afd2, and both pass, so every check except the advisory beta job is green.

711afd2 changes no connector code, so what I checked on dcfa406 still applies:

  • The probes behind each comment pass. A mixed XML tool set builds param-name ::= identifier, and a typed-only set keeps its names. The two schemas are accepted. A failed load surfaces as LlamaModelException. createChat() during a turn returns in 3 ms and cancels it.
  • On Qwen3.5-0.8B (qwen3CoderXml, CPU), the mixed set now lets the model write <parameter=date>. As you noted, the call still comes back as text because of llamadart's nullable-string parsing. Typed sets return book_table({date: 2026-10-20}).
  • The three tests from my local migration pass against your code unchanged.
  • Your connector_smoke_test.dart passes with llamadart 0.13.0 on the DDP Galaxy S24: three cycles in 6.9 s. I have not re-run it on 0.13.1. That release changes the offline hook digest, Apple workspaces and Web cancel, and the Android run touches none of them.

@DenisovAV
DenisovAV merged commit 52d16e7 into DenisovAV:main Oct 16, 2026
34 of 37 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