Skip to content

feat(local-llm): Add support for local LLM engine integration - #762

Merged
haiphucnguyen merged 11 commits into
mainfrom
feature/support-local-llama
Oct 12, 2026
Merged

haiphucnguyen merged 11 commits into
mainfrom
feature/support-local-llama

Conversation

@haiphucnguyen

Copy link
Copy Markdown
Collaborator

Summary

  • Added support for local llama.cpp engine integration
  • Updated internationalization files with new strings for local LLM settings
  • Modified Main.kt to handle application exit logic
  • Created new settings section for local LLM in SettingsView.kt
  • Enhanced FooterBar.kt to display local LLM engine status
  • Configured AppConfig.kt for local LLM engine persistence
  • Updated TokenAwareSummarizingMemory.kt to handle duplicate retry messages
  • Modified ChatRequestTransformers.kt to trim request body
  • Added several new files for local LLM management
  • Updated OpenAiCompatibleModelFactory.kt to support local LLM
  • Enhanced OpenAiCompatibleTemplate.kt with local LLM template
  • Improved RAGIntentClassifier.kt to handle parsing errors
  • Expanded AskimoHome.kt with directories for local LLM
  • Refactored HttpUtils.kt for better request configuration

Related Issue(s)

Type of Change

  • 🐛 Bug fix
  • ✨ New feature
  • 💥 Breaking change
  • 📝 Documentation
  • ♻️ Refactor (no functional change)
  • 🧪 Tests
  • 🔧 Chore / tooling / CI

What Changed & Why

How to Test

./gradlew test

Screenshots / Recordings (if applicable)

Checklist

  • I have read the CONTRIBUTING guide
  • My branch is up to date with main
  • I ran ./gradlew spotlessApply and ./gradlew detekt locally
  • I ran ./gradlew test and all tests pass
  • I added/updated tests for my changes (if applicable)
  • I added/updated documentation (if applicable)
  • My commits are signed off (DCO) — git commit -s
  • This PR is focused on a single feature/fix

Additional Notes

- Added support for local llama.cpp engine integration
- Updated internationalization files with new strings for local LLM settings
- Modified Main.kt to handle application exit logic
- Created new settings section for local LLM in SettingsView.kt
- Enhanced FooterBar.kt to display local LLM engine status
- Configured AppConfig.kt for local LLM engine persistence
- Updated TokenAwareSummarizingMemory.kt to handle duplicate retry messages
- Modified ChatRequestTransformers.kt to trim request body
- Added several new files for local LLM management
- Updated OpenAiCompatibleModelFactory.kt to support local LLM
- Enhanced OpenAiCompatibleTemplate.kt with local LLM template
- Improved RAGIntentClassifier.kt to handle parsing errors
- Expanded AskimoHome.kt with directories for local LLM
- Refactored HttpUtils.kt for better request configuration
Copilot AI balanced review requested due to automatic review settings October 12, 2026 16:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Local proxy security, process cleanup, dynamic model discovery, concurrency, platform detection, and unfinished translations require correction.

24 open findings

And 4 more that still need to be addressed.

What changed in this PR

Adds built-in llama.cpp support for downloading, configuring, running, and monitoring local GGUF models.

Changes:

  • Adds local model discovery, downloads, process management, and OpenAI-compatible proxying.
  • Adds desktop settings, status controls, persistence, and shutdown handling.
  • Updates request handling, memory retries, RAG parsing, and localization.
File Description
shared-jvm/​.../​HttpUtils.kt Consolidates HTTP request handling.
shared-jvm/​.../​AskimoHome.kt Adds local engine/model directories.
shared-jvm/​.../​RAGIntentClassifier.kt Tolerates non-exact classifier output.
shared-jvm/​.../​OpenAiCompatibleTemplate.kt Adds the local LLM template.
shared-jvm/​.../​OpenAiCompatibleModelFactory.kt Resolves the live local proxy URL.
shared-jvm/​.../​LlamaServerProcessManager.kt Manages proxy and llama-server processes.
shared-jvm/​.../​LlamaServerDownloader.kt Downloads and extracts engine binaries.
shared-jvm/​.../​LlamaServerCatalog.kt Defines supported platform assets.
shared-jvm/​.../​LlamaModelDownloader.kt Downloads GGUF model files.
shared-jvm/​.../​LlamaModelCatalog.kt Defines curated local models.
shared-jvm/​.../​LlamaDownloadManager.kt Tracks app-scoped downloads.
shared-jvm/​.../​HuggingFaceGgufBrowser.kt Searches Hugging Face for GGUF models.
shared-jvm/​.../​ChatRequestTransformers.kt Normalizes deduplication text.
shared-jvm/​.../​TokenAwareSummarizingMemory.kt Deduplicates retry messages.
shared-jvm/​.../​AppConfig.kt Persists local engine configuration.
desktop/​.../​FooterBar.kt Adds local engine status controls.
desktop/​.../​SettingsView.kt Adds the Local LLM settings section.
desktop/​.../​LocalLlmSettingsSection.kt Implements engine and model management UI.
desktop/​.../​Main.kt Unifies application exit handling.
messages.properties Adds English local LLM strings.
messages_zh_TW.properties Adds Traditional Chinese strings.
messages_zh_CN.properties Adds Simplified Chinese strings.
messages_vi_VN.properties Adds Vietnamese strings.
messages_pt_BR.properties Adds Portuguese strings.
messages_ko_KR.properties Adds Korean strings.
messages_ja_JP.properties Adds Japanese strings.
messages_fr.properties Adds French strings.
messages_es.properties Adds Spanish strings.
messages_de.properties Adds German strings.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Process lifecycle races, unsafe extraction behavior, platform detection, and model-discovery defects can leave orphan processes or make downloaded models unusable.

12 open findings
14 resolved since last review
Previously missed (1)

In code that hasn't changed since last review

Medium severity Sharded GGUF files are treated as standalone models

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​HuggingFaceGgufBrowser.kt:76

Hugging Face commonly exposes sharded GGUFs such as model-00001-of-00004.gguf. Each shard is currently presented as an independent model and the downloader fetches only that one file, so llama-server cannot load it because the remaining shards are absent. Either group/download all shards or exclude shard filenames from these standalone results.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Platform detection, model discovery, download integrity, and process lifecycle contain unresolved correctness and concurrency issues.

10 open findings
2 resolved since last review
Previously missed (4)

In code that hasn't changed since last review

Medium severity Deleting an active model does not stop its server process

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:991

Deleting a model directly can target the file currently opened by a llama-server child. On Windows this commonly throws due to the file lock (the click handler does not catch it); on Unix the process keeps serving an unlinked model while the UI reports it deleted. Unload the matching resident slot and await process termination before deleting, and surface deletion errors.

Medium severity Retry deduplication drops legitimate duplicate user messages

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​memory/​TokenAwareSummarizingMemory.kt:309

This cannot distinguish an automatic retry from a legitimate second add of the same user message. After any failed/cancelled request leaves its user message last in memory, manually sending the same text again is silently dropped from memory and persistence. Retry deduplication needs an explicit retry signal or rollback in sendStreamingMessageWithCallback, rather than changing the semantics of every ChatMemory.add.

Medium severity Missing fallback when atomic move is unsupported

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaModelDownloader.kt:106

ATOMIC_MOVE is optional and throws AtomicMoveNotSupportedException on unsupported filesystems, turning an otherwise successful multi-GB download into a failure. The existing Whisper downloader already falls back to a normal replace move; apply the same fallback here.

Medium severity CLI shutdown does not clean up the shared server manager

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaServerProcessManager.kt:267

Starting this shared HttpServer creates a long-lived server thread, but cleanup was wired only into the desktop Main. The CLI can also use the shared local-LLM model factory; after doing so it has no call to LlamaServerProcessManager.shutdown(), so the CLI can hang on exit and any child process may remain alive. Register manager-owned JVM shutdown cleanup or add lifecycle integration for every application entry point.

This issue also appears on line 293 of the same file.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Model discovery, platform detection, concurrent state updates, and process lifecycle handling contain blocking correctness and reliability issues.

11 open findings
Previously missed (5)

In code that hasn't changed since last review

Medium severity Catalog model restore ignores persisted embedding role

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:225

For catalog models this ignores the persisted lastSelectedModelIsEmbedding and restores the catalog's default role instead. Because the same page says role is determined by the provider field, a catalog chat model previously used for embeddings is incorrectly warmed in the chat slot without --embedding (and vice versa), wasting memory and starting the wrong mode. Preserve catalog metadata but override isEmbedding with the persisted actual slot.

Medium severity Downloaded search models disappear from management UI

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:845

After a search result disappears from searchResults (including after an app restart), its downloaded GGUF is no longer shown anywhere on this management page because displayedEntries only combines the static catalog and current search. Users then cannot see or delete dynamically downloaded models without manually editing the folder. Include valid on-disk non-catalog files, or persist downloaded search metadata and merge it here.

Medium severity CLI shutdown leaves proxy and child processes running

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaServerProcessManager.kt:217

The manager is in shared JVM code and local OpenAI-compatible instances are usable by the CLI, but only desktop Main.kt calls shutdown(). A CLI request starts this proxy and potentially a child process, while ChatCli's shutdown hook only closes analytics, so non-interactive commands can hang on server threads or leave llama-server orphaned. Register manager cleanup in every application entry point.

Medium severity Launch does not enforce ubatchSize limit

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaServerProcessManager.kt:607

ubatchSize is passed through unchanged even though the new configuration contract says it must be <= batchSize. The UI permits lowering batch size below the current micro-batch size, and hand-edited config can do the same, causing llama-server startup to reject the arguments. Enforce the invariant at launch as a final validation boundary.

Medium severity Failed downloads leave response bodies unclosed

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​util/​StreamingDownloader.kt:86

The response body is an InputStream, but the non-2xx branch throws without closing it. Failed downloads can therefore retain the HTTP connection and its resources until GC. Close the body before raising the status error.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Platform selection, download integrity, archive validation, configuration invariants, and lifecycle behavior have unresolved correctness and security issues.

4 open findings
13 resolved since last review
Previously missed (4)

In code that hasn't changed since last review

Medium severity Settings display stale values after configuration changes

desktop-shared/​src/​main/​kotlin/​io/​askimo/​ui/​common/​theme/​AppComponents.kt:1303

Local LLM callers pass values read directly from AppConfig, which is not Compose-observable. After this callback persists a new option, closing the menu only recomposes this component with its old value parameter, so the field continues displaying the previous selection until a broader recomposition/navigation. Keep a local displayed value (as settingsBooleanField does) and update it before invoking the callback.

Medium severity Downloaded model files are not validated after moving

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaModelDownloader.kt:115

The download is marked successful immediately after the move without running the existing validationError(entry) check. A complete HTTP 200 error body or otherwise wrong-sized response therefore becomes the final .gguf, and the UI reports it as downloaded until the first inference fails. Validate after the move and delete the final file before surfacing a download error.

Medium severity Truncated tar archives are accepted as valid

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaServerDownloader.kt:296

A well-formed gzip stream whose tar payload ends before the next full header is accepted as successful here. If the executable was already extracted, the later existence check passes and the truncated archive is marked installed. Treat any short header as corruption; valid tarballs reach the zero-block branch instead.

Medium severity Cancellation is incorrectly converted to download failure

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​util/​StreamingDownloader.kt:109

ensureActive() throws CancellationException, but this broad catch wraps it in DownloadException. That converts normal coroutine cancellation into an operational failure and can trigger error UI/logging instead of cancellation propagation. Delete the partial file, then rethrow cancellation unchanged.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Streaming downloads can hang indefinitely, and several configuration and download edge cases remain broken.

1 open finding
4 resolved since last review
Previously missed (4)

In code that hasn't changed since last review

Medium severity Unescaped apostrophes break MessageFormat placeholders

desktop-shared/​src/​main/​resources/​i18n/​messages_fr.properties:590

This string is formatted with a port argument, but MessageFormat treats the apostrophes in d'exécution and l'instant as quoting delimiters, so {0} is emitted literally and the apostrophes disappear. Escape both apostrophes by doubling them.

Medium severity Unknown content length shows misleading 0% progress

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:779

When Content-Length is absent, totalBytes is -1, but this renders an empty 0% determinate bar and reports downloaded / 0 MB. That incorrectly looks stalled even while bytes are arriving. Use an indeterminate indicator and an unknown-total progress message for this branch.

Medium severity Repository file paths are not URI-encoded

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​HuggingFaceGgufBrowser.kt:111

Hugging Face permits spaces and reserved URI characters in repository file paths. Concatenating rfilename verbatim makes URI(url) fail for names containing spaces and changes the target for characters such as #, so valid search results cannot be downloaded. Percent-encode each path segment before constructing the resolve URL.

Medium severity Partial download files survive early failure paths

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​util/​StreamingDownloader.kt:92

These failure paths occur before the cleanup try, so an existing multi-GB .part/.download file from a prior interrupted run survives a connection error or non-2xx retry, contrary to this method's cleanup contract. Delete destPath on both paths without allowing cleanup failure to mask the download error.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Local model lifecycle, filesystem naming, extraction, configuration validation, and deduplication have unresolved correctness issues.

1 open finding
1 resolved since last review
Previously missed (4)

In code that hasn't changed since last review

Medium severity Restore persisted model settings during application startup

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:200

This restoration effect only executes when the Local LLM settings section is composed. After an application restart, the persisted model is therefore not reloaded until the user opens this page, contrary to the startup/warm-up behavior described here and in LocalLlmConfig. Move restoration into application startup/lifecycle code so it runs independently of navigation.

Medium severity Persist or reload discovered downloaded models

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:569

searchResults is transient Compose state, so after leaving this page or restarting, downloaded models discovered through Hugging Face disappear from this management list. They remain on disk and in /models, but the app no longer offers their delete control unless the user happens to reproduce the search. Merge persisted/on-disk non-catalog GGUF files into this list or persist the discovered model metadata.

Medium severity Use safe unique local names for remote model files

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​HuggingFaceGgufBrowser.kt:103

The remote leaf name is used verbatim as a local path component. Hugging Face paths may contain reserved characters (the code below explicitly handles ?, #, etc. in the URL), but characters such as ?, *, or : make this destination invalid on Windows. Using only the leaf also collides for two files in different repo subdirectories with the same name. Derive a bounded, filesystem-safe name from the full repo ID and remote path instead.

Medium severity Clear installation directory before extracting releases

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​providers/​llama/​LlamaServerDownloader.kt:185

Extraction writes a new release over the existing platform directory. This is especially problematic on Windows, where all releases share the same directory and executable path: files removed or renamed by the new release remain behind and can be loaded alongside the new executable. Clear and recreate the destination after checksum verification so each installation contains only the verified archive's files.

🧠 Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Path containment, cancellation handling, launch-parameter validation, and installation-state issues remain unresolved.

2 open findings
1 resolved since last review
Previously missed (3)

In code that hasn't changed since last review

Medium severity Unblock cancelled downloads by closing the read stream

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​util/​StreamingDownloader.kt:117

This completion handler cannot unblock cancellation: a normal invokeOnCompletion handler runs only when the coroutine completes, but completion is waiting for this blocking read to return. A cancelled multi-GB download can therefore remain stuck until the 1–4 hour inactivity timeout, and the resulting IOException is then wrapped as DownloadException. Use a cancellation-time hook/bridge that closes the stream as soon as the job enters cancellation, and re-check cancellation before wrapping read failures.

Low severity Show indeterminate progress for unknown download sizes

desktop/​src/​main/​kotlin/​io/​askimo/​desktop/​settings/​LocalLlmSettingsSection.kt:779

The downloader explicitly supports unknown content length (totalBytes == -1), but this renders a determinate 0% bar and “downloaded / 0 MB” for the entire transfer. Use an indeterminate progress indicator and an unknown-total status string in that branch so users can tell the download is active.

Low severity Handle expected watchdog thread interruption

shared-jvm/​src/​main/​kotlin/​io/​askimo/​core/​util/​StreamingDownloader.kt:126

finally interrupts this thread during Thread.sleep, but the lambda does not catch InterruptedException. Consequently every normal download teardown can emit an uncaught watchdog stack trace. Treat interruption as the expected shutdown path.

🧠 Review effort: Balanced


class DownloadException(message: String, cause: Throwable? = null) : Exception(message, cause)

fun modelPath(entry: LlamaModelEntry): Path = AskimoHome.llamaModelsDir().resolve(entry.fileName)
// destDir isn't keyed by release tag, and on Windows executableName has no
// version-specific subpath at all — extracting over an old install would leave files
// the new release removed/renamed behind. Clear it now that the archive is verified.
prepareCleanDestDir(destDir)
@haiphucnguyen
haiphucnguyen merged commit 6acf3b1 into main Oct 12, 2026
11 of 12 checks passed
@haiphucnguyen
haiphucnguyen deleted the feature/support-local-llama branch October 12, 2026 22:20
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