Skip to content

Studio: persist chat history in backend storage - #5272

Merged
danielhanchen merged 68 commits into
unslothai:mainfrom
Imagineer99:move-chat-history-to-studio-db
May 22, 2026
Merged

danielhanchen merged 68 commits into
unslothai:mainfrom
Imagineer99:move-chat-history-to-studio-db

Conversation

@Imagineer99

@Imagineer99 Imagineer99 commented May 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves chat history persistence from browser IndexedDB/Dexie to the backend studio.db.

New chat threads and messages are now written through backend chat-history APIs backed by SQLite. Dexie remains available as a read-only legacy fallback so existing local chat history is still visible and can be continued without data loss.

Changes

  • Add chat_threads and chat_messages tables to studio.db
  • Add authenticated /api/chat/* endpoints for thread/message CRUD, export, count, and clear
  • Update chat runtime autosave/history adapters to write to backend storage
  • Keep Dexie as a legacy read fallback for old chat threads/messages
  • Materialize legacy Dexie threads into backend storage when users continue them
  • Update sidebar, search, export, clear, and delete flows to prefer backend data

Draft PR, requires manual testing and further iteration

@Imagineer99 Imagineer99 changed the title feat: Persist chat history in backend storage Studio: Persist chat history in backend storage May 4, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request transitions the chat history storage from a local-only Dexie database to a backend SQLite database. It introduces new FastAPI routes for managing chat threads and messages, updates the frontend to synchronize with the backend while maintaining a legacy fallback for existing local data, and refactors the assistant-ui runtime provider to use the new backend storage adapter. Feedback focuses on improving error handling by avoiding broad exception catches in the database synchronization logic and optimizing performance when clearing chat history by batching operations.

Comment thread studio/backend/storage/studio_db.py Resolved
@Imagineer99 Imagineer99 changed the title Studio: Persist chat history in backend storage Studio: persist chat history in backend storage May 7, 2026
@wasimysaid
wasimysaid marked this pull request as ready for review May 18, 2026 02:02

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f7a36e46d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 234906e542

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d110cb4f07

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Validated this PR empirically on a 3-GPU host (B200 x 3, isolated UNSLOTH_STUDIO_HOME per probe). Recording the findings in case they help close out the remaining items.

Setup

Three independent installs:

  • A at merge-base bad5ff4 (pre-PR baseline). Real chats seeded via the OLD Studio UI on unsloth/Llama-3.2-1B-Instruct-GGUF Q4_K_M, raw Dexie dumped via browser_evaluate.
  • B at PR head 8c05957. Real chats seeded via the NEW Studio UI on the same model.
  • C at PR head 8c05957 with mock legacy Dexie injected via browser_evaluate before first sidebar mount (3 threads each carrying the A -> B -> {C, D-E, F} regen tree with parentId set per record), then reload to fire importLegacyChatsIfNeeded.

Driven by test_unsloth_studio.py against @playwright/[email protected] --browser chromium --isolated. Cross-browser coverage flagged at the bottom.

Q1: does old Dexie data migrate cleanly?

Yes for the current code path. Branch fidelity holds in practice. One real gap on the sentinel.

C: mock-Dexie -> reload -> studio.db state

chat_threads:                  3 rows (legacy-t1, legacy-t2, legacy-t3)
chat_messages per thread:      8 rows
chat_messages WHERE thread_id='legacy-t1' AND parent_id='legacy-t1-msgB':  3
chat_messages WHERE thread_id='legacy-t2' AND parent_id='legacy-t2-msgB':  3
chat_messages WHERE thread_id='legacy-t3' AND parent_id='legacy-t3-msgB':  3

Branch switcher rendered "1/3 -> 2/3 -> 3/3" per thread, both navigation directions, zero JS console errors. UPSERT-by-id keying in syncChatMessages(... pruneMissing:false) preserved parent_id verbatim. After deleting localStorage['unsloth_chat_legacy_imported_to_studio_db'] and reloading, migration re-ran against the populated studio.db: still exactly 3 threads (not 6), sentinel reset to "true", idempotent.

A: pre-PR Studio Dexie ground truth

Pre-PR Studio writes parentId for sibling branches. Seeded 3 threads with the A -> B -> {C, D-E, F} pattern; raw Dexie dump showed 3 messages per thread sharing the same parentId at position B:

thread __LOCALID_5aSzkNe: 3 messages with parentId="Xbwp1zq"
thread __LOCALID_FHvEOds: 3 messages with parentId="KRklpw7"
thread __LOCALID_77iznKx: 3 messages with parentId="A2e2AGT"

So the structural data the migration depends on is actually present in real users' Dexie. The normalizeLegacyMessages linear-chain fallback (chat-history-storage.ts:120-132) only fires for legacy rows that lack parentId, which the byte-identical-base-vs-head MessageRecord type shows has not been the case for a while.

Cross-browser

PR head has zero browser-specific handling (grep on userAgent, Safari, Firefox, navigator, indexedDB in the chat dir: no hits). The migration depends only on plain IndexedDB + localStorage:

  • Chrome / Edge / Chromium / Firefox: same code path; no platform differences.
  • Safari: ITP does not affect first-party IndexedDB, but Safari private mode silently fails localStorage writes. The sentinel never persists, so migration re-runs on every page load. Idempotent so no data harm, just heavier first-paint each session.

Local probe is pinned to chromium. The Edge/Firefox/WebKit conclusion is inferred from code absence of browser branches plus standards compliance. If you want a real cross-OS x browser matrix I can spin one up on danielhanchen/unsloth-staging-2 with runs-on: {ubuntu-latest, macos-14, windows-latest} plus Playwright --browser msedge/firefox/webkit, using the CUDA spoof in tests/_zoo_aggressive_cuda_spoof.py for GPU-less runners.

Q2: does the new DB break old features?

No core persistence regression in B. Test thread __LOCALID_A7vvZON:

12 messages, distinct parent_ids:
  parent_id='fHjfTqN' -> 3 sibling assistant rows (the regen branches)
  ... linear chain of follow-ups under each sibling

PR head correctly stores regen branches natively in chat_messages.parent_id. The single global id PK and (thread_id, parent_id) tree shape works end-to-end against assistant-ui's MessageRepository. Page refresh recovery is mathematically guaranteed by server-side SQLite once the row is written.

For the still-open items from the 71f5aa56 review and the codex bot, the empirical run did not surface anything new to add.

Two side notes worth flagging separately:

  1. First-message-empty-assistant. On a freshly-created thread, the Search and Code tool buttons are auto-enabled. The first user message produces a 200 OK from /v1/chat/completions but the stored assistant content_json is []. Reproduces on both pre-PR (A) and PR head (B). Not introduced by this PR.

  2. studio/setup.sh:319-330 hidden-gitignore race. Two concurrent bash install.sh --local against PR head failed for one because setup.sh walks up the dir tree, moves any .gitignore containing only * to .gitignore._twbuild, restores via trap EXIT. Two parallel installs from sibling workspaces both target the same ancestor .gitignore and one restore fails with mv: cannot stat. CI does not hit this because it installs one at a time, but it bites parallel provisioning. Fixes either way: scope the walk to ancestors inside $_REPO_ROOT only, or use an exclusive flock around the hide+restore block.

The "never delete Dexie unless the user clears browser history" proposal

Most of this is already true in the current PR. The only gap is the boolean localStorage sentinel.

What the PR already gets right:

  • importLegacyChatsIfNeeded (chat-history-storage.ts:246) never deletes Dexie rows. Dexie sits on disk until the browser itself nukes it.
  • Conflict resolution is already "new DB wins" for shared ids: chat_messages.id UPSERT, with pruneMissing:false so Dexie-only messages insert.
  • Tombstones (utils/chat-thread-tombstones.ts, 90-day GC, 5000 cap) prevent resurrection of explicitly-deleted threads.

What the PR is missing:

  • The boolean localStorage['unsloth_chat_legacy_imported_to_studio_db'] makes import non-recoverable. C reproduces the failure mode flagged in your earlier comment: if the sentinel is set on a studio.db rebuild (or any state where Dexie data hasn't been imported into the current backend), Dexie data is silently hidden from the sidebar even though db.threads/messages still exist. The deep-link path via getStoredChatThread(id) keeps working but new sessions never see those threads in the list.

Concrete fix that matches the proposed policy:

  1. Server-side import ledger in studio.db:
    CREATE TABLE IF NOT EXISTS chat_import_ledger (
        legacy_thread_id   TEXT NOT NULL,
        legacy_message_id  TEXT NOT NULL,
        imported_at        INTEGER NOT NULL,
        PRIMARY KEY (legacy_thread_id, legacy_message_id)
    );
    
  2. Replace the boolean isLegacyChatImportDone() with an idempotent per-launch import. On each importLegacyChatsIfNeeded call, diff the Dexie row set against the ledger and skip already-imported (thread, message) pairs in O(1).
  3. Drop db.messages.clear() / db.threads.clear() from clearStoredChats (chat-history-storage.ts:567-570). Backend wipe is sufficient; tombstones suppress Dexie-only rows from reappearing; preserving IndexedDB keeps the safety net for users who later wipe studio.db.
  4. Keep unsloth_chat_legacy_imported_to_studio_db as a fast-path hint only. localStorage failures degrade to extra ledger queries, never to silent data loss.

That gets us to: never delete Dexie unless the user explicitly clears browser storage, merge to studio.db on every launch, new DB wins on id conflicts, Dexie-only rows insert when no backend conflict.

Happy to land any of (1)-(4) on this branch or as a follow-up PR, whichever you prefer.

@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to the previous comment: stood up the cross-browser matrix I sketched at the bottom of that comment. PR danielhanchen#138 on danielhanchen/unsloth-staging-2 is green on all 6 jobs:

OS Browser Result
ubuntu-latest chromium pass
ubuntu-latest firefox pass
macos-14 chromium pass
macos-14 webkit pass
windows-latest chromium pass
windows-latest msedge pass

Run: https://github.com/danielhanchen/unsloth-staging-2/actions/runs/26266969056

So Q1 cross-browser (Chrome / Edge / Safari / Firefox) is now backed by real headless runs, not just static evidence. importLegacyChatsIfNeeded migrates injected legacy Dexie data into studio.db correctly and preserves the regen-branch fan-out on every browser Playwright supports across all three OSes.

Setup, no GPU: install.sh --local --no-torch (Linux/Mac) / install.ps1 --local --no-torch (Windows) + UNSLOTH_API_ONLY=1 unsloth studio so no llama.cpp prebuilt is pulled and no chat model is loaded. Migration runs purely on Dexie -> SQLite copy semantics.

Two cross-browser test-rig notes worth flagging upstream:

  1. The UI /change-password and /login forms are non-trivial to drive headlessly: Firefox silently dropped the submit click and WebKit lost the TCP connection on first goto. Worked around in the test by rotating the bootstrap password via /api/auth/login + /api/auth/change-password from the workflow and pre-injecting the access + refresh tokens into localStorage via context.add_init_script. Not a PR-5272 bug but worth knowing for anyone else writing Studio Playwright tests.

  2. Playwright + webkit on macos-14 arm64 has a flaky pipe-driver crash out of pipeTransport.js ("Unexpected end of JSON input") that happens before the first goto. Pinning playwright==1.55.0 + a 3-attempt workflow-level retry gets us reliably green. Worth tracking upstream at microsoft/playwright if it persists.

The test itself plus the workflow are at https://github.com/danielhanchen/unsloth-staging-2/pull/138/files . Easy to lift into unslothai/unsloth as tests/studio/playwright_pr5272_migration.py + .github/workflows/pr5272-cross-browser.yml if you want it gating merges.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fbbd3a0c01

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

wasimysaid and others added 3 commits May 22, 2026 06:12
The boolean localStorage sentinel
(unsloth_chat_legacy_imported_to_studio_db) made importLegacyChatsIfNeeded
non-recoverable: deleting studio.db while the browser keeps the flag
silently hides every legacy Dexie thread from the sidebar (verified by
the 3-GPU validation probe; matches the third review comment on PR
unslothai#5272). Same trap fires for browser-profile sync to a fresh machine
and any other path that wipes studio.db while keeping IndexedDB.

Source of truth moves into studio.db itself via a new
chat_legacy_import_log table keyed by legacy thread id. The ledger
disappears together with studio.db, so the next launch re-runs the
import from whatever Dexie still holds. localStorage stays as a
per-session perf hint only.

Performance, all bounded by the three new fast-paths before any
backend work:

  A) localStorage hint says "imported earlier in this session" -- 0
     network, ~0 ms. Covers the warm sidebar mount.

  B) indexedDB.databases() reports no "unsloth-chat" DB -- 0 network,
     ~1 ms. Covers every new user who never had the old browser-only
     Studio (the common case after launch).

  C) db.threads.count() + db.messages.count() are both 0 -- 0 network,
     ~5 ms. Covers returning users who migrated long ago and Dexie was
     never repopulated.

Only when all three miss does the code talk to the backend
(GET /api/chat/import-ledger -> diff vs Dexie -> existing import path
-> POST /api/chat/import-ledger to record what was just imported).
Per-thread tracking is enough because Dexie is read-only after this
PR; a thread's message set does not grow.

Backend deployments that predate the import-ledger routes are
handled transparently: the client treats 404/405 as an empty ledger
and re-runs the (idempotent via UPSERT) import on next launch.

Changes:
- storage/studio_db.py: new chat_legacy_import_log table (WITHOUT
  ROWID, PK on legacy_thread_id) + list_chat_legacy_import_log() +
  record_chat_legacy_import_log() (idempotent batch UPSERT).
- routes/chat_history.py: GET + POST /api/chat/import-ledger with the
  obvious request/response models.
- frontend api/chat-api.ts: listChatImportLedger() (returns a Set for
  O(1) diff) + recordChatImportLedger(), both with 404/405 fallback.
- frontend utils/chat-history-storage.ts: importLegacyChatsIfNeeded
  gains three fast-paths, ledger fetch on the slow path, and writes
  the ledger after a successful import. The localStorage helper is
  unchanged on the surface; it just stops being authoritative.
- tests: 5 new test_legacy_import_log_* cases (empty default, record
  + list round-trip, idempotency, input dedup, empty/null ignore).
  All 9 pre-existing tests still pass.
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 4cbad62e to this branch with the server-side import ledger from the proposal at #5272 (comment) (item 3 of the design block). What landed:

Schema

CREATE TABLE IF NOT EXISTS chat_legacy_import_log (
    legacy_thread_id TEXT NOT NULL PRIMARY KEY,
    imported_at      INTEGER NOT NULL
) WITHOUT ROWID

Per-thread is sufficient because Dexie is read-only after this PR -- a thread's message set does not grow once migrated. Saves ~50x the row count vs per-message tracking.

Routes

GET /api/chat/import-ledger -> {threadIds: string[]}.
POST /api/chat/import-ledger body {threadIds: string[]} -> {recorded: N} (idempotent UPSERT).

Frontend rewrite

importLegacyChatsIfNeeded now has three fast-paths before any backend work:

A. isLegacyChatImportDone() localStorage hint says "imported earlier this session" -> 0 network, ~0 ms.

B. indexedDB.databases() reports no "unsloth-chat" DB -> 0 network, ~1 ms. Covers every new user who never had the old browser-only Studio -- the common case after this PR ships.

C. db.threads.count() + db.messages.count() === 0 -> 0 network, ~5 ms (O(1) index-header read). Covers returning users who migrated long ago.

Slow path only runs when all three miss: parallel fetch of (Dexie threads, backend threads, ledger), walk Dexie skipping ledger hits, import the rest with the existing sync semantics, then POST the new ids back to the ledger.

recordChatImportLedger returning 404/405 is treated as "older backend"; the client logs nothing and the next launch re-runs the (UPSERT-idempotent) import. Safe for staged rollouts.

clearStoredChats left alone -- explicit user-initiated clear keeps wiping Dexie as before. "Never delete Dexie" applies to the migration-time / implicit paths only.

Recovery contract

If the user deletes studio.db, the ledger rows disappear with it. Next sidebar mount -> fast-paths A/B/C all miss -> ledger fetch returns empty -> import re-runs from Dexie. The recovery the boolean sentinel lacked.

Tests

5 new test_legacy_import_log_* cases in studio/backend/tests/test_chat_history_storage.py: empty default, record+list round-trip, idempotency, input dedup, empty/null ignore. The 9 pre-existing tests still pass (14/14 green locally).

Cross-browser validation

PR danielhanchen#138 re-ran with the fix applied (commit 01bd3c45 on staging-2, same change set): 6/6 jobs green on the full ubuntu/macos/windows x chromium/firefox/webkit/msedge matrix. Run: https://github.com/danielhanchen/unsloth-staging-2/actions/runs/26277147998 .

Builds on top of 2b5f8534 (@shine1i's "Tighten chat legacy fallbacks"); clean cherry-pick, no conflicts.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6fcc8a2c49

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +369 to +371
}
}
markLegacyChatImportDone();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid marking import complete when ledger endpoint is missing

When the backend predates /api/chat/import-ledger, recordChatImportLedger() returns 0 (404/405 fallback) instead of throwing, so this path still calls markLegacyChatImportDone(). That sets the localStorage fast-path permanently, which prevents future re-import attempts even after a later studio.db reset, causing legacy Dexie chats to stay hidden/lost in mixed-version deployments. Only mark the import as done after ledger persistence is actually confirmed (or explicitly detect unsupported ledger and skip setting the hint).

Useful? React with 👍 / 👎.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request May 22, 2026
…ation

Adds tests/studio/playwright_pr5272_migration.py + matrix workflow on
ubuntu/macos/windows x chromium/firefox/webkit/msedge. Validates that
importLegacyChatsIfNeeded (chat-history-storage.ts:246) correctly
copies mock legacy Dexie data into chat_threads / chat_messages on
first sidebar mount, with parent_id preserved for the regen branch
fan-out.

No GPU required: install.sh --local --no-torch + UNSLOTH_API_ONLY=1
boots Studio without llama-server. The migration runs purely on
Dexie -> SQLite copy semantics, so chat inference is not exercised
and runner cost stays low.

Drops the other workflows on this branch to stay well under the
5-Windows-concurrent runner cap.
The previous commit added a server-side ledger to make Dexie -> studio.db
import recoverable after a studio.db wipe, but the localStorage perf hint
still short-circuited the import gate before the ledger was ever consulted.
After a wipe, the hint stayed "true" and the bulk re-import never ran -- the
ledger sat empty and only the per-thread lazy materialize-on-continue path
restored data.

Changes:

- Remove the localStorage short-circuit from importLegacyChatsIfNeeded so
  the ledger is checked on every fresh tab. legacyChatImportPromise keeps
  the per-session cache; the hint now only matters for the listing paths.
- Batch the slow path: one db.messages.where().anyOf().toArray() and one
  batchListChatMessages() instead of 2N round-trips. At 1k threads this
  drops a multi-second blocking import to a single request pair.
- recordChatImportLedger returns {accepted, inserted, supported}. The
  localStorage hint is only flipped when supported is true, so old
  backends (404 / 405 / 501) no longer permanently poison recovery.
- Ledger backfill: threads already present in chat_threads but missing
  from the ledger now get added too, so old-FE-then-new-FE deployments
  don't redo the diff every launch.
- Backend response field renamed recorded -> {accepted, inserted}.
  accepted is the deduped non-empty input count; inserted is the rows
  actually new (via INSERT ... RETURNING). Bounded by Field(max_length=
  10_000) on the request payload.
- Storage helpers renamed: chat_legacy_import_log -> chat_legacy_imports,
  record_* -> upsert_* to match the existing noun/verb conventions.
- DEXIE_DB_NAME exported from db.ts; duplicate constant in
  chat-history-storage.ts removed.
- 3 new route-level tests for /api/chat/import-ledger covering the
  round-trip, the (accepted, inserted) split, and the 10k payload cap.

All 18 chat-history tests pass.
@danielhanchen

Copy link
Copy Markdown
Member

Follow-up to #issuecomment-4508407406. I ran a five-angle review of 4cbad62e (security, correctness, performance, API contract, code quality) and pushed 54f918d7 to address the findings.

Most consequential fix

4cbad62e added the server-side ledger so a studio.db wipe could re-trigger import. But importLegacyChatsIfNeeded still short-circuited on isLegacyChatImportDone() (the localStorage hint) before fetching the ledger. After a studio.db wipe, the hint stayed "true" and the bulk re-import never ran. Per-thread lazy materialize-on-continue still restored data on click, but the ledger sat empty and the recovery path the ledger was built for was bypassed.

Removed the localStorage short-circuit. legacyChatImportPromise keeps the per-session cache so repeated sidebar mounts in the same tab still share one import. New users skip the network entirely via the indexedDB.databases() probe + count() fast paths.

Other fixes in the same commit

  • Discriminated 404/405/501 fallback. recordChatImportLedger returns {accepted, inserted, supported}. markLegacyChatImportDone() only fires when supported === true, so older deployments don't poison the hint and lock recovery out for clients that later talk to a new backend.
  • N+1 batched. Slow path was 2N round-trips per import (one db.messages.where().equals().toArray() + one listChatMessages(id) per thread). Replaced with one db.messages.where('threadId').anyOf(unimportedIds).toArray() + one batchListChatMessages(unimportedIds). At 1k threads this drops a multi-second blocking import to a single request pair.
  • Ledger backfills the already-in-backend branch. Threads already present in chat_threads but missing from the ledger now get added too, so users who imported under the old client don't redo the diff on every launch after upgrading.
  • recorded → {accepted, inserted}. recorded returned the deduped input count, not rows actually new; the name read as "rows inserted." Backend now uses INSERT ... RETURNING to report both values honestly.
  • Payload cap. Field(max_length=10_000) on the import-ledger POST body.
  • Helper rename for codebase consistency. chat_legacy_import_log → chat_legacy_imports; record_* → upsert_* (matches the existing upsert_chat_message / upsert_chat_thread family).
  • DEXIE_DB_NAME exported from db.ts instead of the magic string being duplicated in chat-history-storage.ts.
  • 3 new route-level tests for GET/POST /api/chat/import-ledger (round-trip, accepted/inserted split, 10k payload cap rejection).
  • dexieIsEmpty() still returns false on Dexie errors (forcing the slow path which throws and resets the import promise for retry) — comment documents the intent.

Verification

The cross-browser CI drives the actual Dexie → studio.db migration with the patched code on real Playwright browsers; the fix exercises (a) the new-user fast path (indexedDB.databases() returns no unsloth-chat entry), (b) the slow-path batched bulk import, and (c) the ledger write + markLegacyChatImportDone() only on supported.

Conflict in studio/frontend/src/features/chat/shared-composer.tsx:
took main's helper-based aria-labels (thinkEffortAriaLabel /
thinkToggleAriaLabel from unslothai#5655) since this branch never touched
the Think pill — they were left at the pre-helper inline strings
from before the divergence.
Conflict in studio/frontend/src/features/chat/api/chat-adapter.ts:
upstream main (unslothai#5671 Anthropic web_fetch wiring) extended the
sources extractor to handle both web_search and web_fetch tool
results. The PR branch only had the web_search-only version.
Took main's expanded condition; kept the existing multi-line
parseSourcesFromResult call style for codebase consistency.
@danielhanchen
danielhanchen merged commit 61ed4ca into unslothai:main May 22, 2026
20 of 29 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0102b086e9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +478 to +480
includeLegacyOnly:
!isLegacyChatImportDone() ||
(backendMessages.length === 0 && legacyMessages.length > 0),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stop rehydrating empty backend threads from legacy Dexie

After migration is marked complete, this includeLegacyOnly condition still flips to true whenever a backend thread currently has zero messages. In that case mergeMessages(...) treats all legacy-only messages as authoritative and merged.shouldSync becomes true, so the next call re-sends old Dexie messages back to /api/chat/threads/{id}/messages. A reproducible path is deleting all messages in a thread (backend becomes empty while legacy Dexie still has historical rows): reopening the thread restores deleted messages, which is a data-integrity regression.

Useful? React with 👍 / 👎.

rsd-darshan pushed a commit to rsd-darshan/unsloth that referenced this pull request Jun 3, 2026
* feat: Persist chat history in backend storage

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Address chat tombstone batching review

* fix: update desktop auth routes stub

* chat db settings storage

* chat db settings routes

* chat db settings client

* chat db settings store

* chat db settings wiring

* chat db history storage

* chat db settings migration

* chat db settings fallback

* chat db container metadata

* chat db legacy migration fixes

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* chat ci auth background reads

* chat auth storage fixes

* chat migration final fixes

* chat export batch message lookup

* chat history review fixes

* chat prune sync fix

* chat settings hydration retry

* gate settings persistence

* Scope chat-history rows by subject; fix hijack, clear-confirm, hydrate race

Backend storage and routes:
- chat_threads / chat_messages / chat_settings carry a NOT NULL subject
  column with composite PRIMARY KEY (id, subject). Two authenticated
  identities can no longer see or wipe each other's data.
- Pre-existing rows on an existing studio.db migrate under sentinel
  subject __legacy_unscoped__ via rename + rebuild + copy; single-user
  installs see no behavior change.
- ON CONFLICT(id, subject) DO UPDATE ... WHERE chat_messages.thread_id =
  excluded.thread_id refuses cross-thread re-parenting via upsert.
  upsert_chat_message + sync_chat_messages now raise
  ChatMessageThreadMismatch which the routes map to HTTP 409.
- replace_thread_messages rejects body messages whose threadId does not
  match the URL thread (HTTP 400) instead of silently rewriting them.
- DELETE /api/chat requires ?confirm=true, returns row count, logs the
  subject and count.
- upsert_chat_settings_merge does read + deep-merge + write inside a
  single BEGIN IMMEDIATE so concurrent writers no longer drop each
  other's updates. The route delegates to this helper.
- New POST /api/chat/messages:batch returns {thread_id -> messages[]}
  for many threads in one HTTP call. Subject-scoped. Unknown ids return
  empty lists instead of 404 so the sidebar/search caller can rebuild
  atomically.

Frontend:
- chat-runtime-store: hydrate-failure catch sets settingsHydrated:true
  so a transient backend blip no longer permanently disables
  persistence. setParams bumps inferenceParamMutationVersions
  unconditionally so a slow hydration response cannot clobber a
  pre-hydrate user edit. saveSettingsPatch replaces the serial chain
  with a debounced pendingPatch + deep merge; flush on beforeunload.
- chat-history-storage: clearStoredChats returns ClearStoredChatsResult
  distinguishing backend / legacy / both outcomes.
  listStoredChatThreadsWithMessages uses the batched fetch (one HTTP
  call) instead of Promise.all per-thread; legacy Dexie fallback only
  fires when the batch result is empty.
- chat-api: batchListChatMessages with graceful 404 / 405 fallback to
  per-thread listChatMessages for older servers.
- chat-thread-tombstones: store {id, deletedAt} tuples with 90-day GC
  and a 5000-entry cap so localStorage stays bounded. Back-compat reads
  pre-fix plain strings. Adds removeChatThreadTombstones (rollback) and
  clearAllChatThreadTombstones (post-legacy-purge clean-up).
- use-chat-sidebar-items: deleteChatItem tombstones synchronously
  BEFORE the backend round-trip and rolls back on failure (restores
  pre-PR optimistic UX). 300 ms trailing debounce on
  CHAT_HISTORY_UPDATED_EVENT plus requestSeq guard so stream-time event
  bursts produce at most one fetch per quiet window.

Tests:
- studio/backend/tests/pr5272_sim/ adds 64 regression tests covering
  schema migration from pre-fix shape, subject scoping, cross-thread
  hijack, bulk-replace mismatch, clear-confirm, concurrent settings,
  unicode + 2MB content + SQL-injection-safe binding, chunking
  boundary at 900 and 901 ids, batched endpoint (multi-subject + 1200
  ids + per-thread order), and grep contracts for the frontend patches.
  test_chat_history_storage.py updated to pass subject.

Verified locally on Linux + macOS + Windows GitHub Actions runners
(staging fork): 64 pass + 2 from the PR's own backend test on all
three OSes.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop subject scoping and clear-confirm gate (Studio is single-user)

Per maintainer feedback: subject scoping, cross-thread message hijack
guard, and DELETE /api/chat ?confirm=true gate are unnecessary because
Studio is intentionally single-user (the client already shows a confirm
dialog before clear-all).

This commit reverts those backend changes and keeps only the
non-multi-user pieces from the earlier fix commit:

- studio_db.py: restored to pre-fix shape; adds upsert_chat_settings_merge
  which does atomic read + deep-merge + write under BEGIN IMMEDIATE so
  two concurrent slider drags cannot drop one another's updates.
- routes/chat_history.py: restored; put_settings now calls the atomic
  merge instead of doing the read-merge-write across three separate
  connections. Adds POST /api/chat/messages:batch to collapse the
  sidebar/search rebuild from N round-trips to 1.
- frontend/api/chat-api.ts: align batchListChatMessages request and
  response keys with the backend (threadIds / messagesByThreadId).
- tests/test_chat_history_storage.py: add atomic-merge concurrency test,
  deep-merge nested-key test, and 901-id chunking-boundary test.
- Drop the pr5272_sim test directory (those tests covered the reverted
  subject-scoping/hijack/confirm behavior).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix sidebar delete crash, keepalive on settings beforeunload flush, search rebuild race

Two correctness bugs and one perf race surfaced by a fresh code review of
the prior fix commit:

- chat-api.ts: notifyChatHistoryUpdated was declared as a non-exported
  function, but use-chat-sidebar-items.ts imports it. The import would
  fail tsc with TS2305 and at runtime the optimistic-delete and
  delete-failure rollback paths would both throw.
- chat-runtime-store.ts + chat-settings-api.ts + chat-settings-storage.ts:
  the beforeunload settings flush is now actually keepalive. Without it
  the browser cancels the in-flight PUT on tab close, so the last slider
  drag is silently dropped (which is exactly the case the
  debounce+beforeunload combination was meant to protect against).
- use-chat-search-index.ts: rebuilds now coalesce with a 300ms trailing
  debounce and discard out-of-order responses via a requestSeq guard.
  Matches the sibling pattern in use-chat-sidebar-items.ts so two rapid
  CHAT_HISTORY_UPDATED_EVENTs (run-start + run-end save during a turn)
  cannot land with stale data winning.
- chat-thread-tombstones.ts: drop dead clearAllChatThreadTombstones with
  no call sites; Dexie is never wiped so the function has no use.

* fix(studio): protect chat persistence writes

* fix(studio): align chat history clear semantics

* fix(studio): show partial chat clear feedback

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): preserve chat persistence fallbacks

* fix(studio): harden chat thread persistence checks

* Preserve chat message timestamps

* Gate chat stream on history save

* Make chat thread backfill best effort

* Avoid chat message 404 probe

* Tighten chat legacy fallbacks

* chat: server-side ledger so legacy Dexie import is recoverable

The boolean localStorage sentinel
(unsloth_chat_legacy_imported_to_studio_db) made importLegacyChatsIfNeeded
non-recoverable: deleting studio.db while the browser keeps the flag
silently hides every legacy Dexie thread from the sidebar (verified by
the 3-GPU validation probe; matches the third review comment on PR
unslothai#5272). Same trap fires for browser-profile sync to a fresh machine
and any other path that wipes studio.db while keeping IndexedDB.

Source of truth moves into studio.db itself via a new
chat_legacy_import_log table keyed by legacy thread id. The ledger
disappears together with studio.db, so the next launch re-runs the
import from whatever Dexie still holds. localStorage stays as a
per-session perf hint only.

Performance, all bounded by the three new fast-paths before any
backend work:

  A) localStorage hint says "imported earlier in this session" -- 0
     network, ~0 ms. Covers the warm sidebar mount.

  B) indexedDB.databases() reports no "unsloth-chat" DB -- 0 network,
     ~1 ms. Covers every new user who never had the old browser-only
     Studio (the common case after launch).

  C) db.threads.count() + db.messages.count() are both 0 -- 0 network,
     ~5 ms. Covers returning users who migrated long ago and Dexie was
     never repopulated.

Only when all three miss does the code talk to the backend
(GET /api/chat/import-ledger -> diff vs Dexie -> existing import path
-> POST /api/chat/import-ledger to record what was just imported).
Per-thread tracking is enough because Dexie is read-only after this
PR; a thread's message set does not grow.

Backend deployments that predate the import-ledger routes are
handled transparently: the client treats 404/405 as an empty ledger
and re-runs the (idempotent via UPSERT) import on next launch.

Changes:
- storage/studio_db.py: new chat_legacy_import_log table (WITHOUT
  ROWID, PK on legacy_thread_id) + list_chat_legacy_import_log() +
  record_chat_legacy_import_log() (idempotent batch UPSERT).
- routes/chat_history.py: GET + POST /api/chat/import-ledger with the
  obvious request/response models.
- frontend api/chat-api.ts: listChatImportLedger() (returns a Set for
  O(1) diff) + recordChatImportLedger(), both with 404/405 fallback.
- frontend utils/chat-history-storage.ts: importLegacyChatsIfNeeded
  gains three fast-paths, ledger fetch on the slow path, and writes
  the ledger after a successful import. The localStorage helper is
  unchanged on the surface; it just stops being authoritative.
- tests: 5 new test_legacy_import_log_* cases (empty default, record
  + list round-trip, idempotency, input dedup, empty/null ignore).
  All 9 pre-existing tests still pass.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the legacy-import recovery actually recoverable

The previous commit added a server-side ledger to make Dexie -> studio.db
import recoverable after a studio.db wipe, but the localStorage perf hint
still short-circuited the import gate before the ledger was ever consulted.
After a wipe, the hint stayed "true" and the bulk re-import never ran -- the
ledger sat empty and only the per-thread lazy materialize-on-continue path
restored data.

Changes:

- Remove the localStorage short-circuit from importLegacyChatsIfNeeded so
  the ledger is checked on every fresh tab. legacyChatImportPromise keeps
  the per-session cache; the hint now only matters for the listing paths.
- Batch the slow path: one db.messages.where().anyOf().toArray() and one
  batchListChatMessages() instead of 2N round-trips. At 1k threads this
  drops a multi-second blocking import to a single request pair.
- recordChatImportLedger returns {accepted, inserted, supported}. The
  localStorage hint is only flipped when supported is true, so old
  backends (404 / 405 / 501) no longer permanently poison recovery.
- Ledger backfill: threads already present in chat_threads but missing
  from the ledger now get added too, so old-FE-then-new-FE deployments
  don't redo the diff every launch.
- Backend response field renamed recorded -> {accepted, inserted}.
  accepted is the deduped non-empty input count; inserted is the rows
  actually new (via INSERT ... RETURNING). Bounded by Field(max_length=
  10_000) on the request payload.
- Storage helpers renamed: chat_legacy_import_log -> chat_legacy_imports,
  record_* -> upsert_* to match the existing noun/verb conventions.
- DEXIE_DB_NAME exported from db.ts; duplicate constant in
  chat-history-storage.ts removed.
- 3 new route-level tests for /api/chat/import-ledger covering the
  round-trip, the (accepted, inserted) split, and the 10k payload cap.

All 18 chat-history tests pass.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: shine1i <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
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.

4 participants