Repository navigation
feat(chat-history): server-side chat history with tombstones (follow-up to #9902) - #12663
Conversation
Persist WebUI chat conversations server-side so browser refresh, private windows, or device changes preserve user history (issue mudler#9432). This commit adds the on-disk representation: - Conversation holds id, name, model, opaque history, MCP / sampling settings, and timestamps. - ConversationsFile is the per-user list serialised to JSON. History is stored as json.RawMessage so the server stays agnostic to React message shapes (user / assistant / thinking / tool_call / tool_result mixed with text / image_url / audio_url / file attachments). Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
…#9432) File-backed persister for chat history. Each user's conversations live under {baseDir}/{userID}/conversations.json (anonymous/ when auth is disabled). Design choices: - In-memory cache backed by sync.Mutex so concurrent saves don't interleave writes. - Atomic write via tmp file + os.Rename so a crash mid-save never leaves a corrupted history. - ID validation regex blocks path-traversal payloads at the store boundary, in addition to the auth context constraint. Tests cover round-trip persistence across instances, user isolation, unsafe-ID rejection, bulk replace migration, and the anonymous fallback path. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
Wire the chathistory store into the HTTP layer. New endpoints under /api/conversations: - GET /api/conversations list - POST /api/conversations upsert (id in body) - DELETE /api/conversations delete all - PUT /api/conversations/bulk replace entire set (localStorage migration) - GET /api/conversations/:id fetch one - PUT /api/conversations/:id upsert (id in path; path id wins over body) - DELETE /api/conversations/:id delete one All endpoints scope queries to the authenticated user via getUserID(c) - callers cannot impersonate other users by passing a user_id in the body. The endpoints are gated behind the new chat_history feature permission (default ON in APIFeatures), registered through the existing RouteFeatureRegistry so the unified feature middleware picks them up automatically. Application.ChatHistoryStore() returns nil when DisableWebUI is set or no persistence path is configured, in which case route registration is skipped entirely rather than registering handlers that always 503. Also adds the chat-history instruction entry and Swagger tag so the endpoint surfaces in /api/instructions and /swagger. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
mudler#9432) useChat now probes /api/conversations on mount. When the endpoint responds 200, the server becomes the authoritative source: the hook merges remote conversations into local state and pushes per-chat PUT updates on each debounced save. When the endpoint 404s - older LocalAI deploys or the feature disabled - the hook silently keeps the old localStorage-only behaviour, so the change is backward-compatible. Migration: when the server is reachable but empty and the browser has local conversations with history, the hook fires a single PUT /api/conversations/bulk to seed the server. The atomic bulk endpoint avoids partial-upload states where a retry would skip already-uploaded entries. Delete operations propagate to the server when it's available; failures are silently swallowed so the local UI stays responsive on transient network errors. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
The initial test file used the stdlib testing package (t.Fatalf / t.Errorf), which is forbidden by the forbidigo linter rule in .golangci.yml — LocalAI mandates Ginkgo/Gomega for all Go tests (see .agents/coding-style.md). Restructured the same six scenarios into Describe / Context / It blocks, with a chathistory_suite_test.go bootstrap that registers the Ginkgo fail handler. Test coverage is unchanged: basic CRUD round-trip, cross- instance persistence, user isolation, unsafe ID rejection (now via DescribeTable), bulk replace overwrite, and the anonymous fallback path. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
Addresses mudler's review on mudler#9902. Chat history was the only per-user state in LocalAI sitting in a separate filesystem store instead of the shared GORM database — AgentStore and JobStore both live there. Move it onto Application.authDB so per-user state stays in one place. * ConversationRecord (GORM model) with composite primary key (user_id, conv_id) — React mints IDs locally with no global coordination so per-user uniqueness is the natural shape. * Store.New(db *gorm.DB) replaces Store.New(baseDir string). Save / Get / List / Delete / DeleteAll / ReplaceAll keep their signatures so HTTP handlers and the React UI are untouched. * ReplaceAll runs in a transaction with an Unscoped() pre-clear so a future retention sweep cannot resurrect a stale ID on re-upload. * gorm.DeletedAt in the schema means a future retention pruner is a one-line query — addresses the second half of the review (unbounded in-memory map). The map is gone: reads go straight to the DB. Trade-off worth flagging in the PR reply: chat history persistence now requires auth.Enabled = true (that's what initialises Application.authDB). With auth disabled the React UI transparently falls back to localStorage, the same path the original PR took on 404. Consistent with AgentStore / JobStore; if a "chat history always on" mode is preferred we can pull DB init out of auth.InitDB into a shared helper. Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash] Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
ConversationsFile was the JSON wrapper for the old file-based chat
history store — a {Conversations: [...], UpdatedAt: ...} pair
serialised to disk under {baseDir}/{userID}/conversations.json. The
previous commit replaced that store with a GORM-backed one that
writes rows directly as ConversationRecord, leaving the envelope
without a consumer.
Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash]
Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
Mirror the AgentStore test setup: spin up a PostgreSQL 16 container via testutil.SetupTestDB(), construct a Store on top of it, exercise CRUD round-trips. The previous file-based fixtures (TempDir, filepath.Join checks) are no longer meaningful now that the store talks GORM. Tests are skipped on macOS (testcontainers needs Docker) and run on CI, same as the other GORM-backed suites in the repo. Also reframed two cases: * "unsafe IDs" → "malformed IDs" — the DB-backed store doesn't care about path traversal, but idRegex still rejects whitespace / control characters so IDs stay safe in logs and HTTP responses. * "anonymous user" no longer pins a directory path (no directory exists anymore); instead it checks the round-trip plus the per-user isolation guarantee. Added a DeleteAll round-trip to cover the bulk-clear endpoint. Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash] Signed-off-by: TLoE419 <tloemizuchizu@gmail.com>
The seven /api/conversations handlers had no tests. Inject the *chathistory.Store into the handlers instead of the whole Application and move the route table into RegisterChatHistoryRoutes, so a spec can drive the real registration and middleware chain (auth.Middleware plus the chat_history feature gate) against an in-memory SQLite auth database. The new specs cover 401 without credentials on every route, 403 when an admin revoked chat_history, the CRUD round trip, path id over body id, 400 on malformed ids and bodies, per-user isolation, bulk replace and delete-all, and that a nil store registers nothing (the UI then falls back to localStorage). The handlers' nil-store branches are gone: the routes are only registered with a store, so those branches could never run. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
A conversation deleted on one device came back as soon as a client with a stale copy wrote it again: Delete soft-deleted the row, and the next Save went through GORM's upsert, which cleared deleted_at and resurrected it for every device. The lookup that recovered CreatedAt also ran outside any transaction, so concurrent writers raced on it. The server is now authoritative over deletions: * Delete turns the row into a tombstone: content dropped, deleted_at set. It is idempotent, and deleting an id the server has not seen yet still records a tombstone, so a delete that overtakes the UI's in-flight debounced save of the same chat still wins. * Save runs in a transaction, refuses a tombstoned id with ErrDeleted (HTTP 410 Gone), and bumps the version with a single UPDATE ... SET version = version + 1 guarded by deleted_at IS NULL, so concurrent writers each count and a delete committed between the lookup and the write still wins. Two concurrent first writes of the same id retry once (ON CONFLICT DO NOTHING, then update). * Every row carries a server-assigned version (1 on the first save, +1 per write including the delete), returned to the client. A non-zero version tells the UI the server has seen a conversation, which is how it can tell a never-synced draft from a server-side deletion. * GET /api/conversations returns the tombstones under "deleted". * DeleteAll and ReplaceAll leave tombstones too. ReplaceAll no longer hard-deletes everything first; it upserts the payload, skips ids that were deleted (reported in "skipped"), and tombstones the rest. * createdAt/updatedAt are stored as the client sends them (only zero values are stamped), so clients compare updatedAt from their own clocks rather than against the server's. The store specs now run against PostgreSQL (testcontainers) and, with the auth tag, SQLite through auth.InitDB, since both back the auth database. The API specs cover a stale client reconnecting after a remote deletion. Swagger is regenerated with swag v1.16.6 (json.RawMessage fields get swaggertype), and the feature is documented, including that it needs user auth. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
mergeRemoteAndLocal kept every chat that was only in the browser and let the server copy win for every shared id. A stale browser therefore uploaded chats deleted on another device as if they were new drafts, and a message sent while the list request was still in flight was replaced by the older server copy and then lost from localStorage too. The first load now reconciles with the server's tombstones and versions: * a chat the server lists under "deleted" is dropped locally; * a chat on both sides keeps the copy with the newer updatedAt, so an edit made during the load wins and is uploaded afterwards; * a chat only in the browser is uploaded only if it was never synced (no version). With a version the server has seen it and no longer has it, so it is dropped instead of resurrected (this also keeps one account's cached chats out of another account on a shared browser); * deletes made while the list is loading are queued and sent once it arrives. Saves record the version the server returns, and a 410 on save drops the chat locally instead of retrying it forever. Chats received from the server count as already sent, so adopting a server copy no longer echoes it straight back. The bulk localStorage migration is gone: it replaced the whole server set from a possibly stale browser, and the per-chat saves already upload never-synced drafts through the tombstone check. The Playwright spec drives each case against a stubbed /api/conversations that follows the server contract. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
master's createNewChat sets localaiAssistant, but serializeChat did not send it and schema.Conversation had no field for it, so a chat with the Assistant mode on came back with it off after a reload from the server (and the local cache dropped it too). Add the field on both sides. The other fields createNewChat sets were already covered; a handler spec now round-trips all of them, and the UI spec checks the toggle on the way up and in the local cache. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
localai-org-maint-bot
left a comment
There was a problem hiding this comment.
Changes requested on 2cfca0c383680e2fe3a48dfcffe31af85ea058cf. The server tombstones address the earlier successful-delete resurrection case, but two client paths still need correction:
-
[P1] Associate the local cache and unsynced drafts with the authenticated account.
useChat.jsstill reads/writes the shared browser chat key, andreconcileWithServerkeeps every unversioned local conversation missing from the server. Logout does not clear or partition that key. If account A has an unsynced conversation (for example a failed first save), signs out, and account B signs in, B's empty list retains A's conversation and the save effect uploads A's private history into B's account. The version check only protects already-synced rows. Partition the cache/pending operations by account and make legacy anonymous-cache migration explicit; add a two-account regression covering an unsuccessful first save. -
[P2] Preserve failed deletions until the server acknowledges them.
useChat.js:371-402removes conversations locally and swallows DELETE failures.pendingDeletesRefis populated only while the initial probe is pending, and is not persisted. After a successful probe, disconnect the network and delete a synced conversation: it disappears from the UI, no pending deletion remains, and reopening Chat after reconnect adds the unchanged server copy back. The same problem affects delete-all and failures while flushing pending deletes. Persist deletion intent and retry it, or visibly restore/report a failed delete instead of silently treating it as complete.
I reproduced both paths with a Node harness executing the PR's actual reconciliation and delete callback: the failed delete left zero pending operations and the next reconciliation restored the row; an unversioned previous-account conversation survived reconciliation against an empty new account. This was a focused logic check, not the full browser/Go suite.
These affect privacy and the deletion contract, so they require coordinated state/sync changes rather than a minor review cleanup. The auth-only default remains a separate maintainer decision as described in the PR.
Two gaps in the client half of server-side chat history, both found in review: The browser cache was one shared localStorage key. A draft that one account could not upload (a failed first save) stayed in it, and after that account signed out and another signed in, the reconcile kept the unversioned draft and the save pass uploaded it into the second account. The cache now lives under localai_chats_data:<user id>, Chat remounts its state when the account changes, and nothing is synced without a signed-in account. The shared key is left for browser-only use without auth and is not uploaded when signed in, because nothing tells which account it belongs to. Deletes were dropped locally and their DELETE errors swallowed; only deletes made while the first list was loading were queued, and not persisted. A delete made while the server was unreachable therefore came back with the next list. Deletes (single, delete all, and deletes on the Home page) are now kept as pending deletes in the account's cache until the server confirms them, override the server list in the reconcile, and are sent again on the next change, on the online event and on the next load. While a delete-all is pending no conversation is uploaded, so a chat started after it is not caught by it. The Playwright specs replay both review scenarios (account switch after a failed first save; delete and delete-all while offline) with counter-checks that the same account keeps and uploads its own draft and that a confirmed delete is neither re-sent nor resurrected. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
|
Thanks, both reproduced and fixed in ef0ae8f. P1 (cache bound to the account): the browser cache now lives under P2 (deletes until confirmed): single deletes, delete-all and deletes from the Home page are kept as pending deletes in the account's cache until the server confirms them. They override the server list in the reconcile and are re-sent on the next change, on
Open question: chats stored under the shared key before chat history was enabled are not adopted by a signed-in account. Is that the behaviour you want, or would you prefer an explicit import path? |
|
@mudler Incremental source-review sign-off at I found and fixed one remaining clear-all race: navigating away before the 500 ms cache debounce left an old unsynced draft on disk, allowing it to be uploaded after the deletion was acknowledged. Clear-all now persists the cleared list and deletion intent together. Added a Playwright regression and documentation. An isolated Node harness executing the actual PR functions reproduced the failure before the fix and passed afterward; JS syntax and whitespace checks also pass. I did not run the browser suite. No further confirmed source blocker in this incremental review. The branch still conflicts with master |
Navigation cancels the debounced cache write and can restore unsynced chats after Clear all. Save the cleared list with its pending deletion before returning, and cover immediate navigation in the browser spec. Assisted-by: Codex:GPT-6 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
Conflicts with 48f358d: - core/application/application.go: keep chatHistoryStore next to the new WebSocket ticket fields. - api_instructions_test.go: both sides added an instruction (chat-history, motion); the list has 23 entries now. - useChat.js: keep the account-scoped cache and server sync. The chat setting reasoningEffort added upstream (mudler#12700, mudler#12716) is now part of the synced chat, and the browser cache keeps converting the old reasoningOff flag. Docs-Not-Needed: conflict resolution only; the synced chat is opaque JSON and the documentation lists no chat fields. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
- "clear all persists before navigation" opened a single chat, and the menu offers no Clear all for one chat, so the spec timed out in every run. It now opens two unsynced chats and checks that neither survives. Reverting 03cd9c1's save in clearAllChats turns it red again. - "a delete the server confirmed is not sent again" reopened the page as soon as the server had the request, before the page had the answer; the unconfirmed delete was then rightly sent again (4 of 5 runs). It now waits until the cache holds no pending delete. Docs-Not-Needed: test-only change. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
03cd9c1 to
a5b50c1
Compare
|
Thanks for the review and the clear-all fix. Merged master
Running the browser suite locally turned up two problems in
Full UI e2e suite: 1772 passed, 4 skipped; Go: The question from my last comment is still open: should chats stored under the shared key before chat history was enabled be adopted by the first account that signs in, or stay unadopted as now? |
mudler-agent
left a comment
There was a problem hiding this comment.
One remaining persistence issue on this head: the server drops the conversation's reasoning-effort setting. Please preserve it and add a round-trip regression before merging.
Validation: a focused SQLite reproduction using unchanged copies of this head's schema and store confirmed the loss under the race detector. Focused Node checks for account-scoped caches and persisted deletion intent passed. The repository-level Go race tests and vet could not start because generated protobuf packages were absent; full browser tests were not run. These results do not establish full CI coverage.
| LocalAIAssistant bool `json:"localaiAssistant,omitempty"` | ||
| Temperature *float64 `json:"temperature,omitempty"` | ||
| TopP *float64 `json:"topP,omitempty"` | ||
| TopK *float64 `json:"topK,omitempty"` |
There was a problem hiding this comment.
[P2] Preserve reasoningEffort in the server-side conversation schema. serializeChat in core/http/react-ui/src/hooks/useChat.js sends this property, but Conversation does not declare it. JSON binding therefore discards it before persistence, so loading a synced conversation loses the selected reasoning behavior.
I reproduced this with an actual schema/store round-trip: decode a conversation containing "reasoningEffort":"none", call Store.Save, then Store.Get and JSON-encode the result. The response omits reasoningEffort. The focused SQLite reproduction passed under the race detector.
Please add the field, regenerate the Swagger artifacts, and add a regression asserting that a non-empty reasoning-effort setting survives save/get/list.
reasoningEffort (mudler#12700, mudler#12716) is part of the chat the UI syncs since the master merge, but schema.Conversation had no field for it, so the server dropped it and a reload from the server reset the setting. Add the field. The handler spec that round-trips every chat field now includes reasoningEffort. A schema test reads serializeChat in useChat.js and fails for any key the UI sends that schema.Conversation cannot hold, so the next such drift shows up as a failing test rather than in review (it reports reasoningEffort on the previous head). Swagger and docs updated. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de>
|
Right — my merge claimed
|
mudler-agent
left a comment
There was a problem hiding this comment.
The reasoningEffort persistence fix in 5f42128 resolves my original finding. I verified the UI/schema guard goes red with the previous schema, and the updated authenticated HTTP/SQLite history tests pass under the race detector.
One test-only blocker remains: core/schema/chat_conversation_ui_test.go uses t.Fatalf (twice), t.Fatal, and t.Errorf. These four new calls fail the repository forbidigo rule. Reproduced with Go 1.26.8 and golangci-lint against the PR diff.
Please keep the guard but convert it to the existing schema package Ginkgo/Gomega style: Describe/It, Expect(err).NotTo(HaveOccurred()), Expect(body).NotTo(BeNil()), a >= 10 key-count assertion, and HaveKey for the reflected JSON fields. I tested that conversion: the missing-field case still fails, the restored schema passes with -race, and changed-package lint reports 0 issues. No production change is needed.
CI is queued; this review does not claim a full CI or PostgreSQL pass.
The new drift guard uses testing methods forbidden by repository lint. Keep its field coverage and fail-fast parser checks in Ginkgo/Gomega. Assisted-by: nib:gpt-6.1-sol
mudler-agent
left a comment
There was a problem hiding this comment.
The reasoningEffort persistence fix and the follow-up Ginkgo conversion resolve my findings. The conversion is pushed as 6781979; it preserves the drift guard, fails with the missing field, and passes schema race tests and changed-package lint with Go 1.26.8. Authenticated HTTP and SQLite history tests also passed under the race detector. Approval is source/local-test review, not a substitute for required CI. PostgreSQL coverage was not available locally. The bot follow-up intentionally leaves human DCO certification to the contributor, per repository policy.
Follow-up to #9902 by @TLoE419, continuing on top of their branch with the maintainer's agreement. The eight commits from #9902 are kept unchanged in authorship and rebased onto current
master; four commits on top address the open review points.Closes #9432.
What
Server-side persistence of the web UI chat conversations, per user, in the auth database (SQLite by default, PostgreSQL when configured). The Chat page syncs to
/api/conversationsand keepslocalStorageas a cache.Why the extra commits
The review on #9902 found that the server could not be authoritative across devices: a conversation deleted on device A came back when a stale device B reconnected, a message sent while the first list request was in flight could be lost, and
Saveafter a soft delete resurrected the row. This PR fixes those with a small, explicit design and adds the missing docs, swagger and tests.Design: tombstones and versions
Server (authoritative over deletions)
DELETEturns the row into a tombstone: content dropped,deleted_atset, row kept. It is idempotent, and deleting an id the server has never seen still records a tombstone. That matters because the UI deletes immediately while a debouncedPUTof the same chat may still be in flight; whichever request lands second, the delete wins.410 Goneand writes nothing.GET /api/conversations/{id}returns410for a deleted conversation,404for one that never existed.GET /api/conversationsreturns{"conversations": [...], "deleted": [{"id", "version", "deletedAt"}]}.version: 1 on the first save, +1 on every write including the delete. It is returned on every save and in the list, and ignored on input.Saveruns in a transaction. The version bump is a singleUPDATE ... SET version = version + 1withdeleted_at IS NULLin theWHEREclause, so concurrent writers each count and a delete that commits between the lookup and the write still wins. Two concurrent first writes of the same id useON CONFLICT DO NOTHINGand retry once into the update path. This also removes the read-modify-write race the review flagged inSave.DeleteAllandPUT /bulkleave tombstones too.ReplaceAllno longer hard-deletes first: it upserts the payload, skips ids that were deleted (returned asskipped), and tombstones the user's other live conversations, so a replacement also reaches other devices as a deletion.createdAtandupdatedAtare stored as the client sends them; only zero values are stamped. The UI comparesupdatedAtacross copies, so the server's clock must not replace the client's.Client (
useChat.js)mergeRemoteAndLocalis replaced by a reconcile step that can tell a never-synced draft from a server-side deletion:deletedupdatedAtwins (local keeps the server's version and is uploaded)versionversionversionis kept in thelocalStoragecache, which is how the next load knows a chat was synced.410on save drops the chat locally instead of retrying it forever.PUT /bulkfor the localStorage migration. It replaced the whole server set from a possibly stale browser; the per-chat saves already upload never-synced drafts, and each goes through the tombstone check. The endpoint stays for API clients.Not in scope: concurrent edits of the same live conversation on two devices are last-writer-wins at conversation granularity, as in #9902. The
versionis exposed, so conditional writes (If-Match-style, 409 on a stale base version) could be added later without a schema change. I left them out because they need a client-side conflict UI.Review points and how each was addressed
core/http/routes/chat_history_auth_test.go) and UI specs "a stale client drops a chat deleted on another device instead of uploading it again" and "a synced chat the server no longer has is dropped, not resurrected" (core/http/react-ui/e2e/chat-history-sync.spec.js).updatedAtinstead of letting the server always win, and the server now stores the client'supdatedAt. UI spec "a message sent while the list is loading survives the older server copy" holds the list request open, sends a message, then releases the list. The opposite direction is covered by "a newer copy from the server replaces the older local one".Saverefuses a tombstoned id withErrDeleted→410 Gone, inside a transaction. That is neither a 500 nor a silent resurrection. Store specs "rejects a save after delete instead of resurrecting the row", "records a delete that arrives before the conversation's first save", and theReplaceAll/DeleteAllvariants.docs/content/features/chat-history.md(permission, tombstone semantics, sync behaviour, API table, example), a pointer fromfeatures/chat.md, and achat-historyrow in the instructions table offeatures/api-discovery.md. The/api/instructions/chat-historyintro now describes the tombstone contract, andapi_instructions_test.golistschat-history. Swagger was regenerated withswag init -g core/http/app.go --output swagger(swag v1.16.6, the version ingo.mod); the diff is limited to the chat-history paths andschema.Conversation*definitions.json.RawMessagefields carryswaggertype:"array,object"because swag cannot resolve the type otherwise.useChatPlaywright spec, and the store suite runs on both PostgreSQL and SQLite (see below). To make the handlers testable they now take the*chathistory.Store, and the route table moved intoroutes.RegisterChatHistoryRoutes, whichRegisterLocalAIRoutescalls. The specs drive that function with the realauth.Middlewareand thechat_historyfeature gate.serializeChatsendslocalaiAssistant, andschema.Conversationhas the field. Since May, master'screateNewChatadded onlylocalaiAssistant(mcpResourceswas already covered). A handler spec round-trips every per-chat setting the UI stores, and a UI spec checks the toggle on upload and in the local cache.LOCALAI_AUTH=true(or with legacy API keys only, or with the web UI disabled) the endpoints are not registered, and the UI keeps usinglocalStorage.Also from the earlier review: API surface checklist items are unchanged from #9902 (swagger tags,
instructionDefs,RouteFeatureRegistry,FeatureChatHistoryinAPIFeatures+APIFeatureMetas()). No MCP admin tool: these are per-user endpoints, notRequireAdmin, so.agents/localai-assistant-mcp.mddoes not apply.Behaviour changes compared to #9902
DELETE /api/conversations/{id}is idempotent:200for an unknown or already deleted id (it was404). Reason: the in-flight save race above.GETof a deleted conversation is410(it was404).PUT /bulktombstones instead of hard-deleting, skips deleted ids, and returnsskipped.countis the number stored.createdAt/updatedAt(previouslyupdatedAtwas overwritten with server time).Rebase notes
The branch was 1129 commits behind. Conflicts and their resolutions:
core/http/auth/features.go,permissions.go: master addedFeatureDecisionsin the same spots. I kept both.api_instructions_test.go: master's count was 21, so withchat-historyit is now 22.core/application/application.go: master now usescmpandpath/filepath(router corpus), which TLoE419's GORM refactor commit removed as unused. The imports are restored inside that commit, so every commit still builds.Tests run
Go, with the tags the coverage gate uses (
debug auth):core/services/chathistory(PostgreSQL via testcontainers + SQLite viaauth.InitDB)core/http/routes(incl. 22 chat history endpoint specs)core/http/endpoints/localaicore/http/authcore/schemagolangci-lint run --new-from-merge-base=upstream/master(v2.11.4, the CI version) on the touched packages, with and without--build-tags auth: 0 issues.UI (Playwright against
tests/e2e-ui/ui-test-serverwith the rebuilt bundle):Each fix was also checked to fail without it:
saveInTxput back to feat: persist chat conversations server-side (#9432) #9902's write path (no tombstone check, plaingorm.Saveupsert), 14 store specs fail (7 per dialect: the tombstone and version specs), and 4 API specs fail (the whole "stale client reconnecting after a remote deletion" context).useChat.js, all 6 sync specs that existed at that point fail. For "a newer copy from the server replaces the older local one" the red comes from the echo assertion, because the old code re-uploads the adopted server copy.field "localaiAssistant" was droppedand the UI spec withReceived: undefined.The UI spec stubs
/api/conversationswith a small fake that follows the server contract (tombstones in the list, 410 for deleted ids, versions). The UI test server runs with auth disabled, where the real endpoints are not registered. The server side of the contract is covered by the Go specs above.Open question for the maintainer
Chat history is a no-op when auth is disabled, which is LocalAI's default. The store needs
Application.authDB, and that database only exists withLOCALAI_AUTH=true. #9902 made this trade-off deliberately (consistent withAgentStore/JobStore). This PR does not change it; it only documents it. Options if you want it on by default:"". The store already partitions on it, but every browser on that server would then share one history;Which way should it go?
A smaller follow-up I'd also suggest: tombstones are tiny (id, version, timestamp) but are never pruned. If you want a bound, a retention sweep on
deleted_atis a one-line query. The trade-off: a client offline for longer than the retention period could then re-upload a chat it had synced before. Even then the client drops it rather than resurrecting it, because it carries a version the server no longer has.Checklist
docs/content/features/chat-history.md,chat.md,api-discovery.md)useChatsync)Assisted-by:trailers🤖 Generated with Claude Code