Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Name forks after the chat they came from, and close their inherited history (#11607)
Michael Han76846f426159
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 1a06ad6bf82..e249a3f7ac4 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -179,6 +179,8 @@ class ChatThread(BaseModel):anthropicCodeExecContainerId: Optional[str] = NoneforkedFromThreadId: Optional[str] = NoneforkedFromMessageId: Optional[str] = None+ forkBoundaryMessageId: Optional[str] = None+ forkTitleBase: Optional[str] = Nonesettings: Optional[ChatThreadSettings] = None@field_serializer("settings")@@ -1655,14 +1657,11 @@ def fork_thread(status_code = 404,detail = f"Message {payload.messageId} not found in thread {thread_id}",)- base_title = source.get("title") or "New Chat"- new_title = f"fork · {base_title}"try:forked = fork_chat_thread(source_thread_id = thread_id,branch_message_id = payload.messageId,new_thread_id = payload.newThreadId,- new_title = new_title,created_at = payload.createdAt,id_factory = lambda: str(uuid.uuid4()),)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 35b125645b6..c512d4c4021 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -20,7 +20,7 @@ from datetime import datetime, timezonefrom pathlib import Pathlogger = logging.getLogger(__name__)-from typing import Any, Callable, Iterable, Optional+from typing import Any, Callable, Iterable, Mapping, Optionalfrom utils.account_context import is_owner_context@@ -423,6 +423,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:anthropic_code_exec_container_id TEXT,forked_from_thread_id TEXT,forked_from_message_id TEXT,+ fork_boundary_message_id TEXT,+ fork_title_base TEXT,settings_json TEXT,FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE)@@ -453,6 +455,13 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE chat_threads ADD COLUMN forked_from_thread_id TEXT")if "forked_from_message_id" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN forked_from_message_id TEXT")+ # Null on forks taken before this column: those threads simply show no divider.+ if "fork_boundary_message_id" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN fork_boundary_message_id TEXT")+ # The name a fork numbers from, written when it is made and cleared when it is renamed.+ # Null on every earlier row, which then numbers from its whole title.+ if "fork_title_base" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN fork_title_base TEXT")if "updated_at" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN updated_at INTEGER")# Floor at created_at: forked threads copy older ancestor messages, so the fork's creation time wins.@@ -1953,6 +1962,8 @@ def _chat_thread_from_row(row: sqlite3.Row, include_settings: bool = True) -> di"anthropicCodeExecContainerId": data.get("anthropic_code_exec_container_id"),"forkedFromThreadId": data.get("forked_from_thread_id"),"forkedFromMessageId": data.get("forked_from_message_id"),+ "forkBoundaryMessageId": data.get("fork_boundary_message_id"),+ "forkTitleBase": data.get("fork_title_base"),}if include_settings:thread["settings"] = _json_loads(data.get("settings_json"), None)@@ -2014,8 +2025,8 @@ def upsert_chat_thread(thread: dict) -> dict:conn.execute("""INSERT INTO chat_threads- (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, settings_json)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, fork_boundary_message_id, fork_title_base, settings_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETtitle = excluded.title,model_type = excluded.model_type,@@ -2034,6 +2045,19 @@ def upsert_chat_thread(thread: dict) -> dict:anthropic_code_exec_container_id = excluded.anthropic_code_exec_container_id,forked_from_thread_id = excluded.forked_from_thread_id,forked_from_message_id = excluded.forked_from_message_id,+ -- fork_boundary_message_id is deliberately absent. It is set once, on the insert+ -- that makes the fork, and moved only by the prune that deletes the row it names.+ -- A whole-record writer carries whatever it read, which may predate that move, so+ -- on conflict the stored anchor always wins.+ -- Server-managed on an existing row, like the anchor above: the payload never+ -- contributes, since a writer carries whatever it read and a base it saw can+ -- already have been cleared by a rename it did not see. The title decides alone.+ -- A new one drops the base; the same one keeps whatever is stored.+ fork_title_base = CASE+ WHEN excluded.title = chat_threads.title+ THEN chat_threads.fork_title_base+ ELSE NULL+ END,-- an absent snapshot keeps the stored one: most writers rebuild the record without it.settings_json = COALESCE(excluded.settings_json, chat_threads.settings_json)""",@@ -2052,6 +2076,8 @@ def upsert_chat_thread(thread: dict) -> dict:thread.get("anthropicCodeExecContainerId"),thread.get("forkedFromThreadId"),thread.get("forkedFromMessageId"),+ thread.get("forkBoundaryMessageId"),+ thread.get("forkTitleBase"),json.dumps(thread["settings"]) if thread.get("settings") is not None else None,),)@@ -2126,6 +2152,16 @@ def update_chat_thread(if key in patch:assignments.append(f"{column} = ?")values.append(value)+ # A rename ends the generated name, so the base it numbered from goes with it. Auto-titling+ # lands here too, and it is a rename like any other. Only an actual change, though: renaming a+ # pair patches every thread in it, so one can be sent the title it already has, and clearing+ # there would cost its next fork a number. The right-hand side reads the pre-update row, so+ # this compares the stored title against the incoming one. Same rule as the upsert's.+ if "title" in patch:+ assignments.append(+ "fork_title_base = CASE WHEN title = ? THEN fork_title_base ELSE NULL END"+ )+ values.append(patch.get("title"))if not assignments and settings_write is None:return get_chat_thread(id)@@ -3729,6 +3765,9 @@ def sync_chat_messages(for message_id, stored_parent in _parents_of(conn, thread_id, reseat_candidates).items()if stored_parent is not None and stored_parent in pruned}+ # Same repair for the fork divider's anchor: walked from the stored chain before the+ # delete, since afterwards the row it names is gone and the walk has nothing to follow.+ reseat_boundary = _fork_boundary_reseat(conn, thread_id, pruned)_raise_if_chat_message_thread_conflicts(conn,thread_id,@@ -3804,6 +3843,11 @@ def sync_chat_messages((thread_id, *chunk),)_reseat_protected_messages(conn, thread_id, reseat_parents)+ if reseat_boundary is not _NO_RESEAT:+ conn.execute(+ "UPDATE chat_threads SET fork_boundary_message_id = ? WHERE id = ?",+ (reseat_boundary, thread_id),+ )_recompute_chat_thread_updated_at(conn, thread_id)elif reconciled_messages:_bump_chat_thread_updated_at(@@ -3838,6 +3882,47 @@ def _parents_of(conn, thread_id: str, message_ids: set) -> dict:}+# Distinct from None, which is a boundary to clear: the thread kept none of its inherited history.+_NO_RESEAT = object()+++def _fork_boundary_reseat(conn, thread_id: str, pruned: set):+ """Where a fork's divider moves when the message it sits under is pruned: up to the last+ inherited message that survived, or off entirely. Left on a deleted row it matches nothing+ and the fork's history loses its close for good. `_NO_RESEAT` means leave it alone."""+ if not pruned:+ return _NO_RESEAT+ row = conn.execute(+ "SELECT fork_boundary_message_id FROM chat_threads WHERE id = ?", (thread_id,)+ ).fetchone()+ boundary = row["fork_boundary_message_id"] if row is not None else None+ if boundary is None or boundary not in pruned:+ return _NO_RESEAT+ return _surviving_visible_ancestor(conn, thread_id, boundary, pruned)+++def _surviving_visible_ancestor(+ conn: sqlite3.Connection, thread_id: str, message_id: str, pruned: set+) -> "str | None":+ """The nearest ancestor of `message_id` that survives `pruned` and paints a row.++ The divider rides the row it names, so an ancestor the thread renders as nothing cannot+ carry it; landing there loses the divider as surely as landing on a deleted row does.+ None when no visible inherited history is left, which is a boundary to clear."""+ seen = {message_id}+ candidate = _surviving_parent_id(conn, thread_id, message_id, pruned)+ while candidate is not None and candidate not in seen:+ seen.add(candidate)+ row = conn.execute(+ "SELECT role FROM chat_messages WHERE thread_id = ? AND id = ?",+ (thread_id, candidate),+ ).fetchone()+ if row is not None and row["role"] in _RENDERED_MESSAGE_ROLES:+ return candidate+ candidate = _surviving_parent_id(conn, thread_id, candidate, pruned)+ return None++def _reseat_protected_messages(conn, thread_id: str, reseat_parents: dict) -> None:"""Point protected messages at the ancestor that survived the prune. Their own rows survive it, theparents they pointed at need not, and a dangling parent makes the whole thread unimportable on@@ -3910,11 +3995,56 @@ class ChatForkActiveGenerationError(RuntimeError):"""A durable generation prevents copying a settled chat."""+_FORK_TITLE_SUFFIX = re.compile(r"^(?P<base>.*?)\s*\((?P<n>\d+)\)\s*$", re.DOTALL)++# Roles the thread paints a row for. Mirrors threadMessageKind in+# components/assistant-ui/thread-message-slot.ts, which is pinned from the other side by+# thread-message-slot.test.ts. Only used to place the fork divider, which rides a row.+_RENDERED_MESSAGE_ROLES = frozenset({"user", "assistant"})+++def _title_family(conn: sqlite3.Connection, base: str) -> list[tuple[str, str]]:+ """Every chat named `base` or `base (n)`, as (id, title)."""+ return [+ (row["id"], row["title"] or "")+ for row in conn.execute(+ "SELECT id, title FROM chat_threads WHERE title = ? OR title LIKE ? ESCAPE '\\'",+ (base, _like_escape(base) + " (%)"),+ )+ ]+++def fork_base_of(src: Mapping) -> str:+ """The name a fork of `src` numbers from.++ A generated title carries the base it was built from, so "Notes (1)" gives "Notes"+ however its family fares later: the source can be deleted or renamed and the next+ fork is still "Notes (2)". Anything else numbers from its whole title, which is what+ keeps a chat the user named "Budget (2026)" out of the suffix rule. The base is+ cleared on rename, so a fork renamed to "Report (2026)" lands there too.+ """+ stored = (src["fork_title_base"] or "").strip()+ return stored or (src["title"] or "").strip()+++def _next_fork_title(conn: sqlite3.Connection, base: str) -> str:+ """Lowest free `base (n)`, n >= 1. Called inside the fork's write lock, so two+ concurrent forks of one chat cannot pick the same number."""+ taken: set[int] = set()+ for _id, title in _title_family(conn, base):+ match = _FORK_TITLE_SUFFIX.match(title)+ if match and match.group("base").strip() == base:+ taken.add(int(match.group("n")))+ n = 1+ while n in taken:+ n += 1+ return f"{base} ({n})"++def fork_chat_thread(source_thread_id: str,branch_message_id: Optional[str],new_thread_id: str,- new_title: str,created_at: int,id_factory,) -> Optional[dict]:@@ -3989,17 +4119,32 @@ def fork_chat_thread(ancestry.reverse() # root .. branch msgid_map: dict[str, str] = {row["id"]: id_factory() for row in ancestry}src_dict = dict(src)+ # Named from the row this transaction read, under the write lock: a title taken+ # before it could be renamed by another tab, and the number could already be gone.+ base = fork_base_of(src)+ title = _next_fork_title(conn, base)+ # Anchor for the "Continued from chat" divider. Not derivable later: copies keep the+ # source's timestamps and take fresh ids. The last message that PAINTS one, not simply+ # the last copied: an imported chat can end on a system message, which renders as no row+ # at all (threadMessageKind), and the divider rides the row it anchors to. Picking it in+ # the frontend instead would mean reading the whole message list in every row, which is+ # what the thread's render budget forbids. None when nothing inherited is visible.+ boundary_row = next(+ (row for row in reversed(ancestry) if row["role"] in _RENDERED_MESSAGE_ROLES), None+ )+ boundary_message_id = id_map[boundary_row["id"]] if boundary_row is not None else Noneconn.execute("""INSERT INTO chat_threads(id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at,openai_code_exec_container_id, anthropic_code_exec_container_id,- forked_from_thread_id, forked_from_message_id, settings_json)- VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?, ?)+ forked_from_thread_id, forked_from_message_id, fork_boundary_message_id,+ fork_title_base, settings_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?, ?, ?, ?)""",(new_thread_id,- new_title,+ title,src_dict["model_type"],src_dict.get("model_id") or "",src_dict.get("model_gguf_variant"),@@ -4008,6 +4153,8 @@ def fork_chat_thread(int(created_at),source_thread_id,branch_message_id,+ boundary_message_id,+ base,src_dict.get("settings_json"),),)diff --git a/studio/backend/tests/multi_account/factories_chat.py b/studio/backend/tests/multi_account/factories_chat.pyindex d8f0f42c529..d4a01655a05 100644--- a/studio/backend/tests/multi_account/factories_chat.py+++ b/studio/backend/tests/multi_account/factories_chat.py@@ -161,7 +161,6 @@ def seed_chat_fork_tree(account) -> dict[str, str]:source_thread_id = FORK_THREAD_ID,branch_message_id = FORK_MESSAGE_ID,new_thread_id = FORKED_CHILD_THREAD_ID,- new_title = f"fork of {CHAT_SENTINEL}",created_at = 1001,id_factory = lambda: FORKED_CHILD_THREAD_ID + "-message",)diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex 8ae39197a03..f49f5441f1d 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -859,7 +859,7 @@ def test_fork_thread_happy_path(monkeypatch):forked = {**source,"id": "new",- "title": "fork · Original",+ "title": "Original (1)","createdAt": 2,"forkedFromThreadId": "src","forkedFromMessageId": "m1",@@ -901,7 +901,7 @@ def test_fork_thread_happy_path(monkeypatch):current_subject = "test-user",)assert response.thread.id == "new"- assert response.thread.title == "fork · Original"+ assert response.thread.title == "Original (1)"assert response.thread.forkedFromThreadId == "src"assert response.thread.forkedFromMessageId == "m1"assert len(response.messages) == 1@@ -940,7 +940,7 @@ def test_fork_thread_warns_when_parent_had_container(monkeypatch):lambda **_: {**source,"id": "new",- "title": "fork · T",+ "title": "T (1)","forkedFromThreadId": "src","forkedFromMessageId": "m1","openaiCodeExecContainerId": None,@@ -1498,3 +1498,92 @@ def test_compare_and_set_rejects_a_non_finite_number_renderably(monkeypatch):assert response.status_code == 400assert "NaN" not in response.text+++def test_fork_route_numbers_the_title_and_reports_the_boundary(tmp_path, monkeypatch):+ """The whole path, real storage: the name loses the prefix and the divider gets its anchor."""+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())++ studio_db.upsert_chat_thread(+ {"id": "src", "title": "Research notes", "modelType": "base", "createdAt": 1}+ )+ studio_db.sync_chat_messages(+ "src",+ [+ {+ "id": f"m{i}",+ "threadId": "src",+ "parentId": None if i == 1 else f"m{i - 1}",+ "role": "user",+ "content": [{"type": "text", "text": f"m{i}"}],+ "createdAt": i,+ }+ for i in (1, 2)+ ],+ )++ titles = []+ for i in range(2):+ response = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = f"fork-{i}", createdAt = 10 + i),+ current_subject = "test-user",+ )+ titles.append(response.thread.title)++ assert titles == ["Research notes (1)", "Research notes (2)"]+ assert not any(t.startswith("fork") for t in titles)++ forked = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = "fork-x", createdAt = 20),+ current_subject = "test-user",+ )+ assert forked.thread.title == "Research notes (3)"+ # The anchor is this fork's own last inherited message, so the divider lands under it.+ assert forked.thread.forkBoundaryMessageId == forked.messages[-1].id+ assert forked.thread.forkBoundaryMessageId not in {"m1", "m2"}+++def test_fork_title_comes_from_the_row_not_the_route_s_earlier_read(tmp_path, monkeypatch):+ """A rename landing between the route's read and the write lock must not name the fork."""+ from storage import studio_db++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())++ studio_db.upsert_chat_thread(+ {"id": "src", "title": "Renamed", "modelType": "base", "createdAt": 1}+ )+ studio_db.sync_chat_messages(+ "src",+ [+ {+ "id": "m1",+ "threadId": "src",+ "parentId": None,+ "role": "user",+ "content": [{"type": "text", "text": "hi"}],+ "createdAt": 1,+ }+ ],+ )+ # What the route saw before the lock: the name as it was, now stale.+ monkeypatch.setattr(+ chat_history,+ "get_chat_thread",+ lambda _id: {"id": "src", "title": "Stale name", "modelType": "base", "createdAt": 1},+ )++ response = chat_history.fork_thread(+ thread_id = "src",+ payload = chat_history.ChatForkRequest(newThreadId = "fork-1", createdAt = 2),+ current_subject = "test-user",+ )+ assert response.thread.title == "Renamed (1)"+ assert "Stale" not in response.thread.titlediff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 51d02ee674f..d2844954fef 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -822,7 +822,6 @@ def test_fork_chat_thread_copies_ancestry_with_fresh_ids(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "m3",new_thread_id = "fork-1",- new_title = "fork · Original",created_at = 99,id_factory = id_factory,)@@ -858,7 +857,6 @@ def test_fork_preserves_legacy_ancestry(tmp_path, monkeypatch, linked_tip, brancsource_thread_id = "src",branch_message_id = branch_message_id,new_thread_id = "fork-1",- new_title = "fork",created_at = 4,id_factory = iter(("copy-1", "copy-2", "copy-3")).__next__,)@@ -878,7 +876,6 @@ def test_fork_chat_thread_preserves_project_id(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "m1",new_thread_id = "fork-1",- new_title = "fork · Original",created_at = 99,id_factory = lambda: "new-1",)@@ -929,7 +926,6 @@ def test_fork_chat_thread_detaches_research_run_metadata(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "research-report",new_thread_id = "fork-1",- new_title = "fork",created_at = 3,id_factory = iter(("fork-user", "fork-report")).__next__,)@@ -965,7 +961,6 @@ def test_fork_chat_thread_returns_none_for_missing_source(tmp_path, monkeypatch)source_thread_id = "nope",branch_message_id = "m1",new_thread_id = "fork",- new_title = "f",created_at = 1,id_factory = lambda: "x",)@@ -983,7 +978,6 @@ def test_fork_chat_thread_rejects_a_deleted_target_id(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "m1",new_thread_id = "fork",- new_title = "f",created_at = 2,id_factory = lambda: "new-1",)@@ -1006,7 +1000,6 @@ def test_count_forks_for_message(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "m1",new_thread_id = "f1",- new_title = "f1",created_at = 2,id_factory = id_factory,)@@ -1014,7 +1007,6 @@ def test_count_forks_for_message(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = "m1",new_thread_id = "f2",- new_title = "f2",created_at = 3,id_factory = id_factory,)@@ -1041,7 +1033,6 @@ def test_fork_counts_for_thread(tmp_path, monkeypatch):source_thread_id = "src",branch_message_id = branch,new_thread_id = new_id,- new_title = new_id,created_at = 10 + index,id_factory = id_factory,)@@ -1380,3 +1371,402 @@ def test_repeated_identical_sends_in_flat_thread_persist_separately(tmp_path, momessages = studio_db.sync_chat_messages("thread-1", payload)assert len(messages) == 2assert [m["id"] for m in messages] == ["u1", "u2"]+++# ---------------------------------------------------------------------------+# fork titles and the inherited-history boundary+# ---------------------------------------------------------------------------+++ "stored,title,base",+ [+ ("Chat", "Chat (2)", "Chat"), # generated, so the stored base wins+ ("Chat (2)", "Chat (2) (3)", "Chat (2)"), # a base may hold a number of its own+ (None, "Chat", "Chat"),+ (None, "Budget (2026)", "Budget (2026)"), # the user's number, kept whole+ (None, "Release (2)", "Release (2)"),+ (None, "(2)", "(2)"),+ (None, " Spaced ", "Spaced"),+ ("", "Chat (2)", "Chat (2)"), # blank is no base at all+ (" ", "Chat (2)", "Chat (2)"),+ ],+)+def test_fork_base_of(stored, title, base):+ """Without a stored base the whole title is one, so only a generated "(n)" is replaced."""+ assert studio_db.fork_base_of({"fork_title_base": stored, "title": title}) == base+++def _fork(source: str, new_id: str, at: int):+ return studio_db.fork_chat_thread(+ source_thread_id = source,+ branch_message_id = None,+ new_thread_id = new_id,+ created_at = at,+ id_factory = lambda: uuid.uuid4().hex,+ )+++def test_fork_of_an_ordinary_chat_keeps_a_numeric_suffix(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Budget (2026)"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])++ # The year is the user's, not a fork number, so it survives into the fork's name.+ assert _fork("src", "f0", 10)["title"] == "Budget (2026) (1)"+ # And a fork of that fork still numbers from the same base rather than nesting again.+ assert _fork("f0", "f1", 11)["title"] == "Budget (2026) (2)"+++def test_a_renamed_fork_keeps_the_name_the_user_gave_it(tmp_path, monkeypatch):+ """forked_from_thread_id survives a rename, so it alone cannot say the "(n)" is ours."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.upsert_chat_thread(+ {**_thread("f"), "title": "Report (2026)", "forkedFromThreadId": "orig"}+ )+ studio_db.sync_chat_messages("f", [_msg("m1", None, 1)])++ # No "Report" family to join, so the year is the user's and the whole name is the base.+ assert _fork("f", "f2", 10)["title"] == "Report (2026) (1)"+++def test_a_generated_suffix_is_still_replaced(tmp_path, monkeypatch):+ """A real fork carries the base it was built from, so its "(n)" is ours to take."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])++ assert _fork("orig", "f", 10)["title"] == "Notes (1)"+ assert _fork("f", "f2", 11)["title"] == "Notes (2)"+++def test_a_fork_numbers_from_its_base_after_the_source_is_gone(tmp_path, monkeypatch):+ """The stored base is the whole signal, so nothing about the source can take it away."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])+ assert _fork("orig", "f", 10)["title"] == "Notes (1)"++ studio_db.delete_chat_threads(["orig"]) # "Notes (1)" is now the only one left++ assert _fork("f", "f2", 11)["title"] == "Notes (2)"+++def test_a_fork_numbers_from_its_base_after_the_source_is_renamed(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])+ assert _fork("orig", "f", 10)["title"] == "Notes (1)"++ studio_db.update_chat_thread("orig", {"title": "Journal"})++ # The fork keeps its own family rather than following a name it never had.+ assert _fork("f", "f2", 11)["title"] == "Notes (2)"+++def test_renaming_a_fork_ends_the_generated_name(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])+ _fork("orig", "f", 10)++ studio_db.update_chat_thread("f", {"title": "Report (2026)"})+ assert studio_db.get_chat_thread("f")["forkTitleBase"] is None++ # The year is the user's now, so the whole name is the base.+ assert _fork("f", "f2", 11)["title"] == "Report (2026) (1)"+++def test_a_rename_through_upsert_also_ends_it(tmp_path, monkeypatch):+ """Whole-record writers rebuild the row without the base; only a new title drops it."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("orig"), "title": "Notes"})+ studio_db.sync_chat_messages("orig", [_msg("m1", None, 1)])+ _fork("orig", "f", 10)++ # Same title, no base in the payload: the stored one survives.+ studio_db.upsert_chat_thread({**_thread("f"), "title": "Notes (1)", "archived": True})+ assert studio_db.get_chat_thread("f")["forkTitleBase"] == "Notes"++ studio_db.upsert_chat_thread({**_thread("f"), "title": "Report (2026)"})+ assert studio_db.get_chat_thread("f")["forkTitleBase"] is None+++def test_fork_titles_number_from_the_original_name(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Research notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1), _msg("m2", "m1", 2)])++ titles = [_fork("src", f"f{i}", 10 + i)["title"] for i in range(3)]+ assert titles == ["Research notes (1)", "Research notes (2)", "Research notes (3)"]++ # Forking a fork numbers from the same base rather than nesting suffixes.+ assert _fork("f0", "deep", 20)["title"] == "Research notes (4)"+++def test_fork_title_fills_the_lowest_free_number(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ for i in range(3):+ _fork("src", f"f{i}", 10 + i)+ studio_db.delete_chat_threads(["f1"]) # frees "Notes (2)"++ assert _fork("src", "f-new", 30)["title"] == "Notes (2)"+++def test_fork_title_ignores_other_names_and_archived_state(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ # A different chat whose name merely starts with the base must not consume a number.+ studio_db.upsert_chat_thread({**_thread("other"), "title": "Notes extra (1)"})+ # An archived chat still holds its number, so restoring it cannot collide.+ studio_db.upsert_chat_thread({**_thread("old"), "title": "Notes (1)", "archived": True})++ assert _fork("src", "f-new", 30)["title"] == "Notes (2)"+++def test_fork_records_the_last_inherited_message(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages(+ "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]+ )++ forked = studio_db.fork_chat_thread(+ source_thread_id = "src",+ branch_message_id = "m2",+ new_thread_id = "fork-1",+ created_at = 99,+ id_factory = lambda: uuid.uuid4().hex,+ )+ copied = studio_db.list_chat_messages("fork-1")+ boundary = forked["forkBoundaryMessageId"]+ # The fork's own copy of the branch message, not the source's id.+ assert boundary == copied[-1]["id"]+ assert boundary not in {"m1", "m2", "m3"}+ assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == boundary+++def test_the_boundary_skips_a_trailing_message_that_paints_no_row(tmp_path, monkeypatch):+ """An imported chat can end on a system message, which the thread renders as nothing.+ Anchoring there would hang the divider off a row that never mounts."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})+ studio_db.sync_chat_messages(+ "src",+ [+ _stored_message(id = "m1", parentId = None, createdAt = 1),+ _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),+ _stored_message(id = "m3", parentId = "m2", role = "system", createdAt = 3),+ ],+ )++ forked = _fork("src", "fork-1", 99)+ copied = {m["id"]: m for m in studio_db.list_chat_messages("fork-1")}++ # The system message is still inherited, it just does not close the history.+ assert [m["role"] for m in copied.values()] == ["user", "assistant", "system"]+ assert copied[forked["forkBoundaryMessageId"]]["role"] == "assistant"+++def test_a_fork_with_nothing_visible_to_inherit_has_no_boundary(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Prompt only"})+ studio_db.sync_chat_messages(+ "src", [_stored_message(id = "m1", parentId = None, role = "system", createdAt = 1)]+ )++ # Nothing the reader can see, so no inherited history to close and no divider.+ assert _fork("src", "fork-1", 99)["forkBoundaryMessageId"] is None+++def test_a_whole_record_save_without_the_boundary_keeps_it(tmp_path, monkeypatch):+ """The backend owns the anchor and moves it itself, so an absent one is not a clear."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ boundary = _fork("src", "fork-1", 99)["forkBoundaryMessageId"]+ assert boundary is not None++ stored = studio_db.get_chat_thread("fork-1")+ studio_db.upsert_chat_thread({k: v for k, v in stored.items() if k != "forkBoundaryMessageId"})++ assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == boundary+++def test_a_stale_whole_record_save_cannot_move_the_boundary_back(tmp_path, monkeypatch):+ """A whole-record writer carries whatever it read, which may predate a prune that moved+ the anchor. Writing that back would park the divider on a deleted row for good."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages(+ "src",+ [+ _stored_message(id = "m1", parentId = None, createdAt = 1),+ _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),+ ],+ )+ _fork("src", "fork-1", 99)+ stale = dict(studio_db.get_chat_thread("fork-1")) # read before the delete++ copied = studio_db.list_chat_messages("fork-1")+ studio_db.sync_chat_messages(+ "fork-1",+ [m for m in copied if m["id"] != stale["forkBoundaryMessageId"]],+ prune_missing = True,+ )+ reseated = studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"]+ assert reseated != stale["forkBoundaryMessageId"]++ # The first writer now saves its old record for an unrelated change.+ studio_db.upsert_chat_thread({**stale, "archived": True})++ assert studio_db.get_chat_thread("fork-1")["forkBoundaryMessageId"] == reseated+ assert studio_db.get_chat_thread("fork-1")["archived"] is True+++def test_a_patch_repeating_the_stored_title_keeps_the_base(tmp_path, monkeypatch):+ """Renaming a pair patches every thread in it, so one can be sent the name it already has.+ That is not a rename, and clearing there would cost its next fork a number."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ forked = _fork("src", "fork-1", 99)+ assert forked["title"] == "Notes (1)"++ studio_db.update_chat_thread("fork-1", {"title": "Notes (1)"})++ assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] == "Notes"+ assert _fork("fork-1", "fork-2", 100)["title"] == "Notes (2)"+++def test_a_stale_whole_record_save_cannot_restore_a_cleared_base(tmp_path, monkeypatch):+ """A writer carries the base it read, which a rename it never saw may have cleared.+ Renaming away and back leaves the titles equal, so only the stored value can decide."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ _fork("src", "fork-1", 99)+ stale = dict(studio_db.get_chat_thread("fork-1"))+ assert stale["forkTitleBase"] == "Notes"++ studio_db.update_chat_thread("fork-1", {"title": "Report"})+ studio_db.update_chat_thread("fork-1", {"title": "Notes (1)"}) # the user's own name now+ assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None++ studio_db.upsert_chat_thread({**stale, "archived": True})++ assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None+ # The number is the user's, so it is kept whole rather than taken.+ assert _fork("fork-1", "fork-2", 100)["title"] == "Notes (1) (1)"+++def test_a_whole_record_rename_clears_the_base_it_carries(tmp_path, monkeypatch):+ """The record a client read still holds the old base, so the title has to decide alone."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages("src", [_msg("m1", None, 1)])+ _fork("src", "fork-1", 99)++ carried = dict(studio_db.get_chat_thread("fork-1"))+ assert carried["forkTitleBase"] == "Notes"+ studio_db.upsert_chat_thread({**carried, "title": "Report"})++ assert studio_db.get_chat_thread("fork-1")["forkTitleBase"] is None+ assert _fork("fork-1", "fork-2", 100)["title"] == "Report (1)"+++def test_plain_thread_has_no_fork_boundary(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread("plain"))+ assert studio_db.get_chat_thread("plain")["forkBoundaryMessageId"] is None+++def _forked_thread(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Notes"})+ studio_db.sync_chat_messages(+ "src", [_msg("m1", None, 1), _msg("m2", "m1", 2), _msg("m3", "m2", 3)]+ )+ return _fork("src", "f", 9)+++def test_pruning_the_boundary_moves_the_divider_up(tmp_path, monkeypatch):+ """Left on a deleted row the boundary matches nothing, and the divider never comes back."""+ _forked_thread(tmp_path, monkeypatch)+ copied = studio_db.list_chat_messages("f")+ studio_db.sync_chat_messages("f", copied[:-1], prune_missing = True)++ survivors = [m["id"] for m in studio_db.list_chat_messages("f")]+ assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] == survivors[-1]+++def test_pruning_every_inherited_message_clears_the_boundary(tmp_path, monkeypatch):+ _forked_thread(tmp_path, monkeypatch)+ studio_db.sync_chat_messages("f", [], prune_missing = True)++ # Nothing was inherited any more, so there is no history for a divider to close.+ assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] is None+++def test_pruning_an_earlier_message_leaves_the_boundary_alone(tmp_path, monkeypatch):+ forked = _forked_thread(tmp_path, monkeypatch)+ copied = studio_db.list_chat_messages("f")+ studio_db.sync_chat_messages("f", copied[1:], prune_missing = True)++ assert (+ studio_db.get_chat_thread("f")["forkBoundaryMessageId"] == forked["forkBoundaryMessageId"]+ )+++def test_the_reseat_skips_an_ancestor_that_paints_no_row(tmp_path, monkeypatch):+ """A system message can survive a prune that takes the boundary. It renders as nothing,+ so parking the divider there loses it just as surely as leaving it on the deleted row."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})+ studio_db.sync_chat_messages(+ "src",+ [+ _stored_message(id = "m1", parentId = None, createdAt = 1),+ _stored_message(id = "m2", parentId = "m1", role = "assistant", createdAt = 2),+ _stored_message(id = "m3", parentId = "m2", role = "system", createdAt = 3),+ _stored_message(id = "m4", parentId = "m3", createdAt = 4),+ ],+ )+ forked = _fork("src", "f", 10)+ copied = studio_db.list_chat_messages("f")+ by_id = {m["id"]: m for m in copied}+ boundary = forked["forkBoundaryMessageId"]++ # Prune the boundary; the system message directly above it survives.+ studio_db.sync_chat_messages(+ "f", [m for m in copied if m["id"] != boundary], prune_missing = True+ )++ moved = studio_db.get_chat_thread("f")["forkBoundaryMessageId"]+ assert by_id[moved]["role"] == "assistant"+++def test_the_reseat_clears_when_only_hidden_ancestors_survive(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread({**_thread("src"), "title": "Imported"})+ studio_db.sync_chat_messages(+ "src",+ [+ _stored_message(id = "m1", parentId = None, role = "system", createdAt = 1),+ _stored_message(id = "m2", parentId = "m1", createdAt = 2),+ ],+ )+ forked = _fork("src", "f", 10)+ copied = studio_db.list_chat_messages("f")+ boundary = forked["forkBoundaryMessageId"]++ studio_db.sync_chat_messages(+ "f", [m for m in copied if m["id"] != boundary], prune_missing = True+ )++ # Only the system prompt is left, so there is no visible inherited history to close.+ assert studio_db.get_chat_thread("f")["forkBoundaryMessageId"] is Nonediff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.pyindex ba678ca129f..cb05c8bd4b7 100644--- a/studio/backend/tests/test_chat_thread_settings.py+++ b/studio/backend/tests/test_chat_thread_settings.py@@ -148,7 +148,6 @@ def test_fork_inherits_the_snapshot(tmp_path, monkeypatch):source_thread_id = "thread-1",branch_message_id = "message-1",new_thread_id = "thread-2",- new_title = "Fork",created_at = 1_700_000_000_002,id_factory = lambda: "message-2",)diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex f361c01c2f6..e0432c9f074 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -194,6 +194,11 @@ import {settleThreadScopedSettingsForCopy,useChatRuntimeStore,} from "@/features/chat/stores/chat-runtime-store";+import {+ forkBoundaryAnchor,+ setForkBoundaryAnchor,+ useForkBoundaryStore,+} from "@/features/chat/stores/fork-boundary-store";import {PROMPT_QUEUE_RUN_FAILED_EVENT,PROMPT_QUEUE_STOP_EVENT,@@ -259,6 +264,7 @@ import {} from "@/features/chat/utils/composer-send-guard";import { deleteThreadMessage } from "@/features/chat/utils/delete-thread-message";import {+ readBackendChatThread,getStoredChatThread,updateStoredChatThread,} from "@/features/chat/utils/chat-history-storage";@@ -1759,16 +1765,125 @@ const RUN_SHRINK_WINDOW_MS = 1000;const ThreadMessage: FC = () => {const role = useAuiState(({ message }) => message.role);const isEditing = useAuiState(({ message }) => message.composer.isEditing);+ let body: ReactNode = null;switch (threadMessageKind(role, isEditing)) {case "edit":- return <EditComposer />;+ body = <EditComposer />;+ break;case "user":- return <UserMessage />;+ body = <UserMessage />;+ break;case "assistant":- return <AssistantMessage />;+ body = <AssistantMessage />;+ break;default:return null;}+ return (+ <>+ {body}+ <ForkContinuationRule />+ </>+ );+};++/**+ * Resolves the divider against the branch on screen, once for the thread.+ *+ * Which inherited message closes the history depends on the branch: editing an inherited turn+ * starts a sibling and leaves the fork's anchor off screen with earlier inherited messages+ * still above it. Selecting the message array in each ROW is what the delete render budget+ * forbids, so it is selected here, in one component, and the rows read the id it publishes.+ * The walk stops at the first message the fork did not inherit, so it costs the inherited+ * count rather than the thread length.+ */+const useTrackForkBoundaryAnchor = (threadId: string | null): void => {+ const inherited = useForkBoundaryStore((s) =>+ threadId === null+ ? undefined+ : s.boundaryByThreadId[threadId]?.messageIds,+ );+ const anchor = useAuiState(({ thread }) =>+ forkBoundaryAnchor(thread.messages, inherited),+ );+ useEffect(() => {+ setForkBoundaryAnchor(threadId, anchor);+ }, [threadId, anchor]);+};++// Closes the history a fork inherited. Rendered by the message it follows, since the row slot+// is propless and the boundary arrives through the store.+const ForkContinuationRule: FC = () => {+ const threadId = useChatRuntimeStore((s) => s.activeThreadId);+ const messageId = useAuiState(({ message }) => message.id);+ // Two plain values rather than the record: both stay identical between renders, so a row+ // subscribed to them does not re-render when an unrelated thread publishes.+ const anchor = useForkBoundaryStore((s) =>+ threadId === null ? undefined : s.anchorByThreadId[threadId],+ );+ const sourceThreadId = useForkBoundaryStore((s) =>+ threadId === null+ ? null+ : (s.boundaryByThreadId[threadId]?.sourceThreadId ?? null),+ );+ const navigate = useNavigate();+ if (anchor === undefined || anchor !== messageId) return null;+ const label = (+ <>+ <GitBranchIcon strokeWidth={1.75} className="size-3.5" />+ Continued from chat+ </>+ );+ const labelClass =+ "inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap leading-none";+ return (+ <div+ data-slot="fork-continuation-rule"+ // Same column as the messages it sits between: it is their sibling, not their child,+ // so it takes the width constraint every message root applies to itself.+ className="mx-auto mt-6 mb-2 flex w-full max-w-(--thread-content-max-width) items-center gap-3 text-muted-foreground text-sm"+ >+ <span aria-hidden={true} className="h-px flex-1 bg-border" />+ {sourceThreadId ? (+ <button+ type="button"+ data-slot="fork-continuation-link"+ title="Open the chat this was forked from"+ // Checked on the way out, not on render: the tombstone set is this tab's own, so a+ // source deleted on another device still looks openable until something asks for it.+ // Only a definite "no" stops the trip; an unreachable backend is not a deletion.+ onClick={async () => {+ const source = await readBackendChatThread(sourceThreadId);+ if (source === null) {+ toast.info("That chat has been deleted.");+ return;+ }+ navigate({+ to: "/chat",+ // A paired source is one half of a comparison, and the fork button is offered+ // inside those panes. Opening it as a single chat would show one model's side+ // rather than the view it was forked from. Same shape the sidebar opens a pair+ // with. An unreachable backend has no record to ask, so it falls through.+ search: source?.pairId+ ? { compare: source.pairId }+ : { thread: sourceThreadId },+ replace: false,+ });+ }}+ className={cn(+ labelClass,+ "cursor-pointer rounded-sm underline decoration-transparent underline-offset-2 transition-colors hover:text-foreground hover:decoration-current focus-visible:outline-2 focus-visible:outline-ring focus-visible:outline-offset-2",+ )}+ >+ {label}+ </button>+ ) : (+ // The source is gone, so the text stays but leads nowhere.+ <span className={labelClass}>{label}</span>+ )}+ <span aria-hidden={true} className="h-px flex-1 bg-border" />+ </div>+ );};// Hoisted, so ThreadPrimitive.Messages sees the same children function on every Thread render. An@@ -1799,6 +1914,7 @@ export const Thread: FC<{const threadId = targetThreadId ?? activeThreadId ?? null;const aui = useAui();useThreadForkCounts();+ useTrackForkBoundaryAnchor(threadId);// Measured height of the floating composer dock (null until measured).// Drives the bottom spacer and the scroll-to-bottom footer offset.diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex a7679dc78d3..042c63aa75e 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -110,6 +110,11 @@ export {useReasoningRoundStore,type ReasoningRoundState,} from "./stores/reasoning-round-store";+export {+ setForkBoundary,+ useForkBoundaryStore,+ type ForkBoundaryState,+} from "./stores/fork-boundary-store";export {folderRingKey,planKey,@@ -322,6 +327,7 @@ export {listStoredChatProjects,listStoredChatThreads,markThreadIncognito,+ readBackendChatThread,} from "./utils/chat-history-storage";export { allRecordedSandboxSessionIds } from "./utils/recorded-sandbox-session";export {diff --git a/studio/frontend/src/features/chat/stores/fork-boundary-store.ts b/studio/frontend/src/features/chat/stores/fork-boundary-store.tsnew file mode 100644index 00000000000..ce82bd025e9--- /dev/null+++ b/studio/frontend/src/features/chat/stores/fork-boundary-store.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { create } from "zustand";++import { rendersAsRow } from "@/components/assistant-ui/thread-message-slot";+import type { ThreadMessageRole } from "@/components/assistant-ui/thread-message-slot";++/** Where a fork's inherited history ends, and the chat it came from. */+export interface ForkBoundary {+ /**+ * This thread's own copies of every inherited message.+ *+ * A set rather than one id because the divider is a fact about the branch on screen, not+ * about a message: editing an inherited turn starts a sibling branch and keeps the originals,+ * so the last inherited message on the new branch is an earlier one, and switching back has+ * to restore the old one.+ */+ messageIds: ReadonlySet<string>;+ /** The chat the divider links back to, null once it is gone. */+ sourceThreadId: string | null;+}++// Published on load: message rows render from a propless slot, so they cannot be handed the+// thread record. A thread missing here shows no divider.+export interface ForkBoundaryState {+ boundaryByThreadId: Record<string, ForkBoundary>;+ /** The message the divider currently follows, resolved against the branch on screen. */+ anchorByThreadId: Record<string, string>;+ setForkBoundary: (threadId: string, boundary: ForkBoundary | null) => void;+ setForkBoundaryAnchor: (threadId: string, anchor: string | undefined) => void;+}++function sameIds(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {+ if (a === b) return true;+ if (a.size !== b.size) return false;+ for (const id of a) if (!b.has(id)) return false;+ return true;+}++function same(a: ForkBoundary | undefined, b: ForkBoundary): boolean {+ return (+ a !== undefined &&+ a.sourceThreadId === b.sourceThreadId &&+ sameIds(a.messageIds, b.messageIds)+ );+}++/**+ * The inherited message the divider follows on this branch, or undefined for none.+ *+ * The inherited chain runs from the root to the fork point, so it is a prefix of whatever+ * branch is selected: this stops at the divergence rather than walking a thread that has grown+ * past it. Only a message that paints a row can carry the divider, and `isEditing` is false+ * here because the branch alone does not say which message is being edited; an edit composer+ * is a row either way, so the only effect is on a system message mid-edit.+ */+export function forkBoundaryAnchor(+ messages: readonly { id: string; role: ThreadMessageRole }[],+ inherited: ReadonlySet<string> | undefined,+): string | undefined {+ if (inherited === undefined || inherited.size === 0) return undefined;+ let anchor: string | undefined;+ for (const message of messages) {+ if (!inherited.has(message.id)) break;+ if (rendersAsRow(message.role, false)) anchor = message.id;+ }+ return anchor;+}++export const useForkBoundaryStore = create<ForkBoundaryState>()((set) => ({+ boundaryByThreadId: {},+ anchorByThreadId: {},+ setForkBoundary: (threadId, boundary) =>+ set((state) => {+ const current = state.boundaryByThreadId[threadId];+ if (boundary === null) {+ if (current === undefined) return state;+ const next = { ...state.boundaryByThreadId };+ delete next[threadId];+ return { boundaryByThreadId: next };+ }+ // Same values keep the identity, so the rows subscribed to this do not re-render.+ if (same(current, boundary)) return state;+ return {+ boundaryByThreadId: { ...state.boundaryByThreadId, [threadId]: boundary },+ };+ }),+ setForkBoundaryAnchor: (threadId, anchor) =>+ set((state) => {+ const current = state.anchorByThreadId[threadId];+ if (current === anchor) return state;+ if (anchor === undefined) {+ if (current === undefined) return state;+ const next = { ...state.anchorByThreadId };+ delete next[threadId];+ return { anchorByThreadId: next };+ }+ return {+ anchorByThreadId: { ...state.anchorByThreadId, [threadId]: anchor },+ };+ }),+}));++export function setForkBoundary(+ threadId: string,+ messageIds: Iterable<string> | null | undefined,+ sourceThreadId?: string | null,+): void {+ const ids = messageIds ? new Set(messageIds) : null;+ useForkBoundaryStore+ .getState()+ .setForkBoundary(+ threadId,+ ids && ids.size > 0+ ? { messageIds: ids, sourceThreadId: sourceThreadId ?? null }+ : null,+ );+}++export function setForkBoundaryAnchor(+ threadId: string | null,+ anchor: string | undefined,+): void {+ if (threadId === null) return;+ useForkBoundaryStore.getState().setForkBoundaryAnchor(threadId, anchor);+}diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.tsindex 9448ed41cda..4b389354928 100644--- a/studio/frontend/src/features/chat/types.ts+++ b/studio/frontend/src/features/chat/types.ts@@ -53,6 +53,12 @@ export interface ThreadRecord {* and the parent thread's "N forks" indicator. */forkedFromThreadId?: string | null;forkedFromMessageId?: string | null;+ /** This thread's own copy of the last inherited message. The "Continued from chat" divider+ * sits after it. Null on forks taken before the column existed, which show no divider. */+ forkBoundaryMessageId?: string | null;+ /** The name this thread's generated title numbers from, so the next fork of it is the next+ * number. Cleared on rename, and null on anything the user named. */+ forkTitleBase?: string | null;/** this chat's own settings, applied when it is opened; absent means the global ones. */settings?:| import("./utils/thread-scoped-settings").ThreadScopedSettingsdiff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex ac71909b00b..03274858222 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -39,6 +39,8 @@ import {markChatThreadsDeleted,} from "./chat-thread-tombstones";import { ThreadRecordWriteCoordinator } from "./thread-record-write-coordinator";+// eslint-disable-next-line no-restricted-imports -- this file is in the startup cycle; the chat barrel closes it.+import { setForkBoundary } from "../stores/fork-boundary-store";// Thread ids belonging to a temporary/incognito session. A thread is tagged once at creation// and stays tagged for life; readers and writers consult this set, never the live toggle.@@ -723,6 +725,80 @@ async function retryFailedThreadRecord(return (await getChatThread(threadId)) ?? undefined;}+/**+ * The backend's own record for this chat: the row, null when it holds none, or undefined when+ * it could not say.+ *+ * Not `getStoredChatThread`, which answers with this browser's legacy row when the backend has+ * none. That fallback is right for opening a chat and wrong for asking whether one is still+ * there, which is the question a chat deleted on another device turns on. Undefined is kept+ * distinct from null so an unreachable backend is not reported as a deletion.+ */+export async function readBackendChatThread(+ threadId: string,+): Promise<ThreadRecord | null | undefined> {+ if (isThreadIncognito(threadId)) return null;+ if (isChatThreadDeleted(threadId)) return null;+ try {+ return await getChatThread(threadId);+ } catch {+ return undefined;+ }+}++/** Hand the "Continued from chat" divider where it sits, from a thread just read. */+async function publishForkBoundary(+ thread: ThreadRecord,+ messages: readonly MessageRecord[],+): Promise<void> {+ let inherited = inheritedMessageIds(thread.forkBoundaryMessageId, messages);+ if (thread.forkBoundaryMessageId && inherited.size > 0) {+ // The anchor placed against these messages, which is the ordinary case.+ } else if (thread.forkBoundaryMessageId) {+ // An anchor this list cannot place is not an anchor that is gone. The thread and the+ // messages are read in parallel, so a delete landing between them leaves the thread+ // naming a row the messages no longer carry. Re-reading the thread now puts it no+ // earlier than the messages, so a reseated anchor places; if it still does not, the+ // messages are the older half and the next load settles it. Either way, do not blank a+ // divider on the strength of two reads that disagree.+ const fresh = await getChatThread(thread.id).catch(() => undefined);+ if (!fresh) return;+ inherited = inheritedMessageIds(fresh.forkBoundaryMessageId, messages);+ if (fresh.forkBoundaryMessageId && inherited.size === 0) return;+ }+ setForkBoundary(+ thread.id,+ inherited,+ // A deleted source cannot be opened, so the divider drops its link rather than its text.+ thread.forkedFromThreadId && !isChatThreadDeleted(thread.forkedFromThreadId)+ ? thread.forkedFromThreadId+ : null,+ );+}++/**+ * Every message the fork inherited: the anchor and its ancestors.+ *+ * The anchor alone cannot place the divider, because editing an inherited message starts a+ * branch that leaves the anchor off screen while earlier inherited messages stay on it. The+ * chain is derived here rather than stored, since the parent links are already in hand.+ */+function inheritedMessageIds(+ anchorId: string | null | undefined,+ messages: readonly MessageRecord[],+): Set<string> {+ const ids = new Set<string>();+ if (!anchorId) return ids;+ const byId = new Map(messages.map((message) => [message.id, message]));+ let cursor = byId.get(anchorId);+ // Stops on a repeat as well as at the root: a corrupt chain must not spin.+ while (cursor !== undefined && !ids.has(cursor.id)) {+ ids.add(cursor.id);+ cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;+ }+ return ids;+}+export async function listStoredChatMessages(threadId: string,): Promise<MessageRecord[]> {@@ -741,6 +817,12 @@ export async function listStoredChatMessages(throw error;}),]);+ // The backend's own rows, which are the ones the anchor's parent chain runs through. No list+ // at all means nothing to place the anchor against, so the divider keeps what it has rather+ // than reading a failed read as an empty thread. Not awaited: the chat renders either way.+ if (backendThread && backendMessages) {+ void publishForkBoundary(backendThread, backendMessages);+ }if (backendMessages && (backendThread || backendMessages.length > 0)) {const merged = mergeMessages(backendMessages, legacyMessages, {includeLegacyOnly:@@ -1050,6 +1132,11 @@ export async function syncStoredChatMessages(// actual deletion: an ordinary sync runs constantly and would undo the whole cache.if (options.pruneMissing || (options.deletedMessageIds?.length ?? 0) > 0) {clearServerOwnedChatMessages();+ // Deleting the message the divider sits under moves it, in the same transaction that prunes.+ // Nothing else reads the thread again, so without this the divider stays gone until the chat+ // is reopened. Only on a delete, which is rare and already the user waiting on a round trip.+ const thread = await getChatThread(threadId).catch(() => undefined);+ if (thread) await publishForkBoundary(thread, synced);}return synced;}diff --git a/studio/frontend/src/features/chat/utils/studio-backup-import.ts b/studio/frontend/src/features/chat/utils/studio-backup-import.tsindex 18fb7bad46b..b9556df127e 100644--- a/studio/frontend/src/features/chat/utils/studio-backup-import.ts+++ b/studio/frontend/src/features/chat/utils/studio-backup-import.ts@@ -213,6 +213,14 @@ export function studioBackupToConversations(const forkedFromMessageId = messageIds.get(str(thread.forkedFromMessageId) ?? "",);+ // Points into this thread's own messages, so it remaps like any other id. Dropping it+ // would restore the fork without its "Continued from chat" divider.+ const forkBoundaryMessageId = messageIds.get(+ str(thread.forkBoundaryMessageId) ?? "",+ );+ // A name, not an id, so it restores as it stands. Without it the restored fork numbers+ // its own forks from its whole title, giving "Notes (1) (1)".+ const forkTitleBase = str(thread.forkTitleBase);const projectId = str(thread.projectId);const pairId = str(thread.pairId);const modelId = str(thread.modelId);@@ -241,6 +249,8 @@ export function studioBackupToConversations(...(forkedFromMessageId ? { forkedFromMessageId } : {}),}: {}),+ ...(forkBoundaryMessageId ? { forkBoundaryMessageId } : {}),+ ...(forkTitleBase ? { forkTitleBase } : {}),...(isDict(thread.settings) &&Object.keys(restorableSettings(thread.settings)).length > 0? {diff --git a/studio/frontend/tests/chat-save-server-managed-stop.test.ts b/studio/frontend/tests/chat-save-server-managed-stop.test.tsindex 8001165af46..7a600d3143e 100644--- a/studio/frontend/tests/chat-save-server-managed-stop.test.ts+++ b/studio/frontend/tests/chat-save-server-managed-stop.test.ts@@ -49,6 +49,7 @@ function harness(options: { rejectIds?: Set<string>; failWith?: Error } = {}) {},"../db": { DEXIE_DB_NAME: "test", db: {} },"./chat-thread-tombstones": { isChatThreadDeleted: () => false },+ "../stores/fork-boundary-store": { setForkBoundary: () => {} },"./thread-record-write-coordinator": {ThreadRecordWriteCoordinator: class {async settleCurrent() {}diff --git a/studio/frontend/tests/fork-boundary-republish.test.ts b/studio/frontend/tests/fork-boundary-republish.test.tsnew file mode 100644index 00000000000..602987b73ec--- /dev/null+++ b/studio/frontend/tests/fork-boundary-republish.test.ts@@ -0,0 +1,301 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Deleting the message a fork's "Continued from chat" divider sits under moves the boundary, in+// the same transaction that prunes the row. The delete path imports the returned messages and+// never reads the thread again, so the store kept naming the deleted id and the divider stayed+// gone for the rest of the view. Only a prune re-reads: the streaming autosave runs constantly.++import assert from "node:assert/strict";+import test from "node:test";++import { loadWithStubs } from "./helpers/module-stubs.ts";++type SyncOptions = { pruneMissing?: boolean; deletedMessageIds?: string[] };+type Module = {+ syncStoredChatMessages: (+ threadId: string,+ messages: unknown[],+ options?: SyncOptions,+ ) => Promise<unknown>;+ readBackendChatThread: (+ threadId: string,+ ) => Promise<Record<string, unknown> | null | undefined>;+};++type Published = [string, string[], string | null | undefined];++function harness(+ // null is the backend saying it has no such thread, which is what a 404 becomes.+ thread: Record<string, unknown> | null | undefined = {+ id: "fork-1",+ forkBoundaryMessageId: "m1",+ forkedFromThreadId: "src",+ },+ options: {+ deletedSources?: Set<string>;+ failReadsFrom?: number;+ legacyThreads?: Record<string, Record<string, unknown>>;+ syncedMessages?: { id: string; parentId?: string | null }[];+ // Successive answers from the thread endpoint, for the reads that race a delete.+ threadReadQueue?: (Record<string, unknown> | null)[];+ } = {},+) {+ const published: Published[] = [];+ const threadReads: string[] = [];+ const module = loadWithStubs<Module>(+ new URL(+ "../src/features/chat/utils/chat-history-storage.ts",+ import.meta.url,+ ),+ {+ "../api/chat-api": {+ ChatMessageProtectedError: class extends Error {},+ saveChatMessage: async (message: unknown) => message,+ notifyChatHistoryUpdated: () => {},+ syncChatMessages: async (_threadId: string, messages: unknown[]) =>+ // The rows the prune left behind, which is what the inherited chain walks.+ options.syncedMessages ?? messages,+ getChatThread: async (id: string) => {+ threadReads.push(id);+ // The row ensure reads first, so a count is how this picks out the boundary's own read.+ if (threadReads.length >= (options.failReadsFrom ?? Infinity)) {+ throw new Error("offline");+ }+ const queued = options.threadReadQueue?.shift();+ return queued === undefined ? thread : queued;+ },+ // Echoes the record back, like the real endpoint: returning nothing makes the legacy+ // re-import fail, which would hide the very fallback these tests are about.+ saveChatThread: async (t: unknown) => t,+ },+ "../db": {+ DEXIE_DB_NAME: "test",+ db: {+ threads: {+ get: async (id: string) => options.legacyThreads?.[id],+ },+ messages: {+ where: () => ({ equals: () => ({ toArray: async () => [] }) }),+ },+ },+ },+ "./chat-thread-tombstones": {+ isChatThreadDeleted: (id: string) =>+ options.deletedSources?.has(id) ?? false,+ },+ "../stores/fork-boundary-store": {+ setForkBoundary: (+ threadId: string,+ messageIds: Iterable<string> | null | undefined,+ sourceThreadId: string | null | undefined,+ ) =>+ published.push([threadId, [...(messageIds ?? [])], sourceThreadId]),+ },+ "./thread-record-write-coordinator": {+ ThreadRecordWriteCoordinator: class {+ async settleCurrent() {}+ async write(_id: string, fn: () => Promise<unknown>) {+ return fn();+ }+ observe() {}+ closeAdmission() {}+ confirmFinalState() {}+ hasPending() {+ return false;+ }+ idsRequiringFence() {+ return [];+ }+ },+ },+ },+ );+ return { module, published, threadReads };+}++test("deleting a message republishes the boundary the backend reseated", async () => {+ const { module, published } = harness(+ {+ id: "fork-1",+ // Where the prune moved it: the surviving parent of the row that was deleted.+ forkBoundaryMessageId: "m1",+ forkedFromThreadId: "src",+ },+ {+ syncedMessages: [+ { id: "m0", parentId: null },+ { id: "m1", parentId: "m0" },+ ],+ },+ );++ await module.syncStoredChatMessages("fork-1", [], {+ pruneMissing: true,+ deletedMessageIds: ["m2"],+ });++ assert.deepEqual(published, [["fork-1", ["m1", "m0"], "src"]]);+});++test("a prune that cleared the boundary clears the divider too", async () => {+ // Every inherited message went, so there is no inherited history left to close.+ const { module, published } = harness({+ id: "fork-1",+ forkBoundaryMessageId: null,+ forkedFromThreadId: "src",+ });++ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, [["fork-1", [], "src"]]);+});++test("the streaming autosave never pays for the extra read", async () => {+ const { module, published, threadReads } = harness(undefined, {+ syncedMessages: [+ { id: "m0", parentId: null },+ { id: "m1", parentId: "m0" },+ ],+ });++ await module.syncStoredChatMessages("fork-1", []);+ const before = threadReads.length;+ await module.syncStoredChatMessages("fork-1", [], {+ pruneMissing: false,+ deletedMessageIds: [],+ });+ const plainSyncReads = threadReads.length - before;+ assert.deepEqual(published, []);++ const beforePrune = threadReads.length;+ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ // Exactly one read more than the same sync without a prune, and it is the boundary's.+ assert.equal(threadReads.length - beforePrune, plainSyncReads + 1);+ assert.deepEqual(published, [["fork-1", ["m1", "m0"], "src"]]);+});++test("a source deleted in this tab keeps the words and drops the link", async () => {+ const { module, published } = harness(+ { id: "fork-1", forkBoundaryMessageId: "m1", forkedFromThreadId: "src" },+ {+ deletedSources: new Set(["src"]),+ syncedMessages: [+ { id: "m0", parentId: null },+ { id: "m1", parentId: "m0" },+ ],+ },+ );++ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, [["fork-1", ["m1", "m0"], null]]);+});++// --- the backlink's existence check ------------------------------------------++test("the backend's answer is what decides, not this browser's legacy row", async () => {+ // getStoredChatThread re-imports the Dexie row when the backend has none, which is the very+ // case a source deleted on another device produces. A 404 has to stay a "no" through it.+ const { module } = harness(null, {+ legacyThreads: {+ src: { id: "src", title: "Deleted elsewhere", modelType: "base", createdAt: 1 },+ },+ });++ assert.equal(await module.readBackendChatThread("src"), null);+});++test("a source the backend still holds comes back as its record", async () => {+ // The record, not a boolean: the backlink reads pairId off it to reopen a comparison+ // as a comparison rather than as one of its panes.+ const { module } = harness({ id: "src", pairId: "pair-1" });++ assert.deepEqual(await module.readBackendChatThread("src"), {+ id: "src",+ pairId: "pair-1",+ });+});++test("a backend that could not answer is not a deletion", async () => {+ const { module } = harness(undefined, { failReadsFrom: 1 });++ // Undefined, not false: the divider navigates rather than claiming the chat is gone.+ assert.equal(await module.readBackendChatThread("src"), undefined);+});++test("a source this tab deleted needs no round trip", async () => {+ const { module, threadReads } = harness(+ { id: "src" },+ { deletedSources: new Set(["src"]) },+ );++ assert.equal(await module.readBackendChatThread("src"), null);+ assert.deepEqual(threadReads, []);+});++test("a failed thread read leaves the delete alone", async () => {+ // The row ensure reads first and must succeed; the boundary's read is the one that fails.+ const { module, published } = harness(undefined, { failReadsFrom: 2 });++ // The messages are already pruned; losing the divider until reopen beats failing the delete.+ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, []);+});++// --- two reads that disagree about the anchor ---------------------------------++test("an anchor the message list cannot place is re-read, not treated as gone", async () => {+ // The thread and the messages are read in parallel: another tab deleted "m2" between them,+ // so the thread still names it while the list already reflects the prune.+ const { module, published } = harness(undefined, {+ syncedMessages: [+ { id: "m0", parentId: null },+ { id: "m1", parentId: "m0" },+ ],+ threadReadQueue: [+ // the row ensure+ { id: "fork-1", forkBoundaryMessageId: "m2", forkedFromThreadId: "src" },+ // the stale half this publish is handed+ { id: "fork-1", forkBoundaryMessageId: "m2", forkedFromThreadId: "src" },+ // the re-read, now no earlier than the messages: the backend has reseated it+ { id: "fork-1", forkBoundaryMessageId: "m1", forkedFromThreadId: "src" },+ ],+ });++ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, [["fork-1", ["m1", "m0"], "src"]]);+});++test("an anchor still unplaceable after the re-read leaves the divider alone", async () => {+ // The messages are the older half this time, so the next load settles it. Blanking the+ // divider now would lose it until the chat is reopened.+ const { module, published } = harness(undefined, {+ syncedMessages: [{ id: "m0", parentId: null }],+ threadReadQueue: [+ { id: "fork-1", forkBoundaryMessageId: "m9", forkedFromThreadId: "src" },+ { id: "fork-1", forkBoundaryMessageId: "m9", forkedFromThreadId: "src" },+ { id: "fork-1", forkBoundaryMessageId: "m9", forkedFromThreadId: "src" },+ ],+ });++ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, []);+});++test("a boundary the backend really did clear still clears", async () => {+ // Null is the backend saying there is no inherited history left, not two reads disagreeing.+ const { module, published } = harness({+ id: "fork-1",+ forkBoundaryMessageId: null,+ forkedFromThreadId: "src",+ });++ await module.syncStoredChatMessages("fork-1", [], { pruneMissing: true });++ assert.deepEqual(published, [["fork-1", [], "src"]]);+});diff --git a/studio/frontend/tests/fork-boundary.test.ts b/studio/frontend/tests/fork-boundary.test.tsnew file mode 100644index 00000000000..07067465ab3--- /dev/null+++ b/studio/frontend/tests/fork-boundary.test.ts@@ -0,0 +1,272 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The store behind the "Continued from chat" divider, plus the JSX wiring that reads it.+// The store is plain .ts, so those claims run the code. thread.tsx is .tsx and this runner+// cannot execute JSX, so its claims go through the TypeScript AST rather than a substring+// of the source: a substring passes on broken code and fails on a reformat.++import assert from "node:assert/strict";+import test from "node:test";++import ts from "typescript";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { useForkBoundaryStore, setForkBoundary, forkBoundaryAnchor } =+ await import("../src/features/chat/stores/fork-boundary-store.ts");++const reset = () =>+ useForkBoundaryStore.setState(+ { boundaryByThreadId: {}, anchorByThreadId: {} },+ false,+ );++const ids = (threadId: string) => [+ ...(useForkBoundaryStore.getState().boundaryByThreadId[threadId]?.messageIds ??+ []),+];++test("a thread with no boundary published has none", () => {+ reset();+ assert.equal(+ useForkBoundaryStore.getState().boundaryByThreadId["missing"],+ undefined,+ );+});++test("a fork's inherited messages and source are kept per thread", () => {+ reset();+ setForkBoundary("fork-a", ["m1", "m2"], "src-a");+ setForkBoundary("fork-b", ["m9"], "src-b");+ const { boundaryByThreadId } = useForkBoundaryStore.getState();+ assert.deepEqual(ids("fork-a"), ["m1", "m2"]);+ assert.equal(boundaryByThreadId["fork-a"].sourceThreadId, "src-a");+ assert.deepEqual(ids("fork-b"), ["m9"]);+ assert.equal(boundaryByThreadId["fork-b"].sourceThreadId, "src-b");+});++test("an omitted source leaves the divider without a link", () => {+ reset();+ setForkBoundary("t", ["msg-1"]);+ assert.equal(+ useForkBoundaryStore.getState().boundaryByThreadId["t"].sourceThreadId,+ null,+ );+});++test("an empty set clears the entry, so a chat with nothing inherited shows no divider", () => {+ reset();+ setForkBoundary("t", ["msg-1"]);+ setForkBoundary("t", []);+ assert.equal(useForkBoundaryStore.getState().boundaryByThreadId["t"], undefined);+});++test("null and undefined clear the entry, so a plain chat shows no divider", () => {+ reset();+ setForkBoundary("t", ["msg-1"]);+ setForkBoundary("t", null);+ assert.equal(useForkBoundaryStore.getState().boundaryByThreadId["t"], undefined);+ setForkBoundary("t", ["msg-1"]);+ setForkBoundary("t", undefined);+ assert.equal(useForkBoundaryStore.getState().boundaryByThreadId["t"], undefined);+});++test("republishing the same boundary keeps the identity, so rows do not re-render", () => {+ reset();+ setForkBoundary("t", ["msg-1", "msg-2"], "src");+ const first = useForkBoundaryStore.getState().boundaryByThreadId;+ // A fresh Set with the same members is the same boundary, so identity has to survive it.+ setForkBoundary("t", ["msg-1", "msg-2"], "src");+ assert.equal(useForkBoundaryStore.getState().boundaryByThreadId, first);+ // A message gone from the set is a real change, and so is a deleted source.+ setForkBoundary("t", ["msg-1"], "src");+ assert.notEqual(useForkBoundaryStore.getState().boundaryByThreadId, first);+ setForkBoundary("t", ["msg-1", "msg-2"], "src");+ const second = useForkBoundaryStore.getState().boundaryByThreadId;+ setForkBoundary("t", ["msg-1", "msg-2"], null);+ assert.notEqual(useForkBoundaryStore.getState().boundaryByThreadId, second);+ assert.notEqual(useForkBoundaryStore.getState().boundaryByThreadId, first);+});++test("clearing a thread that has no entry keeps the identity", () => {+ reset();+ const first = useForkBoundaryStore.getState().boundaryByThreadId;+ setForkBoundary("never-set", null);+ assert.equal(useForkBoundaryStore.getState().boundaryByThreadId, first);+});++// --- the wiring in thread.tsx -------------------------------------------------++const threadSource = readSrc("components/assistant-ui/thread.tsx");+const sourceFile = ts.createSourceFile(+ "thread.tsx",+ threadSource,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);++function findDeclaration(name: string): ts.VariableDeclaration {+ let found: ts.VariableDeclaration | undefined;+ const walk = (node: ts.Node) => {+ if (+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.name.text === name+ ) {+ found = node;+ }+ ts.forEachChild(node, walk);+ };+ ts.forEachChild(sourceFile, walk);+ assert.ok(found, `${name} should be declared in thread.tsx`);+ return found;+}++test("ThreadMessage renders the divider after every message kind", () => {+ const text = findDeclaration("ThreadMessage").getText();+ assert.match(text, /<ForkContinuationRule \/>/);+ // After the body, so the rule closes the inherited history rather than heading it.+ const body = text.indexOf("{body}");+ assert.ok(body >= 0, "ThreadMessage should render the message body");+ assert.ok(+ body < text.indexOf("<ForkContinuationRule />"),+ "the rule should follow the message body",+ );+});++test("the divider is gated on the anchor the tracker resolved", () => {+ const text = findDeclaration("ForkContinuationRule").getText();+ assert.match(text, /useForkBoundaryStore/);+ // Nothing at all when this is not the anchor row.+ assert.match(+ text,+ /if \(anchor === undefined \|\| anchor !== messageId\) return null;/,+ );+ assert.match(text, /anchorByThreadId\[threadId\]/);+ assert.match(text, /Continued from chat/);+});++test("only the tracker selects the message array, never a row", () => {+ // Selecting it per row is what the delete render budget forbids: one delete would+ // re-render every message in the thread along with its action bar.+ const rule = findDeclaration("ForkContinuationRule").getText();+ assert.doesNotMatch(rule, /thread\.messages/);+ const tracker = findDeclaration("useTrackForkBoundaryAnchor").getText();+ assert.match(tracker, /useAuiState\(\(\{ thread \}\) =>/);+ assert.match(tracker, /forkBoundaryAnchor\(thread\.messages, inherited\)/);+ assert.match(tracker, /setForkBoundaryAnchor\(threadId, anchor\)/);+ // Mounted once for the thread, not inside the row slot.+ assert.match(+ threadSource,+ /useTrackForkBoundaryAnchor\(threadId\);/,+ );+});++test("a thread with no active id never claims a boundary", () => {+ const text = findDeclaration("ForkContinuationRule").getText();+ assert.match(text, /threadId === null \? undefined/);+});++test("the label links back to the source chat, and only while there is one", () => {+ const text = findDeclaration("ForkContinuationRule").getText();+ // Same navigation the fork action itself uses.+ assert.match(text, /to: "\/chat",/);+ assert.match(text, /\{ thread: sourceThreadId \}/);+ // A paired source reopens as the comparison it was forked from, not as one of its panes.+ assert.match(text, /source\?\.pairId\s*\?\s*\{ compare: source\.pairId \}/);+ // The local tombstone set is this tab's own, so existence is settled on the way out, and+ // against the backend: getStoredChatThread answers with this browser's legacy row instead.+ assert.match(text, /await readBackendChatThread\(sourceThreadId\)/);+ assert.doesNotMatch(text, /getStoredChatThread/);+ // Only a definite null stops the trip; undefined means the backend could not say, and+ // falls through to the single-chat view rather than claiming a deletion.+ assert.match(text, /source === null\) \{[^}]*toast\.info/s);+ assert.match(text, /sourceThreadId \? \(/);+ // A deleted source keeps the words but drops the button.+ assert.match(text, /<span className=\{labelClass\}>\{label\}<\/span>/);+ // A button, not an anchor: it is in-app navigation, not a URL.+ assert.match(text, /<button\n?\s*type="button"/);+});++// --- which inherited message closes the history, per branch ---------------------++const row = (id: string, role: "user" | "assistant" | "system" = "user") => ({+ id,+ role,+});++test("the divider follows the last inherited message on the branch", () => {+ const inherited = new Set(["m1", "m2", "m3", "m4"]);+ assert.equal(+ forkBoundaryAnchor([row("m1"), row("m2", "assistant"), row("m3"), row("m4", "assistant")], inherited),+ "m4",+ );+ // New turns after the fork do not move it.+ assert.equal(+ forkBoundaryAnchor(+ [row("m1"), row("m2", "assistant"), row("m3"), row("m4", "assistant"), row("n1"), row("n2", "assistant")],+ inherited,+ ),+ "m4",+ );+});++test("editing an inherited message moves the divider up, it does not lose it", () => {+ // assistant-ui keeps the originals and selects a sibling branch, so m3 and m4 are off+ // screen while m1 and m2 are still inherited and visible.+ const inherited = new Set(["m1", "m2", "m3", "m4"]);+ assert.equal(+ forkBoundaryAnchor(+ [row("m1"), row("m2", "assistant"), row("m3-edited"), row("a-new", "assistant")],+ inherited,+ ),+ "m2",+ );+ // Switching back to the original branch restores it, which one stored id cannot do.+ assert.equal(+ forkBoundaryAnchor([row("m1"), row("m2", "assistant"), row("m3"), row("m4", "assistant")], inherited),+ "m4",+ );+});++test("editing the first inherited message leaves no divider", () => {+ // Nothing inherited survives on this branch, so there is no history to close.+ assert.equal(+ forkBoundaryAnchor([row("m1-edited"), row("a-new", "assistant")], new Set(["m1", "m2"])),+ undefined,+ );+});++test("the divider never lands on a message that paints no row", () => {+ // A system message renders as nothing, so it cannot carry the rule.+ assert.equal(+ forkBoundaryAnchor([row("m1"), row("m2", "assistant"), row("m3", "system")], new Set(["m1", "m2", "m3"])),+ "m2",+ );+});++test("a thread with nothing inherited has no anchor", () => {+ assert.equal(forkBoundaryAnchor([row("m1")], undefined), undefined);+ assert.equal(forkBoundaryAnchor([row("m1")], new Set()), undefined);+});++test("the walk stops at the divergence rather than scanning the thread", () => {+ const inherited = new Set(["m1"]);+ let seen = 0;+ const messages = Array.from({ length: 500 }, (_, i) => ({+ get id() {+ seen += 1;+ return i === 0 ? "m1" : `n${i}`;+ },+ role: "user" as const,+ }));++ assert.equal(forkBoundaryAnchor(messages, inherited), "m1");+ // The inherited chain is a prefix, so a fork whose history has grown long does not pay+ // for the whole array on every store notification.+ assert.ok(seen <= 4, `walked ${seen} ids`);+});diff --git a/studio/frontend/tests/legacy-chat-store-timeout.test.ts b/studio/frontend/tests/legacy-chat-store-timeout.test.tsindex 5ed7e5fcce0..744151b13d8 100644--- a/studio/frontend/tests/legacy-chat-store-timeout.test.ts+++ b/studio/frontend/tests/legacy-chat-store-timeout.test.ts@@ -77,6 +77,7 @@ function loadStorage(options: {"./thread-record-write-coordinator": {ThreadRecordWriteCoordinator: StubWriteCoordinator,},+ "../stores/fork-boundary-store": { setForkBoundary: () => {} },},);}diff --git a/studio/frontend/tests/studio-backup-import.test.ts b/studio/frontend/tests/studio-backup-import.test.tsindex 4dfea065519..cee91339162 100644--- a/studio/frontend/tests/studio-backup-import.test.ts+++ b/studio/frontend/tests/studio-backup-import.test.ts@@ -138,6 +138,8 @@ function backup() {updatedAt: 2100,forkedFromThreadId: "t1",forkedFromMessageId: "m2",+ forkBoundaryMessageId: "m5",+ forkTitleBase: "Recipe",},];const messages: MessageRecord[] = [@@ -202,6 +204,12 @@ test("a Studio backup restores one chat per thread, with titles, branches, archiassert.equal(recipeMessages[1].parentId, recipeMessages[0].id);assert.equal(recipe.forkedFromThreadId, trip.id);assert.equal(recipe.forkedFromMessageId, tripMessages[1].id);+ // The divider's anchor is one of this thread's own messages, so it remaps to the new id.+ assert.equal(recipe.forkBoundaryMessageId, recipeMessages[1].id);+ assert.notEqual(recipe.forkBoundaryMessageId, "m5");+ // A name rather than an id, so it restores as it stands and the next fork of this one+ // is numbered rather than suffixed again.+ assert.equal(recipe.forkTitleBase, "Recipe");});test("importing the same backup twice reuses the project and never reuses a thread or message id", async () => {diff --git a/studio/frontend/tests/thread-delete-render-budget.test.ts b/studio/frontend/tests/thread-delete-render-budget.test.tsindex 5a1567610b5..8933a82054c 100644--- a/studio/frontend/tests/thread-delete-render-budget.test.ts+++ b/studio/frontend/tests/thread-delete-render-budget.test.ts@@ -51,10 +51,13 @@ test("the render prop is built once, at module scope", () => {test("ThreadMessage sends each kind to the component that names it", () => {const body = block("const ThreadMessage: FC = () => {");assert.match(body, /threadMessageKind\(role, isEditing\)/);- assert.match(body, /case "edit":\s*return <EditComposer \/>;/);- assert.match(body, /case "user":\s*return <UserMessage \/>;/);- assert.match(body, /case "assistant":\s*return <AssistantMessage \/>;/);+ // The kind picks the component; the row renders it below, followed by the fork divider.+ assert.match(body, /case "edit":\s*body = <EditComposer \/>;/);+ assert.match(body, /case "user":\s*body = <UserMessage \/>;/);+ assert.match(body, /case "assistant":\s*body = <AssistantMessage \/>;/);+ // An unknown kind renders nothing at all, divider included.assert.match(body, /default:\s*return null;/);+ assert.match(body, /\{body\}\s*<ForkContinuationRule \/>/);});test("research-reply ownership is selected as an answer, not as the message list", () => {diff --git a/studio/frontend/tests/thread-message-slot.test.ts b/studio/frontend/tests/thread-message-slot.test.tsindex bc20c2364bb..63f18428b21 100644--- a/studio/frontend/tests/thread-message-slot.test.ts+++ b/studio/frontend/tests/thread-message-slot.test.ts@@ -16,6 +16,7 @@ import { createElement } from "react";import {proplessSlot,+ rendersAsRow,threadMessageKind,} from "../src/components/assistant-ui/thread-message-slot.ts";@@ -38,6 +39,16 @@ test("a system message that is not being edited renders nothing", () => {assert.equal(threadMessageKind("system", false), "none");});+test("user and assistant are the only roles that paint a row", () => {+ // storage/studio_db.py keeps the same pair, to anchor a fork's "Continued from chat" divider+ // to a row that actually mounts. Giving another role a body means updating it there too.+ const roles = ["user", "assistant", "system"] as const;+ assert.deepEqual(+ roles.filter((role) => rendersAsRow(role, false)),+ ["user", "assistant"],+ );+});+test("the slot hands back one shared element rather than a new one per render", () => {const Component = () => null;const slot = proplessSlot(Component);