Skip to content

Studio: reopen a chat on the branch it was left on - #13109

Merged
mahiatlinux merged 5 commits into
unslothai:mainfrom
oobabooga:studio-chat-branch-head
Oct 9, 2026
Merged

mahiatlinux merged 5 commits into
unslothai:mainfrom
oobabooga:studio-chat-branch-head

Conversation

@oobabooga

Copy link
Copy Markdown
Member

A Reddit user reports that after closing and reopening Studio, a chat shows only the first prompt and its reply, and that reinstalling did not help. On main this happens to any chat where an early reply was retried (or a message edited) and the original branch was then picked again in the branch picker. Reopening the chat shows the retried branch instead of the one that was left open. The later turns are still stored, and the branch picker on the first reply brings them back. A commenter asked whether the reporter had retried or edited a message, and that question is still unanswered, so it is not confirmed that this is the path the reporter hit.

Root cause

  • Chat rows record every branch through parent_id, but nothing records which branch was on screen.
  • The history loader in runtime-provider.tsx imports the rows without a headId. assistant-ui's MessageRepository.import then uses headId ?? messages.at(-1), and the loader sorts rows by createdAt, so the head is the newest row.

Fix

  • New utils/branch-head.ts stores the head of the branch on screen per thread in localStorage, under unsloth_chat_branch_head:<thread id>, the same way composer drafts are stored.

    • The prefix falls under the account-switch purge.
    • Deleting a chat from the sidebar clears the key once the delete succeeds.
  • useBranchHeadRecorder writes thread.messages.at(-1) whenever it changes: a sent message, a retry, an edit or a branch switch. Temporary chats are skipped until they are saved.

  • The history loader passes the saved head as headId. resolveSavedBranchHead in message-order.ts follows it down to its newest leaf, for two reasons:

    • Turns added under it later, from another tab or device, extend the same branch.
    • MessageRepository.resetHead drops every descendant of the head it is given, so a head that is not a leaf would remove those turns from the view.

    A saved head whose row no longer exists falls back to the newest row.

  • The context-usage restore, the token estimate, the recount fallback, the compare-exit restore and the fine-tune export of chats that are not on screen all use the same saved head.

Behavior that stays as on main:

  • A chat that was never branched opens exactly as before.
  • The selection is stored per browser origin, like composer drafts. Another browser, cleared storage, a Studio served on a different port, or a chat last opened before this change gets the newest row's branch. The desktop app's origin is its bundle, not the backend port.
  • The message count in the Library chats list still counts the newest row's branch. The server computes it in count_chat_messages_for_threads without seeing the browser's selection.

Testing

Live A/B in Studio, with main at 63988fd and this branch's first commit serving the same backend, using gemma-3-1b-it Q4_K_M. A Playwright script in Chromium sent three prompts, retried the first reply, clicked Previous to return to the original branch (1/2), and stopped there. The backend was then restarted, and the chat was opened in a new browser with the same storage.

Reopened chat Main This PR
Messages shown 1 user / 1 assistant (first prompt and the retry, picker on 2/2) 3 user / 3 assistant (the branch left open, picker on 1/2)

studio.db held all seven rows in both arms.

Neighbouring cases on the same build, each reopened afterwards:

Case Reopened chat
Left on the retry (2/2) The retry, 1 user / 1 assistant
Opened in another browser with nothing saved The newest row's branch, as on main
Back on 1/2, then a fourth prompt sent All four turns, and the saved head is the new reply
Two branched chats, one left on 1/2 and one on 2/2, switched three times from the sidebar Each kept its own branch on every switch and on reopening, and each saved head is a row of its own chat

The second commit, which moves the recorder into its own hook and clears the key only after a successful delete, was tested with unit tests only.

  • New reopened-chat-branch.test.ts covers head resolution: the saved branch, no saved head, a deleted head, turns added under the head, a retried child, and legacy rows without parents.
  • New saved-branch-head.test.ts runs the recorder hook and deleteChatItems. Its cases for a temporary chat saved after a branch switch and for a rejected delete each fail without the matching fix.
  • A new case in finetune-export-branches.test.ts exports a closed chat on the branch it was left on. It fails with main's prompt-storage-dialog.tsx.
  • npm run typecheck passed, eslint reports nothing new on the changed files, and npm test on Node 24.16 passed 11080 of 11080.

Not tested:

  • The desktop app, Windows, macOS, Firefox and WebKit.
  • Editing a user message instead of retrying a reply. It creates a branch the same way.
  • In the UI: saving a temporary chat, a rejected delete, the fine-tune export and the context meter. These are covered by unit tests only.
  • Compare panes.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-08T23:54:26.654773Z 72f2ad6 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#351.

@mahiatlinux mahiatlinux self-assigned this Oct 9, 2026
@mahiatlinux

Copy link
Copy Markdown
Contributor

Review-fix complete

Reviewed and converged through mirror PR #189. No functional correctness defect was confirmed. The required PR-scoped comment cleanup landed here as 25df9cf147a6785bc255010be67305446f3ef1d6; its patch ID matches mirror commit 57adec2e3cc76929fd78bb4eed20a2a38135c6b6, and the final source and mirror trees are identical.

Verification:

  • 37/37 focused frontend tests passed; the full frontend test suite passed.
  • TypeScript project typecheck and ESLint on all new files passed.
  • Base/head mutation and adversarial graph probes passed; removing the resolver made 5 of 7 new branch tests fail.
  • Five-slice comment cleanup passed the TypeScript comment-only AST gate; the full suite also protected an exact source-slicing test marker.
  • Exact-base/final-head Chromium evidence used separate Studio installs, homes, databases, ports, caches, and browser contexts.

UI result: BEFORE reopened the two-message retry branch at 2/2; AFTER reopened the six-message original branch at 1/2; both stored the same seven rows.

PR 13109 branch reopen before and after

Mirror Codex convergence: no major issues on 57adec2e3c. Full command-level evidence is in the mirror review comment.

Local browser/platform scope was Chromium on Linux; the source PR's CI supplies the wider browser and OS matrix.

@mahiatlinux mahiatlinux 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.

LGTM! Ready to merge, all manually checked.

@mahiatlinux
mahiatlinux merged commit ee9c077 into unslothai:main Oct 9, 2026
@Imagineer99

Copy link
Copy Markdown
Member

playwright A/B at 472a1fe9 confirms the fix, all three exchanges survive a backend and browser restart and response 2/4 stays selected, 15 targeted tests pass too. before · after

CelesteHeartsong pushed a commit to CelesteHeartsong/unsloth that referenced this pull request Oct 9, 2026
A branched thread lost its forks on refresh: an edited user message is written
after its reply, so the reply's createdAt predates its user parent, and
assistant-ui's import() throws on a child that precedes its parent.

The write path already ordered rows parents-first; the read path never did, so
the import aborted. Reorder the read path's rows with the shared
orderParentsFirst (message-order.ts). headId comes from the saved-branch head
(unslothai#13109), which always resolves to a leaf, so import won't drop the head's
descendants.

Adds regression tests through a real MessageRepository.import();
save-temporary-chat injects the shared helper.
Full frontend suite: 11110 pass / 0 fail; typecheck clean.
mahiatlinux added a commit that referenced this pull request Oct 9, 2026
…13113)

* fix(chat): import branch threads parents-before-children on refresh

A branched thread lost its forks on refresh: an edited user message is written
after its reply, so the reply's createdAt predates its user parent, and
assistant-ui's import() throws on a child that precedes its parent.

The write path already ordered rows parents-first; the read path never did, so
the import aborted. Reorder the read path's rows with the shared
orderParentsFirst (message-order.ts). headId comes from the saved-branch head
(#13109), which always resolves to a leaf, so import won't drop the head's
descendants.

Adds regression tests through a real MessageRepository.import();
save-temporary-chat injects the shared helper.
Full frontend suite: 11110 pass / 0 fail; typecheck clean.

* Trim comments in PR scope

* Avoid recursive chat parent traversal

* Keep fallback chat branch after reordering

---------

Co-authored-by: CelesteHeartsong <[email protected]>
Co-authored-by: mahiatlinux <[email protected]>
danielhanchen added a commit that referenced this pull request Oct 10, 2026
…uting merges (#13173)

* Fix the two Backend CI test failures on main after the branch-restore and Omni routing merges

test_new_chat_context_recount: #13109 made the history restore estimate the
selected branch (estimateContextUsage(branch)) instead of every stored row.
The product change is right; the harness that replays the sliced restore did
not bind the loader's new `branch` local, so every history-hydration case
threw "branch is not defined", and the binding guard's self-check still
pinned `msgs`. Bind `branch` with the real orderBySelectedBranch and
resolveSavedBranchHead from message-order.ts, the way the loader computes it
without a saved head, and make the guard's self-check require only the
destructured remoteId plus one plain local, not a specific input of the
block.

test_omni_text_only_load: #13087's _route tests call FastModel.from_pretrained,
which repoints transformers' LOSS_MAPPING at Unsloth's Triton loss for the
whole process before the route is captured, and never undo it. Any Omni
forward with labels later in that xdist worker then ran Triton on the CPU
runner ("0 active drivers"), so 0 to 4 of these tests failed depending on
scheduling. Stub patch_loss_functions in _route, which routing does not need,
and have the Omni tests use transformers' own causal-LM loss on a CPU host so
another leaker cannot break them; on a GPU host they keep Unsloth's loss.

* Restore the whole loss mapping after each Omni test, and sort the harness messages like the loader

The Omni fixture now snapshots LOSS_MAPPING, installs transformers' own loss
for the test body on CPU, and puts the full snapshot back afterwards, so a
load inside the test (_capture_fast_base_kwargs) cannot leave the Triton loss
behind for the next test in the worker.

The recount harness sorts the stored messages by createdAt, role and id
before taking msgs.at(-1) as the fallback head, as runtime-provider.tsx does,
so an unsorted fixture cannot price a branch the loader would not select.
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.

3 participants