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
Studio: per-chat file history and /rewind (#13522)
Daniel Han2a98c54accb8
diff --git a/studio/backend/core/inference/file_history.py b/studio/backend/core/inference/file_history.pynew file mode 100644index 00000000000..51f31dbb173--- /dev/null+++ b/studio/backend/core/inference/file_history.py@@ -0,0 +1,790 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Per-chat history of the files tool calls change, so /rewind can put them back.++Blobs are content addressed under the account's ``file_history/objects`` and indexed in a SQLite+file next to them (WAL, one short transaction per tool call, always on the tool's worker thread,+never the event loop). The index keeps the last stored image of every file in a folder, so the+image a python or terminal call overwrites is already stored when the call starts: the stat walk+those tools already take is diffed against it, and only files whose (mtime, size) moved are read.++Execution state is not tracked: processes, installed packages and anything outside the chat's+folder stay as they are after a rewind.+"""++from __future__ import annotations++import hashlib+import logging+import os+import sqlite3+import stat as stat_mod+import threading+import time+import uuid+import zlib+from contextvars import ContextVar+from dataclasses import dataclass, field+from typing import Iterable, Optional++logger = logging.getLogger(__name__)++try:+ import zstandard as _zstandard+ _ZSTD_C = _zstandard.ZstdCompressor(level = 1)+ _ZSTD_D = _zstandard.ZstdDecompressor()+except ImportError:+ _ZSTD_C = _ZSTD_D = None++_RAW, _ZLIB, _ZSTD = b"R", b"Z", b"S"++MAX_FILE_BYTES = 16 << 20+BASELINE_BUDGET_BYTES = 256 << 20+CALL_BUDGET_BYTES = 256 << 20+CHAT_CAP_CHECKPOINTS = 500+GLOBAL_CAP_BYTES = 2 << 30+GC_AFTER_BYTES = 128 << 20+# Studio's own trees inside a chat folder: content addressed copies, the scratch dir, spilled output.+_SKIP_PREFIXES = (".unsloth_attachments/", "unsloth-tmp/", ".unsloth_tool_output/")++# (thread_id, user_message_id) of the turn being served, set once per chat request.+_TURN: ContextVar = ContextVar("unsloth_file_history_turn", default = None)++_SCHEMA = """+CREATE TABLE IF NOT EXISTS blobs(+ hash TEXT PRIMARY KEY, size INTEGER NOT NULL, stored INTEGER NOT NULL, created_at REAL NOT NULL);+CREATE TABLE IF NOT EXISTS checkpoints(+ id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id TEXT, workdir TEXT NOT NULL, turn_id TEXT,+ kind TEXT NOT NULL, ambiguous INTEGER NOT NULL DEFAULT 0, created_at REAL NOT NULL);+CREATE INDEX IF NOT EXISTS ck_chat ON checkpoints(chat_id, turn_id);+CREATE TABLE IF NOT EXISTS file_versions(+ checkpoint_id INTEGER NOT NULL REFERENCES checkpoints(id) ON DELETE CASCADE,+ rel_path TEXT NOT NULL, before_kind TEXT NOT NULL, before_blob TEXT, before_mode INTEGER,+ after_kind TEXT NOT NULL, after_blob TEXT, after_mode INTEGER,+ PRIMARY KEY(checkpoint_id, rel_path));+CREATE INDEX IF NOT EXISTS fv_before ON file_versions(before_blob);+CREATE INDEX IF NOT EXISTS fv_after ON file_versions(after_blob);+CREATE TABLE IF NOT EXISTS workdir_state(+ workdir TEXT NOT NULL, rel_path TEXT NOT NULL, mtime_ns INTEGER, size INTEGER, digest TEXT,+ kind TEXT NOT NULL, blob TEXT, mode INTEGER, PRIMARY KEY(workdir, rel_path));+CREATE INDEX IF NOT EXISTS ws_blob ON workdir_state(blob);+CREATE TABLE IF NOT EXISTS workdirs(workdir TEXT PRIMARY KEY, baseline_at REAL);+CREATE TABLE IF NOT EXISTS chat_workdirs(chat_id TEXT NOT NULL, workdir TEXT NOT NULL,+ PRIMARY KEY(chat_id, workdir));+"""+++class RewindBusy(RuntimeError):+ """A tool call is running in the folder, or another restore is."""+++@dataclass+class _Entry:+ mtime_ns: int+ size: int+ digest: Optional[str]+ kind: str # "blob" or "untracked" (over the size cap or budget, or unreadable)+ blob: Optional[str]+ mode: Optional[int]+++@dataclass+class CallToken:+ chat_id: str+ workdir: str+ turn_id: str+ ambiguous: bool = False+ done: bool = False+++@dataclass+class RewindReport:+ has_changes: bool = False+ restored: list = field(default_factory = list)+ deleted: list = field(default_factory = list)+ recreated: list = field(default_factory = list)+ conflicts: list = field(default_factory = list)+ untracked: list = field(default_factory = list)+ errors: list = field(default_factory = list)+ undo_turn_id: Optional[str] = None++ def as_dict(self) -> dict:+ return {+ "has_changes": self.has_changes,+ "restored": self.restored,+ "deleted": self.deleted,+ "recreated": self.recreated,+ "conflicts": self.conflicts,+ "untracked": self.untracked,+ "errors": self.errors,+ "undo_turn_id": self.undo_turn_id,+ }+++def set_turn(thread_id: Optional[str], user_message_id: Optional[str]) -> None:+ """Record which chat turn this request serves. Without both ids nothing is captured."""+ _TURN.set((thread_id, user_message_id) if thread_id and user_message_id else None)+++def current_turn() -> Optional[tuple]:+ return _TURN.get()+++def tracked(rel: str, exclude: "Iterable[str]") -> bool:+ return not rel.startswith(_SKIP_PREFIXES) and rel not in exclude+++def _key(snap_value) -> tuple:+ # (mtime_ns, size, digest) as `_snapshot_workdir_files` records it; the digest is None off FAT-like volumes.+ return (snap_value[0], snap_value[1], snap_value[2] if len(snap_value) > 2 else None)+++class FileHistory:+ """One per account. Every method is blocking: call it from a worker thread."""++ def __init__(self, root: str):+ self.root = root+ self.objects = os.path.join(root, "objects")+ os.makedirs(os.path.join(self.objects, "tmp"), exist_ok = True)+ self._db = sqlite3.connect(+ os.path.join(root, "index.sqlite"), check_same_thread = False, isolation_level = None+ )+ self._db.execute("PRAGMA journal_mode=WAL")+ self._db.execute("PRAGMA synchronous=NORMAL")+ self._db.execute("PRAGMA foreign_keys=ON")+ self._db.executescript(_SCHEMA)+ self._lock = threading.RLock()+ self._state: dict = {} # workdir -> rel -> _Entry, write-through cache of workdir_state+ self._active: dict = {} # workdir -> [CallToken]+ self._restoring: set = set()+ self._since_gc = 0+ self._added = 0 # bytes stored since the last gc++ # Blobs++ def _blob_path(self, digest: str) -> str:+ return os.path.join(self.objects, digest[:2], digest[2:])++ def _put_blob(self, data: bytes) -> str:+ digest = hashlib.sha256(data).hexdigest()+ path = self._blob_path(digest)+ try:+ stored = os.path.getsize(path)+ except OSError:+ stored = None+ if stored is not None:+ # The row too: one lost to a crash or a rolled-back call would leave the file uncounted.+ self._db.execute(+ "INSERT OR IGNORE INTO blobs VALUES(?,?,?,?)",+ (digest, len(data), stored, time.time()),+ )+ return digest+ probe = data[: 64 << 10]+ if _ZSTD_C is not None:+ codec, compress = _ZSTD, _ZSTD_C.compress+ else:+ codec, compress = _ZLIB, lambda chunk: zlib.compress(chunk, 1)+ # Weights and archives do not compress: a probe keeps them from paying for the attempt.+ if probe and len(compress(probe)) < 0.9 * len(probe):+ payload = codec + compress(data)+ else:+ payload = _RAW + data+ os.makedirs(os.path.dirname(path), exist_ok = True)+ tmp = os.path.join(self.objects, "tmp", uuid.uuid4().hex)+ with open(tmp, "wb") as fh:+ fh.write(payload)+ os.replace(tmp, path)+ self._db.execute(+ "INSERT OR IGNORE INTO blobs VALUES(?,?,?,?)",+ (digest, len(data), len(payload), time.time()),+ )+ self._added += len(payload)+ return digest++ def _get_blob(self, digest: str) -> bytes:+ with open(self._blob_path(digest), "rb") as fh:+ payload = fh.read()+ codec, body = payload[:1], payload[1:]+ try:+ if codec == _ZLIB:+ data = zlib.decompress(body)+ elif codec == _ZSTD:+ if _ZSTD_D is None:+ raise OSError("this file was stored with zstd, which is not installed")+ data = _ZSTD_D.decompress(body)+ else:+ data = body+ except OSError:+ raise+ except Exception as exc: # zlib.error, zstd.ZstdError: one file's error, not the rewind's+ raise OSError("stored copy is damaged") from exc+ # A torn write after a crash is reported, never restored.+ if hashlib.sha256(data).hexdigest() != digest:+ raise OSError("stored copy is damaged")+ return data++ # Known state++ def _load_state(self, workdir: str) -> dict:+ state = self._state.get(workdir)+ if state is None:+ state = {+ row[0]: _Entry(*row[1:])+ for row in self._db.execute(+ "SELECT rel_path, mtime_ns, size, digest, kind, blob, mode FROM workdir_state WHERE workdir=?",+ (workdir,),+ )+ }+ self._state[workdir] = state+ return state++ def _capture(self, workdir: str, rel: str, key: tuple, budget: Optional[list]) -> _Entry:+ mtime_ns, size, digest = key+ data, mode = None, None+ if size <= MAX_FILE_BYTES and (budget is None or budget[0] >= size):+ try:+ fd = os.open(+ os.path.join(workdir, rel),+ os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0),+ )+ with os.fdopen(fd, "rb") as fh:+ mode = stat_mod.S_IMODE(os.fstat(fh.fileno()).st_mode)+ data = fh.read(MAX_FILE_BYTES + 1)+ except OSError:+ data = None+ if data is None or len(data) > MAX_FILE_BYTES:+ return _Entry(mtime_ns, size, digest, "untracked", None, mode)+ if budget is not None:+ budget[0] -= len(data)+ return _Entry(mtime_ns, size, digest, "blob", self._put_blob(data), mode)++ def _sync(+ self,+ workdir: str,+ snap: dict,+ paths: Optional[set] = None,+ complete: bool = True,+ ) -> dict:+ """Bring the known state up to ``snap``: rel -> (old, new), either side None when absent.+ ``paths`` limits the sync to those names (edit_file knows its one file); ``complete`` says+ whether a name missing from ``snap`` is really gone (a capped walk cannot say so)."""+ state = self._load_state(workdir)+ first = (+ not state+ and self._db.execute("SELECT 1 FROM workdirs WHERE workdir=?", (workdir,)).fetchone()+ is None+ )+ # Per sync, not only the baseline: one call writing thousands of large files must not copy them all.+ budget = [BASELINE_BUDGET_BYTES if first else CALL_BUDGET_BYTES]+ changes: dict = {}+ names = snap.keys() if first or paths is None else paths+ for rel in names:+ if rel not in snap:+ continue+ key = _key(snap[rel])+ old = state.get(rel)+ if old is not None and (old.mtime_ns, old.size, old.digest) == key:+ continue+ new = self._capture(workdir, rel, key, budget)+ if old is not None and old.kind == new.kind == "blob" and old.blob == new.blob:+ old.mtime_ns, old.digest, old.mode = new.mtime_ns, new.digest, new.mode+ self._db.execute(+ "UPDATE workdir_state SET mtime_ns=?, digest=?, mode=? WHERE workdir=? AND rel_path=?",+ (new.mtime_ns, new.digest, new.mode, workdir, rel),+ )+ continue+ changes[rel] = (old, new)+ gone = (paths or set()) if paths is not None else (state.keys() if complete else ())+ for rel in [r for r in gone if r in state and r not in snap]:+ changes[rel] = (state[rel], None)+ for rel, (_old, new) in changes.items():+ if new is None:+ state.pop(rel, None)+ self._db.execute(+ "DELETE FROM workdir_state WHERE workdir=? AND rel_path=?", (workdir, rel)+ )+ else:+ state[rel] = new+ self._db.execute(+ "INSERT OR REPLACE INTO workdir_state VALUES(?,?,?,?,?,?,?,?)",+ (+ workdir,+ rel,+ new.mtime_ns,+ new.size,+ new.digest,+ new.kind,+ new.blob,+ new.mode,+ ),+ )+ if first:+ self._db.execute("INSERT OR IGNORE INTO workdirs VALUES(?,?)", (workdir, time.time()))+ return {} # the baseline is where history starts, not a change+ return changes++ def _walk_sync(self, workdir: str, walk) -> dict:+ snap, complete = walk(workdir)+ return self._sync(workdir, snap, None, complete)++ def _record(+ self,+ chat_id,+ workdir,+ turn_id,+ kind,+ changes,+ ambiguous = False,+ ) -> Optional[int]:+ if not changes:+ return None+ cur = self._db.execute(+ "INSERT INTO checkpoints(chat_id, workdir, turn_id, kind, ambiguous, created_at) VALUES(?,?,?,?,?,?)",+ (chat_id, workdir, turn_id, kind, int(ambiguous), time.time()),+ )+ rows = []+ for rel, (old, new) in changes.items():+ rows.append(+ (+ cur.lastrowid,+ rel,+ "absent" if old is None else old.kind,+ old.blob if old else None,+ old.mode if old else None,+ "absent" if new is None else new.kind,+ new.blob if new else None,+ new.mode if new else None,+ )+ )+ self._db.executemany("INSERT INTO file_versions VALUES(?,?,?,?,?,?,?,?)", rows)+ return cur.lastrowid++ def _transaction(self, workdir: str, body):+ self._db.execute("BEGIN")+ try:+ result = body()+ self._db.execute("COMMIT")+ return result+ except BaseException:+ self._db.execute("ROLLBACK")+ self._state.pop(workdir, None) # rebuilt from the index on next use+ raise++ def needs_baseline(self, workdir: str) -> bool:+ workdir = os.path.realpath(workdir)+ with self._lock:+ return (+ not self._load_state(workdir)+ and self._db.execute(+ "SELECT 1 FROM workdirs WHERE workdir=?", (workdir,)+ ).fetchone()+ is None+ )++ # Hooks around a tool call++ def begin(+ self,+ chat_id,+ workdir,+ turn_id,+ snap,+ paths = None,+ complete = True,+ ) -> CallToken:+ workdir = os.path.realpath(workdir)+ with self._lock:+ if workdir in self._restoring:+ raise RewindBusy("a rewind is running in this folder")+ token = CallToken(chat_id, workdir, turn_id)+ running = self._active.setdefault(workdir, [])++ def body():+ # Kept even when the call changes nothing: deleting the chat releases its folder's images.+ self._db.execute(+ "INSERT OR IGNORE INTO chat_workdirs VALUES(?,?)", (chat_id, workdir)+ )+ changes = self._sync(workdir, snap, paths, complete)+ if running:+ # Another chat's call is writing this folder right now: its writes cannot be told+ # apart from ours, so they go to the call that started first and both are flagged.+ owner = running[0]+ owner.ambiguous = token.ambiguous = True+ self._record(owner.chat_id, workdir, owner.turn_id, "tool", changes, True)+ else:+ self._record(None, workdir, None, "external", changes)++ self._transaction(workdir, body)+ running.append(token)+ return token++ def end(+ self,+ token: CallToken,+ snap,+ paths = None,+ complete = True,+ ) -> Optional[int]:+ if token.done:+ return None+ token.done = True+ with self._lock:+ try:+ checkpoint = self._transaction(+ token.workdir,+ lambda: self._record(+ token.chat_id,+ token.workdir,+ token.turn_id,+ "tool",+ self._sync(token.workdir, snap, paths, complete),+ token.ambiguous,+ ),+ )+ finally:+ running = self._active.get(token.workdir, [])+ if token in running:+ running.remove(token)+ if not running:+ self._active.pop(token.workdir, None)+ if checkpoint is not None:+ self._trim_chat(token.chat_id)+ return checkpoint++ # Rewind++ def rewind(+ self,+ chat_id,+ turn_ids,+ walk,+ *,+ dry_run = False,+ force = False,+ busy = None,+ ) -> RewindReport:+ """Put the files ``chat_id`` changed during ``turn_ids`` back to how they were before the+ first of those turns touched them. ``walk(workdir)`` returns a fresh ``(snapshot, complete)``. Only files+ this chat changed are touched; one changed since by anything else is skipped as a conflict."""+ report = RewindReport()+ turn_ids = [t for t in dict.fromkeys(turn_ids) if t]+ if not turn_ids:+ return report+ with self._lock:+ marks = ",".join("?" * len(turn_ids))+ rows = self._db.execute(+ "SELECT c.workdir, fv.rel_path, fv.before_kind, fv.before_blob, fv.before_mode, c.ambiguous"+ " FROM file_versions fv"+ f" JOIN checkpoints c ON c.id=fv.checkpoint_id WHERE c.chat_id=? AND c.turn_id IN ({marks})"+ " ORDER BY c.id",+ (chat_id, *turn_ids),+ ).fetchall()+ if not rows:+ return report+ report.has_changes = True+ workdirs = sorted({row[0] for row in rows})+ for workdir in workdirs:+ if (+ self._active.get(workdir)+ or workdir in self._restoring+ or (busy and busy(workdir))+ ):+ raise RewindBusy("a tool call is running in this chat's folder")+ if not dry_run:+ self._restoring.update(workdirs)+ undo_turn = f"rewind:{uuid.uuid4().hex}"+ try:+ for workdir in workdirs:+ self._rewind_folder(chat_id, workdir, rows, walk, report, dry_run, force, undo_turn)+ finally:+ if not dry_run:+ with self._lock:+ self._restoring.difference_update(workdirs)+ if not dry_run and (report.restored or report.deleted or report.recreated):+ report.undo_turn_id = undo_turn+ return report++ def _rewind_folder(self, chat_id, workdir, rows, walk, report, dry_run, force, undo_turn):+ with self._lock:+ # Edits made since the last call (by the user, or another chat) are stored first, so the+ # rewind can tell them apart from this chat's own and they stay restorable too.+ self._transaction(+ workdir,+ lambda: self._record(+ None, workdir, None, "external", self._walk_sync(workdir, walk)+ ),+ )+ target: dict = {}+ # Written while another chat's call ran in this folder: either chat's, so never ours to undo.+ shared = set()+ for wd, rel, kind, blob, mode, ambiguous in rows:+ if wd == workdir:+ target.setdefault(rel, (kind, blob, mode))+ if ambiguous:+ shared.add(rel)+ last_after = {+ row[0]: (row[1], row[2])+ for row in self._db.execute(+ "SELECT fv.rel_path, fv.after_kind, fv.after_blob FROM file_versions fv"+ " JOIN checkpoints c ON c.id=fv.checkpoint_id WHERE c.chat_id=? AND c.workdir=? ORDER BY c.id",+ (chat_id, workdir),+ )+ }+ state = dict(self._load_state(workdir))+ for rel in sorted(target):+ kind, blob, mode = target[rel]+ current = state.get(rel)+ now = ("absent", None) if current is None else (current.kind, current.blob)+ if kind == "untracked" or now[0] == "untracked":+ report.untracked.append(rel)+ continue+ if now == (kind, blob):+ continue+ if (now != last_after.get(rel) or rel in shared) and not force:+ report.conflicts.append(rel)+ continue+ bucket = (+ report.deleted+ if kind == "absent"+ else report.restored+ if current+ else report.recreated+ )+ if dry_run:+ bucket.append(rel)+ continue+ try:+ if kind == "absent":+ _safe_unlink(workdir, rel)+ else:+ _safe_write(workdir, rel, self._get_blob(blob), mode)+ bucket.append(rel)+ except OSError as exc:+ report.errors.append(f"{rel}: {exc}")+ if dry_run:+ return+ with self._lock:+ self._transaction(+ workdir,+ lambda: self._record(+ chat_id, workdir, undo_turn, "rewind", self._walk_sync(workdir, walk)+ ),+ )++ # Retention++ def _trim_chat(self, chat_id) -> None:+ with self._lock:+ count = self._db.execute(+ "SELECT COUNT(*) FROM checkpoints WHERE chat_id=?", (chat_id,)+ ).fetchone()[0]+ if count > CHAT_CAP_CHECKPOINTS:+ self._db.execute(+ "DELETE FROM checkpoints WHERE id IN"+ " (SELECT id FROM checkpoints WHERE chat_id=? ORDER BY id LIMIT ?)",+ (chat_id, count - CHAT_CAP_CHECKPOINTS),+ )+ self._since_gc += 1+ # By count, or sooner by bytes: a few calls rewriting large files can pass the cap alone.+ if self._since_gc >= 50 or self._added >= GC_AFTER_BYTES:+ self._since_gc = self._added = 0+ self.gc()++ def delete_chat(self, chat_id) -> None:+ with self._lock:+ workdirs = [+ row[0]+ for row in self._db.execute(+ "SELECT workdir FROM chat_workdirs WHERE chat_id=?"+ " UNION SELECT workdir FROM checkpoints WHERE chat_id=?",+ (chat_id, chat_id),+ )+ ]+ self._db.execute("DELETE FROM checkpoints WHERE chat_id=?", (chat_id,))+ self._db.execute("DELETE FROM chat_workdirs WHERE chat_id=?", (chat_id,))+ # A folder no other chat uses keeps no stored images either.+ for workdir in workdirs:+ if (+ workdir not in self._active+ and self._db.execute(+ "SELECT 1 FROM chat_workdirs WHERE workdir=? UNION ALL"+ " SELECT 1 FROM checkpoints WHERE workdir=? AND chat_id IS NOT NULL LIMIT 1",+ (workdir, workdir),+ ).fetchone()+ is None+ ):+ self._forget_workdir(workdir)+ self.gc()++ def _forget_workdir(self, workdir: str) -> None:+ self._db.execute("DELETE FROM checkpoints WHERE workdir=?", (workdir,))+ self._db.execute("DELETE FROM workdir_state WHERE workdir=?", (workdir,))+ self._db.execute("DELETE FROM workdirs WHERE workdir=?", (workdir,))+ self._state.pop(workdir, None)++ def gc(self) -> int:+ """Oldest checkpoints go first while the store is over its cap, then unreferenced blobs."""+ with self._lock:+ self._db.execute(+ "DELETE FROM checkpoints WHERE kind='external' AND id NOT IN (SELECT checkpoint_id FROM file_versions)"+ )+ # Counts history only: images of the files folders hold now cannot be freed by dropping+ # checkpoints, and counting them would drop every checkpoint once they pass the cap.+ while (+ self._db.execute(+ "SELECT COALESCE(SUM(stored),0) FROM blobs b"+ " WHERE NOT EXISTS (SELECT 1 FROM workdir_state WHERE blob=b.hash)"+ ).fetchone()[0]+ > GLOBAL_CAP_BYTES+ ):+ oldest = self._db.execute("SELECT MIN(id) FROM checkpoints").fetchone()[0]+ if oldest is None:+ break+ self._db.execute("DELETE FROM checkpoints WHERE id=?", (oldest,))+ self._sweep()+ return self._sweep()++ def _sweep(self) -> int:+ dead = [+ row[0]+ for row in self._db.execute(+ "SELECT hash FROM blobs b WHERE NOT EXISTS (SELECT 1 FROM workdir_state WHERE blob=b.hash)"+ " AND NOT EXISTS (SELECT 1 FROM file_versions WHERE before_blob=b.hash)"+ " AND NOT EXISTS (SELECT 1 FROM file_versions WHERE after_blob=b.hash)"+ )+ ]+ self._db.executemany("DELETE FROM blobs WHERE hash=?", [(digest,) for digest in dead])+ # After the rows: a crash leaves an orphan file, never a row pointing at nothing.+ for digest in dead:+ try:+ os.unlink(self._blob_path(digest))+ except FileNotFoundError:+ pass+ return len(dead)+++def _resolve_inside(workdir: str, rel: str, create_dirs: bool) -> str:+ parts = rel.split("/")+ if os.path.isabs(rel) or any(part in ("", ".", "..") for part in parts):+ raise OSError("not a path inside the chat's folder")+ # The folder itself too: recorded by its real path, so a link there now leads somewhere else.+ _require_plain_dir(workdir, "the chat's folder")+ current = workdir+ for part in parts[:-1]:+ current = os.path.join(current, part)+ try:+ info = os.lstat(current)+ except FileNotFoundError:+ if not create_dirs:+ raise+ os.mkdir(current)+ continue+ # A parent swapped for a link would carry the write outside the folder.+ _require_plain_dir(current, f"'{part}'", info)+ return os.path.join(current, parts[-1])+++def _require_plain_dir(+ path: str,+ name: str,+ info = None,+) -> None:+ info = os.lstat(path) if info is None else info+ if not stat_mod.S_ISDIR(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:+ raise OSError(f"{name} is no longer a plain folder")+++def _safe_write(workdir: str, rel: str, data: bytes, mode: Optional[int]) -> None:+ path = _resolve_inside(workdir, rel, create_dirs = True)+ tmp = os.path.join(os.path.dirname(path), f".unsloth-rewind-{uuid.uuid4().hex}.tmp")+ flags = (+ os.O_WRONLY+ | os.O_CREAT+ | os.O_EXCL+ | getattr(os, "O_NOFOLLOW", 0)+ | getattr(os, "O_BINARY", 0)+ )+ fd = os.open(tmp, flags, 0o600)+ try:+ with os.fdopen(fd, "wb") as fh:+ fh.write(data)+ if mode is not None:+ os.chmod(tmp, mode)+ if os.path.isfile(path):+ from core.library import replace_file+ replace_file(tmp, path) # carries the Library's name and folder over to the new inode+ else:+ os.replace(tmp, path) # replaces a link at the name, never writes through it+ except BaseException:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+++def _safe_unlink(workdir: str, rel: str) -> None:+ path = _resolve_inside(workdir, rel, create_dirs = False)+ if not stat_mod.S_ISREG(os.lstat(path).st_mode):+ raise OSError("no longer a regular file")+ os.unlink(path)+++_stores: dict = {}+_stores_lock = threading.Lock()+++def close_store(root) -> None:+ """Drop and close an account's history before its folders are moved, since an open+ index blocks the rename on Windows."""+ root = str(root)+ with _stores_lock:+ found = _stores.pop(root, None)+ if found is not None:+ with found._lock:+ found._db.close()+++def store() -> FileHistory:+ """The current account's history."""+ from utils.paths.storage_roots import account_path++ root = str(account_path("file_history"))+ with _stores_lock:+ found = _stores.get(root)+ if found is None:+ found = _stores[root] = FileHistory(root)+ return found+++def begin_call(+ session_id,+ workdir,+ snap,+ paths = None,+ complete = True,+) -> Optional[CallToken]:+ """Start tracking a tool call of the current turn. None, and nothing done, outside a chat turn."""+ turn = _TURN.get()+ if turn is None or not session_id or not workdir:+ return None+ try:+ return store().begin(turn[0], workdir, turn[1], snap, paths, complete)+ except Exception:+ logger.warning("file history: could not start tracking a tool call", exc_info = True)+ return None+++def end_call(+ token: Optional[CallToken],+ snap,+ paths = None,+ complete = True,+) -> None:+ if token is None:+ return+ try:+ store().end(token, snap, paths, complete)+ except Exception:+ logger.warning("file history: could not record a tool call", exc_info = True)diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex dfcee1b83b5..5f003961b9b 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -41,6 +41,7 @@ from contextvars import ContextVar# What a truncated result costs besides its body, charged where the cut is decided rather than held back in advance.from .context_window import _RESULT_NOTICE_RESERVE, compaction_receipt_fieldfrom .browser_agent import BROWSER_TOOL_NAMES, execute_browser_tool, is_browser_tool+from . import file_history# The window of the model THIS request is served by, set by execute_tool for the call's duration. Left unset it falls# back to the process-global probe, which is wrong for an external-provider request: that runs Unsloth's tool loop@@ -12795,14 +12796,24 @@ def _edit_file("""Replace exact strings in a file. See the notes above. The receipt can echo a model-chosen name, so it isdefused before the files row of a created file is appended."""created: "list[str]" = []- text = _defuse_sentinels(_edit_file_apply(arguments, session_id, disable_sandbox, created))+ history: dict = {}+ try:+ text = _defuse_sentinels(+ _edit_file_apply(arguments, session_id, disable_sandbox, created, history)+ )+ finally:+ _history_end_file(history)if session_id and created:text += _edit_file_created_sentinel(created[0], _get_workdir(session_id))return textdef _edit_file_apply(- arguments: dict, session_id: "str | None", disable_sandbox: bool, created: "list[str]"+ arguments: dict,+ session_id: "str | None",+ disable_sandbox: bool,+ created: "list[str]",+ history: "dict | None" = None,) -> str:# The receipt echoes a window of the file back, so an edit is a read, and Bypass Permissions# lifts the containment that would otherwise keep it out.@@ -12822,6 +12833,8 @@ def _edit_file_apply(os.path.realpath(target)):return _STUDIO_CREDENTIAL_BLOCKED+ if history is not None:+ history.update(_history_begin_file(session_id, target))name = os.path.basename(target)# Decided before the no-op check below, not after: both strings empty is the documented way to create __init__.py# or .gitkeep, and read as identical, nothing to change it was refused, leaving no way to write a zero-byte file.@@ -22671,7 +22684,7 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":for base, dirs, names in os.walk(workdir):visited += 1if visited > _MAX_SNAPSHOT_DIRS:- return snapshot+ return _CappedSnapshot(snapshot)# depth 0 is the workdir itself, whose files are one segment.relative = base[len(workdir) :].strip(os.sep)depth = len(_user_path_parts(relative.split(os.sep) if relative else []))@@ -22709,10 +22722,14 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":except OSError:continueif len(snapshot) >= _MAX_SNAPSHOT_FILES:- return snapshot+ return _CappedSnapshot(snapshot)return snapshot+class _CappedSnapshot(dict):+ """A walk cut short by a cap: a file missing from it is not known to be gone."""++# Scratch scripts of calls running right now. Chats in one project share a workdir and each snapshots all of it, so# without this the other call's studio_exec_*.py is offered as this call's file and 404s once it is gone._active_scratch: "set[str]" = set()@@ -22743,6 +22760,9 @@ def _call_finished(token: "dict | None") -> None:"""Drop a call's registration. Its token keeps whatever it learned."""if not token or not token.get("workdir"):return+ if token.get("history") is not None and not token["history"].done:+ # An exit that skipped the file sentinels (a launch error): the folder may still have moved.+ _history_end(token, _snapshot_workdir_files(token["workdir"]))with _calls_lock:running = _workdir_calls.get(token["workdir"])if running is None:@@ -22755,6 +22775,98 @@ def _call_finished(token: "dict | None") -> None:_workdir_calls.pop(token["workdir"], None)+def _history_snapshot(snap: "dict[str, tuple]") -> "tuple[dict, bool]":+ """The walk as file history keeps it: without scratch scripts and Studio's own trees. The flag+ says whether the walk was whole, since a capped one cannot prove a file is gone."""+ with _scratch_lock:+ scratch = set(_active_scratch)+ kept = {rel: key for rel, key in snap.items() if file_history.tracked(rel, scratch)}+ return kept, not isinstance(snap, _CappedSnapshot)+++def _history_begin(call_token: dict, session_id: "str | None", before: "dict[str, tuple]") -> None:+ if file_history.current_turn() is None:+ return+ snap, complete = _history_snapshot(before)+ call_token["history"] = file_history.begin_call(+ session_id, call_token.get("workdir"), snap, complete = complete+ )+++def _history_end(call_token: "dict | None", after: "dict[str, tuple]") -> None:+ if not call_token or call_token.get("history") is None:+ return+ if call_token.get("shared"):+ # An upload or another call wrote here meanwhile: what changed is not all this turn's.+ call_token["history"].ambiguous = True+ snap, complete = _history_snapshot(after)+ file_history.end_call(call_token["history"], snap, complete = complete)+++def _walk_lists(workdir: str, rel: str) -> bool:+ """Whether `_snapshot_workdir_files` would list *rel*, so a file edit_file records is never+ taken for a deletion by the next python or terminal walk."""+ parts = rel.split("/")+ if len(_user_path_parts(parts)) > _MAX_SANDBOX_PATH_SEGMENTS or not all(+ map(_servable_segment, parts)+ ):+ return False+ base = workdir+ for part in parts[:-1]:+ if part.startswith(".") or _snapshot_skips_dir(base, part):+ return False+ base = os.path.join(base, part)+ return not (len(parts) == 1 and parts[0] in _INTERNAL_SANDBOX_FILES)+++def _history_begin_file(session_id: "str | None", target: str) -> dict:+ """Track the one file an edit_file call writes. The first call in a folder walks it once for the baseline."""+ if file_history.current_turn() is None or not session_id:+ return {}+ workdir = os.path.realpath(_get_workdir(session_id))+ try:+ rel = os.path.relpath(os.path.realpath(target), workdir)+ except ValueError: # Windows: another drive, so outside the folder+ return {}+ if rel.startswith(os.pardir) or os.path.isabs(rel):+ return {}+ rel = rel.replace(os.sep, "/")+ if not _walk_lists(workdir, rel) or not file_history.tracked(rel, ()):+ return {}+ try:+ baseline = file_history.store().needs_baseline(workdir)+ except Exception:+ # History is an extra: an index it cannot open must not stop the edit.+ logger.warning("file history: could not open the index", exc_info = True)+ return {}+ if baseline:+ snap, complete = _history_snapshot(_snapshot_workdir_files(workdir))+ # A capped walk can miss the very file being edited; without it, the edit reads as a creation.+ snap = {**_history_file_snapshot(workdir, rel), **snap}+ else:+ snap, complete = _history_file_snapshot(workdir, rel), True+ token = file_history.begin_call(session_id, workdir, snap, paths = {rel}, complete = complete)+ return {"token": token, "workdir": workdir, "rel": rel} if token is not None else {}+++def _history_file_snapshot(workdir: str, rel: str) -> dict:+ try:+ info = os.lstat(os.path.join(workdir, rel))+ except OSError:+ return {}+ return {rel: (info.st_mtime_ns, info.st_size, None)} if S_ISREG(info.st_mode) else {}+++def _history_end_file(history: dict) -> None:+ if history.get("token") is None:+ return+ file_history.end_call(+ history["token"],+ _history_file_snapshot(history["workdir"], history["rel"]),+ paths = {history["rel"]},+ )++def _snapshot_differs(before: tuple, after: tuple) -> bool:"""Whether a file changed between two snapshots of its directory. The digest only when bothsnapshots have one: hashing stops at a byte budget, so a file added or removed earlier in the@@ -22774,11 +22886,12 @@ def _created_file_sentinels("""Sentinels naming the files this call created or overwrote. ``__IMAGES__`` renders inline asbefore; ``__FILES__`` carries every file with its size so the UI can offer a download. Bothare stripped before the model sees the result."""- if token is not None and token.get("shared"):+ if token is not None and token.get("shared") and token.get("history") is None:# Another call ran in this directory while this one did, so nothing here can be said to be ours. A missing# card beats one that names, and downloads, another chat's file.return ""after = _snapshot_workdir_files(workdir)+ _history_end(token, after)if token is not None and token.get("shared"):# A call that started while that walk was running. What it wrote is in `after` and cannot be told apart from# ours, so the same rule applies: the check above only saves the walk when the sharing was already known.@@ -22918,6 +23031,7 @@ def _python_exec(call_token = _call_started(workdir)# Snapshot mtimes to detect new and overwritten files._before = _snapshot_workdir_files(workdir)+ _history_begin(call_token, session_id, _before)try:# In the workdir: Python puts it on sys.path[0], so an earlier call's helper.py stays importable and __file__# resolves inside the sandbox.@@ -23184,6 +23298,7 @@ def _bash_exec(# Same pre-run snapshot as _python_exec. A command that writes a file used to produce "(no output)" and no# other trace anywhere in the product._before = _snapshot_workdir_files(workdir)+ _history_begin(call_token, session_id, _before)safe_env = (_build_bypass_env(workdir)if disable_sandboxdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex b786509342d..75067a8a05a 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2947,6 +2947,14 @@ class ChatCompletionRequest(BaseModel):None,description = "[x-unsloth] Conversation ID for scoping stateful tool sessions (e.g. stdio MCP); stays per-thread where session_id may be shared project-wide.",)+ user_message_id: Optional[str] = Field(+ None,+ max_length = 256,+ description = (+ "[x-unsloth] The user message this turn answers. With thread_id it keys the chat's file "+ "history, so /rewind can put back what this turn's tool calls changed."+ ),+ )rag_scope: Optional[dict] = Field(None,description = (diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pyindex 4b5f5db297c..7f47f1da53a 100644--- a/studio/backend/routes/accounts.py+++ b/studio/backend/routes/accounts.py@@ -83,6 +83,9 @@ def retire_account_roots(account: AccountContext):from storage.studio_db import close_wal_keeper_forclose_wal_keeper_for(run_as(account, storage_roots.workspace_root) / "studio.db")+ from core.inference import file_history++ file_history.close_store(run_as(account, storage_roots.account_path, "file_history"))roots = {root.absolute() for root in run_as(account, storage_roots.managed_account_roots)}stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")moved: list[tuple[Path, Path]] = []diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex fe6157140fc..296fce8780a 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -957,6 +957,7 @@ async def _remove_sandboxes(thread_ids, delete_files: bool) -> "tuple[int, list[# with a tool call possibly running in here, so its folder is not this delete's to take.if get_chat_thread(thread_id) is not None:continue+ _drop_file_history(thread_id)# A fork clones the message content, cards and all, so the source# chat's files are still on screen in a chat the user kept.if delete_files and sandbox_is_referenced_elsewhere(thread_id):@@ -1850,6 +1851,66 @@ class ChatThreadForkCountsResponse(BaseModel):counts: dict[str, int]+def _drop_file_history(thread_id: str) -> None:+ try:+ from core.inference import file_history+ file_history.store().delete_chat(thread_id)+ except Exception:+ logger.warning("Could not remove the file history of %s", thread_id, exc_info = True)+++class ChatRewindRequest(BaseModel):+ # The user messages being rewound, from the chosen one to the tip of the selected branch.+ turn_ids: list[Annotated[str, Field(min_length = 1, max_length = 256)]] = Field(max_length = 5000)+ dry_run: bool = False+ force: bool = False++[email protected]("/threads/{thread_id}/rewind")+def rewind_thread_files(+ thread_id: str,+ payload: ChatRewindRequest,+ current_subject: str = Depends(get_current_subject),+):+ """Put back the files this chat's tool calls changed during ``turn_ids``. Moving the+ conversation itself is the client's: it edits the chosen message, which keeps the old branch."""+ from core.inference import file_history, tools+ from hub.services.models import account_access+ from state import active_generations++ if get_chat_thread(thread_id) is None:+ raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")+ if not payload.dry_run and thread_id in active_generations.active_thread_ids(+ account_access.account_scope()+ ):+ raise HTTPException(+ status_code = 409, detail = "This chat is still generating. Rewind it once it finishes."+ )++ def walk(workdir: str):+ return tools._history_snapshot(tools._snapshot_workdir_files(workdir))++ def busy(workdir: str) -> bool:+ with tools._calls_lock:+ return any(os.path.realpath(w) == workdir for w in tools._workdir_calls)++ try:+ report = file_history.store().rewind(+ thread_id,+ payload.turn_ids,+ walk,+ dry_run = payload.dry_run,+ force = payload.force,+ busy = busy,+ )+ except file_history.RewindBusy as exc:+ raise HTTPException(status_code = 409, detail = str(exc)) from exc+ if report.undo_turn_id:+ from core import library+ library.invalidate_listing()+ return report.as_dict()++@router.post("/threads/{thread_id}/fork", response_model = ChatForkResponse)def fork_thread(thread_id: str,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 9587539c3e4..fb3cd0f735a 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -30401,6 +30401,9 @@ async def produce_openai_chat_completions(# still reachable. Otherwise it is dropped in silence and the answer looks legitimate._reject_unsupported_content_parts(payload)await _materialize_sandbox_attachments(payload)+ from core.inference import file_history++ file_history.set_turn(payload.thread_id, payload.user_message_id)# ── External provider routing ────────────────────────────────# encrypted_api_key is optional -- local providers (llama.cpp / vLLM / Ollama) may run without auth.diff --git a/studio/backend/tests/multi_account/factories_chat.py b/studio/backend/tests/multi_account/factories_chat.pyindex d4a01655a05..68b43f0175f 100644--- a/studio/backend/tests/multi_account/factories_chat.py+++ b/studio/backend/tests/multi_account/factories_chat.py@@ -194,6 +194,11 @@ FACTORIES = {{"messageId": FORK_MESSAGE_ID, "newThreadId": FORK_NEW_THREAD_ID, "createdAt": 2000},fragment = CHAT_SENTINEL,),+ "routes.chat_history:POST:/threads/{thread_id}/rewind": Factory(+ "chat-fork-source",+ {"turn_ids": [FORK_MESSAGE_ID], "dry_run": True},+ fragment = '"has_changes":false',+ ),"routes.chat_history:GET:/threads/{thread_id}/forks": Factory("chat-fork-tree",fragment = f'"{FORK_MESSAGE_ID}":1',diff --git a/studio/backend/tests/test_file_history.py b/studio/backend/tests/test_file_history.pynew file mode 100644index 00000000000..292c63f2311--- /dev/null+++ b/studio/backend/tests/test_file_history.py@@ -0,0 +1,391 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Per-chat file history: what python, terminal and edit_file change is recorded per turn, and+/rewind puts back exactly this chat's changes."""++import os+import sys+from pathlib import Path++import pytest++_BACKEND_ROOT = Path(__file__).resolve().parents[1]+if str(_BACKEND_ROOT) not in sys.path:+ sys.path.insert(0, str(_BACKEND_ROOT))++from core.inference import file_history, tools+from core.inference.tools import execute_tool+++def chat(tmp_path, monkeypatch):+ workdir = tmp_path / "sandbox"+ workdir.mkdir()+ history = file_history.FileHistory(str(tmp_path / "file_history"))+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))+ monkeypatch.setattr(file_history, "store", lambda: history)+ yield workdir, history+ file_history.set_turn(None, None)+++def _walk(workdir):+ return tools._history_snapshot(tools._snapshot_workdir_files(workdir))+++def _rewind(history, turn_ids, **kwargs):+ return history.rewind("chat-1", turn_ids, _walk, **kwargs)+++def _edit(path, old, new):+ return execute_tool(+ "edit_file",+ {"path": path, "edits": [{"old_string": old, "new_string": new}]},+ session_id = "s",+ )+++def _terminal(command):+ return execute_tool("terminal", {"command": command}, session_id = "s")+++def test_edit_file_turns_rewind_in_order(chat):+ workdir, history = chat+ (workdir / "keep.txt").write_text("original\n", encoding = "utf-8")+ file_history.set_turn("chat-1", "u1")+ _edit("app.py", "", "x = 1\n")+ _edit("keep.txt", "original", "changed")+ file_history.set_turn("chat-1", "u2")+ _edit("app.py", "x = 1", "x = 2")++ report = _rewind(history, ["u2"])+ assert report.restored == ["app.py"]+ assert (workdir / "app.py").read_text(encoding = "utf-8") == "x = 1\n"+ assert (workdir / "keep.txt").read_text(encoding = "utf-8") == "changed\n"++ report = _rewind(history, ["u1", "u2"])+ assert report.deleted == ["app.py"] and report.restored == ["keep.txt"]+ assert not (workdir / "app.py").exists()+ assert (workdir / "keep.txt").read_text(encoding = "utf-8") == "original\n"++[email protected](os.name != "posix", reason = "uses a POSIX shell")+def test_terminal_and_python_writes_and_deletes_are_restored(chat):+ workdir, history = chat+ (workdir / "data.csv").write_text("a,b\n", encoding = "utf-8")+ (workdir / "old.txt").write_text("bye\n", encoding = "utf-8")+ file_history.set_turn("chat-1", "u1")+ # `rm` waits for approval in the terminal tool; python deletes without asking.+ _terminal("printf 'x' >> data.csv && printf hi > new.txt")+ execute_tool("python", {"code": "import os; os.remove('old.txt')"}, session_id = "s")+ assert (workdir / "data.csv").read_text(encoding = "utf-8") == "a,b\nx"++ report = _rewind(history, ["u1"])+ assert report.restored == ["data.csv"]+ assert report.deleted == ["new.txt"]+ assert report.recreated == ["old.txt"]+ assert (workdir / "data.csv").read_text(encoding = "utf-8") == "a,b\n"+ assert (workdir / "old.txt").read_text(encoding = "utf-8") == "bye\n"+ assert not (workdir / "new.txt").exists()+++def test_a_dry_run_changes_nothing_and_a_second_rewind_is_a_no_op(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "a\n")+ preview = _rewind(history, ["u1"], dry_run = True)+ assert preview.has_changes and preview.deleted == ["a.txt"] and preview.undo_turn_id is None+ assert (workdir / "a.txt").exists()+ assert _rewind(history, ["u1"]).deleted == ["a.txt"]+ again = _rewind(history, ["u1"])+ assert again.has_changes and not (again.deleted or again.restored or again.recreated)+++def test_a_file_changed_since_is_skipped_unless_forced(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("notes.md", "", "mine\n")+ (workdir / "notes.md").write_text("the user's own edit\n", encoding = "utf-8")+ report = _rewind(history, ["u1"])+ assert report.conflicts == ["notes.md"]+ assert (workdir / "notes.md").read_text(encoding = "utf-8") == "the user's own edit\n"+ assert _rewind(history, ["u1"], force = True).deleted == ["notes.md"]+++def test_a_rewind_can_be_undone(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "one\n")+ file_history.set_turn("chat-1", "u2")+ _edit("a.txt", "one", "two")+ report = _rewind(history, ["u2"])+ assert (workdir / "a.txt").read_text(encoding = "utf-8") == "one\n"+ undo = _rewind(history, [report.undo_turn_id])+ assert undo.restored == ["a.txt"]+ assert (workdir / "a.txt").read_text(encoding = "utf-8") == "two\n"+++def test_nothing_is_recorded_outside_a_chat_turn(chat):+ workdir, history = chat+ _edit("a.txt", "", "a\n")+ assert history._db.execute("SELECT COUNT(*) FROM checkpoints").fetchone()[0] == 0+ assert not _rewind(history, ["u1"]).has_changes+++def test_another_chats_changes_are_never_touched(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("mine.txt", "", "1\n")+ file_history.set_turn("chat-2", "v1")+ _edit("theirs.txt", "", "2\n")+ assert _rewind(history, ["u1"]).deleted == ["mine.txt"]+ assert (workdir / "theirs.txt").read_text(encoding = "utf-8") == "2\n"+++def test_a_rewind_waits_for_a_running_call(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "a\n")+ token = history.begin("chat-1", str(workdir), "u2", _walk(str(workdir))[0])+ with pytest.raises(file_history.RewindBusy):+ _rewind(history, ["u1"])+ history.end(token, _walk(str(workdir))[0])+ assert _rewind(history, ["u1"]).deleted == ["a.txt"]+++def test_deleting_the_chat_drops_its_history(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "first version\n")+ _edit("a.txt", "first version", "second version")+ stored = history._db.execute("SELECT COUNT(*) FROM blobs").fetchone()[0]+ history.delete_chat("chat-1")+ assert history._db.execute("SELECT COUNT(*) FROM checkpoints").fetchone()[0] == 0+ # Only the folder's current image is still referenced.+ assert history._db.execute("SELECT COUNT(*) FROM blobs").fetchone()[0] < stored+++def test_large_files_are_reported_not_restored(chat, monkeypatch):+ workdir, history = chat+ monkeypatch.setattr(file_history, "MAX_FILE_BYTES", 8)+ (workdir / "big.bin").write_bytes(b"0123456789")+ file_history.set_turn("chat-1", "u1")+ _edit("note.txt", "", "n\n") # takes the baseline, with big.bin over the cap+ file_history.set_turn("chat-1", "u2")+ if os.name == "posix":+ _terminal("printf 'abcdefghijkl' > big.bin")+ report = _rewind(history, ["u2"])+ assert report.untracked == ["big.bin"]+ assert (workdir / "big.bin").read_bytes() == b"abcdefghijkl"+++def test_the_route_previews_rewinds_and_refuses_while_generating(chat, monkeypatch):+ from fastapi import HTTPException++ from routes import chat_history+ from state import active_generations++ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "a\n")+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda thread_id: {"id": thread_id})+ monkeypatch.setattr(active_generations, "active_thread_ids", lambda scope = None: set())++ def call(**body):+ request = chat_history.ChatRewindRequest(turn_ids = ["u1"], **body)+ return chat_history.rewind_thread_files("chat-1", request, current_subject = "user")++ preview = call(dry_run = True)+ assert (+ preview["has_changes"]+ and preview["deleted"] == ["a.txt"]+ and preview["undo_turn_id"] is None+ )+ assert (workdir / "a.txt").exists()++ monkeypatch.setattr(active_generations, "active_thread_ids", lambda scope = None: {"chat-1"})+ with pytest.raises(HTTPException) as refused:+ call()+ assert refused.value.status_code == 409++ monkeypatch.setattr(active_generations, "active_thread_ids", lambda scope = None: set())+ done = call()+ assert done["deleted"] == ["a.txt"] and done["undo_turn_id"]+ assert not (workdir / "a.txt").exists()+++def test_a_walk_cut_short_by_the_folder_cap_is_not_complete(chat, monkeypatch):+ workdir, _history = chat+ for name in ("a", "b", "c"):+ (workdir / name).mkdir()+ (workdir / name / "f.txt").write_text(name, encoding = "utf-8")+ assert _walk(str(workdir))[1] is True+ # Fewer files than the file cap, so only the folder cap can say the walk missed some.+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_DIRS", 2)+ assert _walk(str(workdir))[1] is False+++def test_a_damaged_copy_is_one_files_error_not_a_failed_rewind(chat):+ workdir, history = chat+ (workdir / "a.txt").write_text("a" * 4096, encoding = "utf-8")+ (workdir / "b.txt").write_text("b" * 4096, encoding = "utf-8")+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "a" * 4096, "x")+ _edit("b.txt", "b" * 4096, "y")+ for blob in Path(history.objects).glob("??/*"):+ payload = blob.read_bytes()+ if payload[:1] != b"R":+ blob.write_bytes(payload[:1] + b"\0garbage")+ report = _rewind(history, ["u1"])+ assert report.errors and all("damaged" in error for error in report.errors)+++def test_the_cap_counts_history_not_the_folders_current_files(chat, monkeypatch):+ workdir, history = chat+ (workdir / "big.txt").write_text("z" * 1000, encoding = "utf-8")+ file_history.set_turn("chat-1", "u1")+ _edit("app.py", "", "x = 1\n")+ monkeypatch.setattr(file_history, "GLOBAL_CAP_BYTES", 1)+ history.gc()+ # Only the current images (big.txt, app.py) are over the cap, and they cannot be dropped.+ assert history._db.execute("SELECT COUNT(*) FROM checkpoints").fetchone()[0] >= 1+++def test_edit_file_still_works_when_history_cannot_open(chat, monkeypatch):+ workdir, _history = chat++ def broken():+ raise OSError("read-only")++ monkeypatch.setattr(file_history, "store", broken)+ file_history.set_turn("chat-1", "u1")+ _edit("app.py", "", "x = 1\n")+ assert (workdir / "app.py").read_text(encoding = "utf-8") == "x = 1\n"+++def test_a_file_written_while_another_chats_call_ran_is_a_conflict(chat):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("seed.txt", "", "s\n") # takes the folder's baseline+ mine = history.begin("chat-1", str(workdir), "u2", _walk(str(workdir))[0])+ theirs = history.begin("chat-2", str(workdir), "v1", _walk(str(workdir))[0])+ (workdir / "theirs.txt").write_text("2\n", encoding = "utf-8")+ history.end(mine, _walk(str(workdir))[0])+ history.end(theirs, _walk(str(workdir))[0])+ report = _rewind(history, ["u2"])+ assert report.conflicts == ["theirs.txt"] and report.deleted == []+ assert (workdir / "theirs.txt").read_text(encoding = "utf-8") == "2\n"++[email protected](os.name != "posix", reason = "uses a symlink")+def test_a_folder_swapped_for_a_link_is_never_written_through(chat, tmp_path):+ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "1\n")+ _edit("a.txt", "1", "2")+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()+ (elsewhere / "a.txt").write_text("2\n", encoding = "utf-8")+ workdir.rename(tmp_path / "moved")+ workdir.symlink_to(elsewhere, target_is_directory = True)+ report = history.rewind(+ "chat-1", ["u1"], lambda wd: tools._history_snapshot(tools._snapshot_workdir_files(wd))+ )+ assert report.errors and (elsewhere / "a.txt").read_text(encoding = "utf-8") == "2\n"+++def test_deleting_a_chat_that_only_read_files_releases_its_baseline(chat):+ workdir, history = chat+ (workdir / "data.csv").write_text("a,b\n", encoding = "utf-8")+ file_history.set_turn("chat-1", "u1")+ execute_tool("python", {"code": "print(open('data.csv').read())"}, session_id = "s")+ assert history._db.execute("SELECT COUNT(*) FROM workdir_state").fetchone()[0] == 1+ history.delete_chat("chat-1")+ assert history._db.execute("SELECT COUNT(*) FROM workdir_state").fetchone()[0] == 0+ assert history._db.execute("SELECT COUNT(*) FROM blobs").fetchone()[0] == 0+++def test_an_edit_missed_by_a_capped_first_walk_restores_the_original(chat, monkeypatch):+ workdir, history = chat+ (workdir / "a").mkdir()+ (workdir / "z").mkdir()+ (workdir / "z" / "keep.txt").write_text("original\n", encoding = "utf-8")+ monkeypatch.setattr(tools, "_MAX_SNAPSHOT_DIRS", 1)+ file_history.set_turn("chat-1", "u1")+ _edit("z/keep.txt", "original", "changed")+ report = _rewind(history, ["u1"])+ assert report.restored == ["z/keep.txt"] and report.deleted == []+ assert (workdir / "z" / "keep.txt").read_text(encoding = "utf-8") == "original\n"+++def test_a_blob_file_without_its_row_gets_the_row_back(chat):+ _workdir, history = chat+ digest = history._put_blob(b"hello" * 100)+ history._db.execute("DELETE FROM blobs WHERE hash=?", (digest,))+ history._put_blob(b"hello" * 100)+ assert (+ history._db.execute("SELECT COUNT(*) FROM blobs WHERE hash=?", (digest,)).fetchone()[0] == 1+ )+++def test_retention_runs_once_enough_bytes_are_stored(chat, monkeypatch):+ _workdir, history = chat+ monkeypatch.setattr(file_history, "GC_AFTER_BYTES", 1)+ ran = []+ monkeypatch.setattr(history, "gc", lambda: ran.append(1))+ file_history.set_turn("chat-1", "u1")+ _edit("a.txt", "", "first\n")+ _edit("a.txt", "first", "second")+ assert ran+++def test_close_store_releases_the_index(tmp_path, monkeypatch):+ root = tmp_path / "file_history"+ history = file_history.FileHistory(str(root))+ monkeypatch.setitem(file_history._stores, str(root), history)+ file_history.close_store(root)+ assert str(root) not in file_history._stores+ with pytest.raises(Exception):+ history._db.execute("SELECT 1")+++def test_one_call_stores_at_most_its_byte_budget(chat, monkeypatch):+ _workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("seed.txt", "", "s\n") # the baseline+ monkeypatch.setattr(file_history, "CALL_BUDGET_BYTES", 1500)+ execute_tool(+ "python",+ {"code": "import os\nfor i in range(4): open(f'f{i}.bin', 'wb').write(os.urandom(1000))"},+ session_id = "s",+ )+ kinds = dict(+ history._db.execute("SELECT rel_path, kind FROM workdir_state WHERE rel_path LIKE 'f%'")+ )+ assert sorted(kinds.values()).count("blob") == 1 and len(kinds) == 4+++def test_an_upload_during_a_call_is_never_undone_with_it(chat):+ import contextvars+ import threading+ import time++ workdir, history = chat+ file_history.set_turn("chat-1", "u1")+ _edit("seed.txt", "", "s\n") # the baseline+ worker = threading.Thread(+ target = contextvars.copy_context().run,+ args = (+ execute_tool,+ "python",+ {"code": "import time; open('out.txt', 'w').write('x'); time.sleep(2)"},+ ),+ kwargs = {"session_id": "s"},+ )+ worker.start()+ time.sleep(0.8)+ tools.save_sandbox_upload("s", "upload.txt", [b"mine\n"])+ worker.join()+ report = _rewind(history, ["u1"])+ assert "upload.txt" in report.conflicts+ assert (workdir / "upload.txt").read_text(encoding = "utf-8") == "mine\n"diff --git a/studio/frontend/src/components/assistant-ui/rewind-dialog.tsx b/studio/frontend/src/components/assistant-ui/rewind-dialog.tsxnew file mode 100644index 00000000000..db625aa4357--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/rewind-dialog.tsx@@ -0,0 +1,351 @@+// 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 { useAui, useAuiState } from "@assistant-ui/react";+import { type FC, useEffect, useMemo, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import {+ collectRewindTurnIds,+ defaultRewindMode,+ isThreadIncognito,+ type RewindMode,+ type RewindResult,+ rewindChangedCount,+ rewindChatThread,+ rewindPickerEntries,+ rewindSkippedCount,+ rewindTouchesConversation,+ rewindTouchesFiles,+ useRewindDialogStore,+} from "@/features/chat";+import { useT } from "@/i18n";+import { toast } from "@/lib/toast";++type Translate = ReturnType<typeof useT>;++type DryRun =+ | { state: "loading" }+ | { state: "done"; result: RewindResult | null }+ | { state: "error"; message: string };++const errorMessage = (error: unknown) =>+ error instanceof Error ? error.message : String(error);++function toastRestoreResult(+ t: Translate,+ remoteId: string,+ result: RewindResult,+) {+ const changed = rewindChangedCount(result);+ const skipped = rewindSkippedCount(result) + result.errors.length;+ if (changed === 0 && skipped > 0) {+ // Every file was skipped: a failure, so the caller stops before moving the conversation.+ toast.error(t("rewind.restoreFailed"), {+ description: t("rewind.skippedCount", { count: skipped }),+ });+ return false;+ }+ const title =+ changed === 0+ ? t("rewind.nothingRestored")+ : changed === 1+ ? t("rewind.restoredOne")+ : t("rewind.restoredMany", { count: changed });+ const undoTurnId = result.undo_turn_id;+ toast.success(title, {+ ...(skipped > 0+ ? { description: t("rewind.skippedCount", { count: skipped }) }+ : {}),+ ...(undoTurnId+ ? {+ action: {+ label: t("rewind.undo"),+ onClick: () => {+ rewindChatThread(remoteId, {+ turn_ids: [undoTurnId],+ dry_run: false,+ }).then(+ (undo) => {+ const skippedUndo =+ rewindSkippedCount(undo) + undo.errors.length;+ if (rewindChangedCount(undo) === 0) {+ toast.error(t("rewind.undoFailed"), {+ ...(skippedUndo > 0+ ? {+ description: t("rewind.skippedCount", {+ count: skippedUndo,+ }),+ }+ : {}),+ });+ } else {+ toast.success(t("rewind.undone"), {+ ...(skippedUndo > 0+ ? {+ description: t("rewind.skippedCount", {+ count: skippedUndo,+ }),+ }+ : {}),+ });+ }+ },+ (error: unknown) =>+ toast.error(t("rewind.undoFailed"), {+ description: errorMessage(error),+ }),+ );+ },+ },+ }+ : {}),+ });+ return true;+}++const FileList: FC<{ label: string; files: string[] }> = ({ label, files }) =>+ files.length === 0 ? null : (+ <div className="grid gap-1">+ <p className="text-muted-foreground text-xs">{label}</p>+ <ul className="max-h-24 overflow-y-auto font-mono text-xs">+ {files.map((file) => (+ <li key={file} className="truncate" title={file}>+ {file}+ </li>+ ))}+ </ul>+ </div>+ );++/** Mounted once per Thread; opens for requests addressed to this thread's list item. */+export const RewindDialog: FC = () => {+ const threadKey = useAuiState(({ threadListItem }) => threadListItem.id);+ const request = useRewindDialogStore((s) => s.request);+ const closeRewind = useRewindDialogStore((s) => s.closeRewind);+ const open = request !== null && request.threadKey === threadKey;+ return (+ <Dialog open={open} onOpenChange={(next) => !next && closeRewind()}>+ <DialogContent className="corner-squircle dialog-soft-surface gap-5 sm:max-w-md">+ {/* Content unmounts on close, so each open starts from a fresh read of the branch. */}+ {open ? (+ <RewindDialogBody+ initialMessageId={request.messageId}+ onClose={closeRewind}+ />+ ) : null}+ </DialogContent>+ </Dialog>+ );+};++const RewindDialogBody: FC<{+ initialMessageId: string | null;+ onClose: () => void;+}> = ({ initialMessageId, onClose }) => {+ const t = useT();+ const aui = useAui();+ const [messageId, setMessageId] = useState(initialMessageId);+ // Read once: subscribing would re-render this dialog on every streamed token.+ const branch = useMemo(() => aui.thread().getState().messages, [aui]);+ const entries = useMemo(() => rewindPickerEntries(branch), [branch]);++ if (messageId === null) {+ return (+ <>+ <DialogHeader>+ <DialogTitle className="text-ui-21">{t("rewind.title")}</DialogTitle>+ <DialogDescription>{t("rewind.pickDescription")}</DialogDescription>+ </DialogHeader>+ {entries.length === 0 ? (+ <p className="text-muted-foreground">{t("rewind.pickEmpty")}</p>+ ) : (+ <ul className="grid max-h-80 gap-1 overflow-y-auto">+ {entries.map((entry) => (+ <li key={entry.id}>+ <button+ type="button"+ onClick={() => setMessageId(entry.id)}+ className="w-full truncate rounded-[12px] px-3 py-2 text-left hover:bg-accent focus-visible:bg-accent outline-none"+ >+ {entry.preview || (+ <span className="text-muted-foreground">+ {t("rewind.attachmentOnly")}+ </span>+ )}+ </button>+ </li>+ ))}+ </ul>+ )}+ </>+ );+ }+ return (+ <RewindChoices+ key={messageId}+ messageId={messageId}+ turnIds={collectRewindTurnIds(branch, messageId)}+ onBack={initialMessageId === null ? () => setMessageId(null) : undefined}+ onClose={onClose}+ />+ );+};++const RewindChoices: FC<{+ messageId: string;+ turnIds: string[];+ onBack?: () => void;+ onClose: () => void;+}> = ({ messageId, turnIds, onBack, onClose }) => {+ const t = useT();+ const aui = useAui();+ const remoteId = useAuiState(({ threadListItem }) => threadListItem.remoteId);+ // A temporary chat keeps no file history (and has no row the route can find).+ const tracked = Boolean(remoteId) && !isThreadIncognito(remoteId ?? "");+ const [dryRun, setDryRun] = useState<DryRun>(+ tracked && turnIds.length > 0+ ? { state: "loading" }+ : { state: "done", result: null },+ );+ const [mode, setMode] = useState<RewindMode>("conversation");+ const [busy, setBusy] = useState(false);+ const turnKey = turnIds.join("\n");++ useEffect(() => {+ if (!remoteId || !tracked || turnKey === "") return;+ let cancelled = false;+ rewindChatThread(remoteId, { turn_ids: turnKey.split("\n"), dry_run: true }).then(+ (result) => {+ if (cancelled) return;+ setDryRun({ state: "done", result });+ setMode(defaultRewindMode(rewindChangedCount(result) > 0));+ },+ (error: unknown) => {+ if (!cancelled) setDryRun({ state: "error", message: errorMessage(error) });+ },+ );+ return () => {+ cancelled = true;+ };+ }, [remoteId, tracked, turnKey]);++ const result = dryRun.state === "done" ? dryRun.result : null;+ // Rows can exist with nothing left to put back (right after a rewind): that is no change.+ const hasChanges = result !== null && rewindChangedCount(result) > 0;++ const confirm = async () => {+ if (aui.thread().getState().isRunning) {+ toast.error(t("rewind.waitForResponse"));+ return;+ }+ if (rewindTouchesFiles(mode) && remoteId) {+ setBusy(true);+ try {+ const restored = await rewindChatThread(remoteId, {+ turn_ids: turnIds,+ dry_run: false,+ });+ if (!toastRestoreResult(t, remoteId, restored)) {+ setBusy(false);+ return;+ }+ } catch (error) {+ setBusy(false);+ toast.error(t("rewind.restoreFailed"), {+ description: errorMessage(error),+ });+ return;+ }+ }+ if (rewindTouchesConversation(mode)) {+ try {+ aui.thread().message({ id: messageId }).composer().beginEdit();+ } catch {+ // The message left the branch while the dialog was open.+ }+ }+ onClose();+ };++ const options: { value: RewindMode; label: string; files: boolean }[] = [+ { value: "both", label: t("rewind.modeBoth"), files: true },+ { value: "conversation", label: t("rewind.modeConversation"), files: false },+ { value: "files", label: t("rewind.modeFiles"), files: true },+ ];++ return (+ <>+ <DialogHeader>+ <DialogTitle className="text-ui-21">{t("rewind.title")}</DialogTitle>+ <DialogDescription>{t("rewind.chooseDescription")}</DialogDescription>+ </DialogHeader>+ <RadioGroup+ value={mode}+ onValueChange={(value) => setMode(value as RewindMode)}+ disabled={busy}+ >+ {options.map((option) => (+ <label+ key={option.value}+ className="flex cursor-pointer items-center gap-3 has-[button:disabled]:cursor-not-allowed has-[button:disabled]:opacity-50"+ >+ <RadioGroupItem+ value={option.value}+ disabled={option.files && !hasChanges}+ />+ {option.label}+ </label>+ ))}+ </RadioGroup>+ <div className="grid gap-2 text-sm">+ {dryRun.state === "loading" ? (+ <p className="text-muted-foreground">{t("rewind.checking")}</p>+ ) : dryRun.state === "error" ? (+ <p className="text-destructive">+ {t("rewind.checkFailed", { error: dryRun.message })}+ </p>+ ) : !result?.has_changes ? (+ <p className="text-muted-foreground">{t("rewind.noFileChanges")}</p>+ ) : (+ <>+ <p>+ {t("rewind.summary", {+ restore: result.restored.length,+ remove: result.deleted.length,+ recreate: result.recreated.length,+ })}+ </p>+ <FileList label={t("rewind.conflicts")} files={result.conflicts} />+ <FileList label={t("rewind.untracked")} files={result.untracked} />+ </>+ )}+ <p className="text-muted-foreground text-xs">{t("rewind.scopeNote")}</p>+ </div>+ <DialogFooter>+ {onBack ? (+ <Button variant="ghost" onClick={onBack} disabled={busy}>+ {t("rewind.back")}+ </Button>+ ) : null}+ <Button variant="outline" onClick={onClose} disabled={busy}>+ {t("rewind.cancel")}+ </Button>+ <Button+ onClick={() => void confirm()}+ disabled={busy || dryRun.state === "loading"}+ >+ {t("rewind.confirm")}+ </Button>+ </DialogFooter>+ </>+ );+};diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 01c0302eb3d..90762eda4c0 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -76,6 +76,7 @@ import { ImageGenerationToolUI } from "@/components/assistant-ui/tool-ui-image-gimport { KnowledgeBaseToolUI } from "@/components/assistant-ui/tool-ui-knowledge-base";import { ReadSkillToolUI } from "@/components/assistant-ui/tool-ui-read-skill";import { SkillMentionPopover } from "@/components/assistant-ui/skill-mentions";+import { isRewindCommand, useRewindDialogStore } from "@/features/chat";import { RenderHtmlToolUI } from "@/components/assistant-ui/tool-ui-render-html";import { PythonToolUI } from "@/components/assistant-ui/tool-ui-python";import { TerminalToolUI } from "@/components/assistant-ui/tool-ui-terminal";@@ -398,6 +399,7 @@ import {McpServerIcon,Scroll01Icon,Telescope02Icon,+ UndoIcon,VolumeMute02Icon,WorkflowCircle05Icon,} from "@hugeicons/core-free-icons";@@ -429,7 +431,9 @@ import {type ReactNode,type RefObject,Fragment,+ Suspense,createContext,+ lazy,memo,useCallback,useContext,@@ -2382,6 +2386,7 @@ export const Thread: FC<{</ThreadPrimitive.Root>{/* Document preview, opened by citation badges. */}<DocumentPreviewMount />+ <RewindDialogMount /></PageDragContext.Provider></GeneratedImageOverlayProvider>);@@ -5347,6 +5352,20 @@ const Composer: FC<{event.preventDefault();return;}+ // A command, not a prompt: ahead of the model and queue gates, so it works with no model loaded.+ if (!overlay && !hasAttachments && isRewindCommand(composerText)) {+ event.preventDefault();+ if (threadIsRunning || aui.thread().getState().isRunning) {+ toast.error(translate("rewind.waitForResponse"));+ return;+ }+ aui.composer().setText("");+ useRewindDialogStore.getState().openRewind({+ threadKey: aui.threadListItem().getState().id,+ messageId: null,+ });+ return;+ }if (disabled || shouldBlockSend()) {event.preventDefault();parkIfWaitingOnAttachments();@@ -8555,7 +8574,50 @@ const ForkMessageMenuItem: FC = () => {);};-// A prompt's More menu: Fork, then Delete.+// Loaded on first use: the dialog is not part of the first screen.+const LazyRewindDialog = lazy(() =>+ import("@/components/assistant-ui/rewind-dialog").then((module) => ({+ default: module.RewindDialog,+ })),+);++const RewindDialogMount: FC = () => {+ const requested = useRewindDialogStore((s) => s.request !== null);+ const [loaded, setLoaded] = useState(false);+ useEffect(() => {+ if (requested) setLoaded(true);+ }, [requested]);+ // Stays mounted once loaded so closing keeps its animation.+ return requested || loaded ? (+ <Suspense fallback={null}>+ <LazyRewindDialog />+ </Suspense>+ ) : null;+};++const RewindMessageMenuItem: FC = () => {+ const aui = useAui();+ const t = useT();+ const messageId = useAuiState(({ message }) => message.id);+ const isRunning = useAuiState(({ thread }) => thread.isRunning);+ return (+ <ActionBarMorePrimitive.Item+ disabled={isRunning}+ onSelect={() =>+ useRewindDialogStore.getState().openRewind({+ threadKey: aui.threadListItem().getState().id,+ messageId,+ })+ }+ className="aui-action-bar-more-item flex cursor-pointer select-none items-center gap-2 rounded-[12px] px-3 py-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"+ >+ <HugeiconsIcon icon={UndoIcon} strokeWidth={1.75} className="size-icon" />+ {t("rewind.menuItem")}+ </ActionBarMorePrimitive.Item>+ );+};++// A prompt's More menu: Fork, Rewind, then Delete.const UserMoreMenu: FC = () => {const triggerRef = useRef<HTMLButtonElement>(null);const collisionPadding = useWindowChromeCollisionPadding(undefined);@@ -8576,6 +8638,7 @@ const UserMoreMenu: FC = () => {<div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto"><MenuDismissGuard triggerRef={triggerRef} /><ForkMessageMenuItem />+ <RewindMessageMenuItem /><DeleteMessageMenuItem /></div></ActionBarMorePrimitive.Content>diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 6f0cfe1d3d7..2bd6a9295c6 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -92,6 +92,7 @@ import {mcpUiReplayImages,} from "../mcp-apps/mcp-ui";import { isMcpToolName } from "../utils/mcp-tool-name";+import { userMessageIdRequestField } from "../utils/rewind";import {type McpImage,planMcpImageBound,@@ -5658,6 +5659,13 @@ export function createOpenAIStreamAdapter(const generationUserMessage = [...survivingMessages].reverse().find((message) => message.role === "user");+ // Names the turn whose file changes /rewind can undo; a continuation reuses its turn's prompt.+ // A temporary chat keeps no file history.+ const userMessageIdField = userMessageIdRequestField(+ resolvedThreadId && isThreadIncognito(resolvedThreadId)+ ? undefined+ : generationUserMessage?.id,+ );// Durability gate keys on THIS turn's attachments only. The scans above walk post-prune history so an old// refused turn cannot mis-attribute media onto the next one - correct for building the request payload, but it@@ -6856,6 +6864,7 @@ export function createOpenAIStreamAdapter(...(sandboxSessionId? { session_id: sandboxSessionId }: {}),+ ...userMessageIdField,...(sandboxAttachments.length > 0? { sandbox_attachments: sandboxAttachments }: {}),@@ -7014,6 +7023,7 @@ export function createOpenAIStreamAdapter(? { sandbox_attachments: sandboxAttachments }: {}),...(resolvedThreadId ? { thread_id: resolvedThreadId } : {}),+ ...userMessageIdField,...(useAdapter === undefined ? {} : { use_adapter: useAdapter }),...localReasoningFields,...(supportsPreserveThinkingdiff --git a/studio/frontend/src/features/chat/api/rewind-api.ts b/studio/frontend/src/features/chat/api/rewind-api.tsnew file mode 100644index 00000000000..b781d47f2b7--- /dev/null+++ b/studio/frontend/src/features/chat/api/rewind-api.ts@@ -0,0 +1,28 @@+// 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 { authFetch } from "@/features/auth";+import { formatApiErrorBody } from "@/lib/format-fastapi-error";+import type { RewindResult } from "../utils/rewind";++/** 409 while a tool call is running or the chat is generating; `detail` says which. */+export async function rewindChatThread(+ threadId: string,+ body: { turn_ids: string[]; dry_run: boolean; force?: boolean },+): Promise<RewindResult> {+ const response = await authFetch(+ `/api/chat/threads/${encodeURIComponent(threadId)}/rewind`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ },+ );+ const payload = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(+ formatApiErrorBody(payload) ?? `Request failed (${response.status})`,+ );+ }+ return payload as RewindResult;+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 701dfb19f89..65d0056e275 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -142,6 +142,23 @@ export {useForkBoundaryStore,type ForkBoundaryState,} from "./stores/fork-boundary-store";+export { rewindChatThread } from "./api/rewind-api";+export {+ type RewindDialogRequest,+ useRewindDialogStore,+} from "./stores/rewind-dialog-store";+export {+ collectRewindTurnIds,+ defaultRewindMode,+ isRewindCommand,+ type RewindMode,+ type RewindResult,+ rewindChangedCount,+ rewindPickerEntries,+ rewindSkippedCount,+ rewindTouchesConversation,+ rewindTouchesFiles,+} from "./utils/rewind";export {folderRingKey,planKey,diff --git a/studio/frontend/src/features/chat/stores/rewind-dialog-store.ts b/studio/frontend/src/features/chat/stores/rewind-dialog-store.tsnew file mode 100644index 00000000000..b080eceb6f8--- /dev/null+++ b/studio/frontend/src/features/chat/stores/rewind-dialog-store.ts@@ -0,0 +1,24 @@+// 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";++/**+ * The open Rewind dialog, if any. `threadKey` is the assistant-ui thread list item id, so only+ * the Thread that asked opens it when compare panes mount several. A null `messageId` is the+ * `/rewind` picker; a message id skips straight to the choices.+ */+export interface RewindDialogRequest {+ threadKey: string;+ messageId: string | null;+}++export const useRewindDialogStore = create<{+ request: RewindDialogRequest | null;+ openRewind: (request: RewindDialogRequest) => void;+ closeRewind: () => void;+}>((set) => ({+ request: null,+ openRewind: (request) => set({ request }),+ closeRewind: () => set({ request: null }),+}));diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 0e9ebd769db..12ea4aba9e3 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -745,6 +745,8 @@ export interface OpenAIChatCompletionsRequest {max_tool_calls_per_message?: number;tool_call_timeout?: number;session_id?: string;+ /** The user message that started this turn; keys the turn's file checkpoints for /rewind. */+ user_message_id?: string;cancel_id?: string;provider_id?: string;provider_type?: string;diff --git a/studio/frontend/src/features/chat/utils/rewind.ts b/studio/frontend/src/features/chat/utils/rewind.tsnew file mode 100644index 00000000000..20b1afee861--- /dev/null+++ b/studio/frontend/src/features/chat/utils/rewind.ts@@ -0,0 +1,104 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Pure helpers for /rewind: no runtime imports, so the node tests load this file directly. */++export type RewindMode = "both" | "conversation" | "files";++export interface RewindResult {+ has_changes: boolean;+ restored: string[];+ deleted: string[];+ recreated: string[];+ conflicts: string[];+ untracked: string[];+ errors: string[];+ undo_turn_id: string | null;+}++interface BranchMessage {+ readonly id: string;+ readonly role: string;+ readonly content?: unknown;+}++const REWIND_COMMAND = "/rewind";+const PREVIEW_MAX_CHARS = 80;++/** Exactly `/rewind`, ignoring surrounding whitespace and case. */+export function isRewindCommand(text: string): boolean {+ return text.trim().toLowerCase() === REWIND_COMMAND;+}++/** The chosen user message and every later user message on the branch, oldest first. */+export function collectRewindTurnIds(+ branch: readonly BranchMessage[],+ userMessageId: string,+): string[] {+ const start = branch.findIndex((message) => message.id === userMessageId);+ if (start < 0 || branch[start].role !== "user") return [];+ return branch+ .slice(start)+ .filter((message) => message.role === "user")+ .map((message) => message.id);+}++/** Omitted without a user message, so a turn with none sends nothing new. */+export function userMessageIdRequestField(+ userMessageId: string | undefined,+): { user_message_id?: string } {+ return userMessageId ? { user_message_id: userMessageId } : {};+}++function messageText(content: unknown): string {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .map((part) =>+ part && typeof part === "object" && (part as { type?: unknown }).type === "text"+ ? String((part as { text?: unknown }).text ?? "")+ : "",+ )+ .join(" ");+}++/** One line per user message on the branch, newest first; an empty preview is attachment-only. */+export function rewindPickerEntries(+ branch: readonly BranchMessage[],+): { id: string; preview: string }[] {+ return branch+ .filter((message) => message.role === "user")+ .map((message) => {+ const line = messageText(message.content).replace(/\s+/g, " ").trim();+ return {+ id: message.id,+ preview:+ line.length > PREVIEW_MAX_CHARS+ ? `${line.slice(0, PREVIEW_MAX_CHARS - 1).trimEnd()}…`+ : line,+ };+ })+ .reverse();+}++export function defaultRewindMode(hasChanges: boolean): RewindMode {+ return hasChanges ? "both" : "conversation";+}++export function rewindTouchesFiles(mode: RewindMode): boolean {+ return mode !== "conversation";+}++export function rewindTouchesConversation(mode: RewindMode): boolean {+ return mode !== "files";+}++export function rewindChangedCount(result: RewindResult): number {+ return (+ result.restored.length + result.deleted.length + result.recreated.length+ );+}++export function rewindSkippedCount(result: RewindResult): number {+ return result.conflicts.length + result.untracked.length;+}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 98b983f283a..54b1d8e0174 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -547,6 +547,36 @@ export const ar = {queueingOnHint: "الرسائل الجديدة تنتظر دورها.",queueingHintShared: "يبقى الطابور كما هو.",},+ rewind: {+ menuItem: "إرجاع…",+ title: "إرجاع",+ pickDescription: "اختر رسالة للرجوع إليها.",+ pickEmpty: "لا توجد رسائل للرجوع إليها بعد.",+ attachmentOnly: "مرفقات فقط",+ chooseDescription: "تُفتح الرسالة للتعديل حتى تتمكن من إعادة إرسالها. تظل الردود الحالية متاحة عبر أسهم الفروع.",+ modeBoth: "المحادثة والملفات",+ modeConversation: "المحادثة فقط",+ modeFiles: "الملفات فقط",+ checking: "جارٍ التحقق من تغييرات الملفات…",+ checkFailed: "تعذر التحقق من تغييرات الملفات: {error}",+ noFileChanges: "لا توجد تغييرات على الملفات بعد هذه الرسالة",+ summary: "ملفات للاستعادة: {restore}. للإزالة: {remove}. لإعادة الإنشاء: {recreate}.",+ conflicts: "تغيرت منذ ذلك الحين، وسيتم تخطيها",+ untracked: "لا يمكن استعادتها",+ scopeNote: "لا تتغير البرامج قيد التشغيل والحزم المثبتة وأي شيء خارج مجلد هذه المحادثة.",+ back: "رجوع",+ cancel: "إلغاء",+ confirm: "إرجاع",+ waitForResponse: "انتظر حتى ينتهي الرد الحالي",+ restoredOne: "تمت استعادة ملف واحد",+ restoredMany: "تمت استعادة {count} ملفات",+ nothingRestored: "لم تكن هناك ملفات تحتاج إلى استعادة",+ skippedCount: "تم تخطي {count}",+ restoreFailed: "تعذرت استعادة الملفات",+ undo: "تراجع",+ undone: "تم التراجع عن استعادة الملفات",+ undoFailed: "تعذر التراجع عن استعادة الملفات",+ },// The chat header's "…" menu.chatMenu: {more: "خيارات المحادثة",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex f3c1db418b9..de6300c65c6 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -547,6 +547,36 @@ export const de = {queueingOnHint: "Neue Nachrichten warten auf ihren Platz.",queueingHintShared: "Die Warteschlange bleibt erhalten.",},+ rewind: {+ menuItem: "Zurückspulen…",+ title: "Zurückspulen",+ pickDescription: "Wähle eine Nachricht, zu der zurückgespult werden soll.",+ pickEmpty: "Es gibt noch keine Nachrichten zum Zurückspulen.",+ attachmentOnly: "Nur Anhänge",+ chooseDescription: "Die Nachricht wird zum Bearbeiten geöffnet, damit du sie erneut senden kannst. Die aktuellen Antworten bleiben über die Verzweigungspfeile erreichbar.",+ modeBoth: "Unterhaltung und Dateien",+ modeConversation: "Nur Unterhaltung",+ modeFiles: "Nur Dateien",+ checking: "Dateiänderungen werden geprüft…",+ checkFailed: "Dateiänderungen konnten nicht geprüft werden: {error}",+ noFileChanges: "Keine Dateiänderungen nach dieser Nachricht",+ summary: "Wiederherzustellende Dateien: {restore}. Zu entfernen: {remove}. Neu zu erstellen: {recreate}.",+ conflicts: "Seitdem geändert, wird übersprungen",+ untracked: "Kann nicht wiederhergestellt werden",+ scopeNote: "Laufende Programme, installierte Pakete und alles außerhalb des Ordners dieses Chats werden nicht geändert.",+ back: "Zurück",+ cancel: "Abbrechen",+ confirm: "Zurückspulen",+ waitForResponse: "Warte, bis die aktuelle Antwort fertig ist",+ restoredOne: "1 Datei wiederhergestellt",+ restoredMany: "{count} Dateien wiederhergestellt",+ nothingRestored: "Keine Dateien mussten wiederhergestellt werden",+ skippedCount: "{count} übersprungen",+ restoreFailed: "Dateien konnten nicht wiederhergestellt werden",+ undo: "Rückgängig",+ undone: "Wiederherstellung der Dateien rückgängig gemacht",+ undoFailed: "Wiederherstellung der Dateien konnte nicht rückgängig gemacht werden",+ },// The chat header's "…" menu.chatMenu: {more: "Chat-Optionen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex d012ecc5268..f65c72d46e9 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -589,6 +589,39 @@ export const en = {queueingOnHint: "New messages wait their turn.",queueingHintShared: "The queue is kept.",},+ // /rewind and the prompt More menu's Rewind item.+ rewind: {+ menuItem: "Rewind…",+ title: "Rewind",+ pickDescription: "Choose a message to rewind to.",+ pickEmpty: "There are no messages to rewind to yet.",+ attachmentOnly: "Attachments only",+ chooseDescription:+ "The message opens for editing so you can resend it. The current replies stay available with the branch arrows.",+ modeBoth: "Conversation and files",+ modeConversation: "Conversation only",+ modeFiles: "Files only",+ checking: "Checking file changes…",+ checkFailed: "Could not check file changes: {error}",+ noFileChanges: "No file changes after this message",+ summary: "Files to restore: {restore}. To remove: {remove}. To recreate: {recreate}.",+ conflicts: "Changed since, will be skipped",+ untracked: "Cannot be restored",+ scopeNote:+ "Running programs, installed packages and anything outside this chat's folder are not changed.",+ back: "Back",+ cancel: "Cancel",+ confirm: "Rewind",+ waitForResponse: "Wait for the current response to finish",+ restoredOne: "Restored 1 file",+ restoredMany: "Restored {count} files",+ nothingRestored: "No files needed restoring",+ skippedCount: "{count} skipped",+ restoreFailed: "Could not restore files",+ undo: "Undo",+ undone: "File restore undone",+ undoFailed: "Could not undo the file restore",+ },// The chat header's "…" menu.chatMenu: {more: "Chat options",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 96e35b0fcaa..4de6ed37d5a 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -547,6 +547,36 @@ export const es = {queueingOnHint: "Los mensajes nuevos esperan su turno.",queueingHintShared: "La cola se conserva.",},+ rewind: {+ menuItem: "Rebobinar…",+ title: "Rebobinar",+ pickDescription: "Elige un mensaje al que volver.",+ pickEmpty: "Todavía no hay mensajes a los que volver.",+ attachmentOnly: "Solo archivos adjuntos",+ chooseDescription: "El mensaje se abre para editarlo y que puedas reenviarlo. Las respuestas actuales siguen disponibles con las flechas de rama.",+ modeBoth: "Conversación y archivos",+ modeConversation: "Solo conversación",+ modeFiles: "Solo archivos",+ checking: "Comprobando cambios en archivos…",+ checkFailed: "No se pudieron comprobar los cambios en archivos: {error}",+ noFileChanges: "No hay cambios en archivos después de este mensaje",+ summary: "Archivos que restaurar: {restore}. Que eliminar: {remove}. Que recrear: {recreate}.",+ conflicts: "Cambiados desde entonces, se omitirán",+ untracked: "No se pueden restaurar",+ scopeNote: "Los programas en ejecución, los paquetes instalados y todo lo que esté fuera de la carpeta de este chat no se modifican.",+ back: "Atrás",+ cancel: "Cancelar",+ confirm: "Rebobinar",+ waitForResponse: "Espera a que termine la respuesta actual",+ restoredOne: "1 archivo restaurado",+ restoredMany: "{count} archivos restaurados",+ nothingRestored: "No había archivos que restaurar",+ skippedCount: "{count} omitidos",+ restoreFailed: "No se pudieron restaurar los archivos",+ undo: "Deshacer",+ undone: "Restauración de archivos deshecha",+ undoFailed: "No se pudo deshacer la restauración de archivos",+ },// The chat header's "…" menu.chatMenu: {more: "Opciones del chat",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 407e7dfe7f5..716ece7934d 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -547,6 +547,36 @@ export const fr = {queueingOnHint: "Les nouveaux messages attendent leur tour.",queueingHintShared: "La file d’attente est conservée.",},+ rewind: {+ menuItem: "Revenir en arrière…",+ title: "Revenir en arrière",+ pickDescription: "Choisissez un message auquel revenir.",+ pickEmpty: "Il n'y a pas encore de message auquel revenir.",+ attachmentOnly: "Pièces jointes uniquement",+ chooseDescription: "Le message s'ouvre en modification pour que vous puissiez le renvoyer. Les réponses actuelles restent accessibles avec les flèches de branche.",+ modeBoth: "Conversation et fichiers",+ modeConversation: "Conversation uniquement",+ modeFiles: "Fichiers uniquement",+ checking: "Vérification des modifications de fichiers…",+ checkFailed: "Impossible de vérifier les modifications de fichiers : {error}",+ noFileChanges: "Aucune modification de fichier après ce message",+ summary: "Fichiers à restaurer : {restore}. À supprimer : {remove}. À recréer : {recreate}.",+ conflicts: "Modifiés depuis, seront ignorés",+ untracked: "Impossible à restaurer",+ scopeNote: "Les programmes en cours, les paquets installés et tout ce qui se trouve hors du dossier de ce chat ne sont pas modifiés.",+ back: "Retour",+ cancel: "Annuler",+ confirm: "Revenir en arrière",+ waitForResponse: "Attendez la fin de la réponse en cours",+ restoredOne: "1 fichier restauré",+ restoredMany: "{count} fichiers restaurés",+ nothingRestored: "Aucun fichier à restaurer",+ skippedCount: "{count} ignorés",+ restoreFailed: "Impossible de restaurer les fichiers",+ undo: "Annuler",+ undone: "Restauration des fichiers annulée",+ undoFailed: "Impossible d'annuler la restauration des fichiers",+ },// The chat header's "…" menu.chatMenu: {more: "Options de la discussion",diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.tsindex 8a6d0e2d57c..a76a00ff8ed 100644--- a/studio/frontend/src/i18n/locales/he.ts+++ b/studio/frontend/src/i18n/locales/he.ts@@ -623,6 +623,36 @@ export const he = {queueingOnHint: "הודעות חדשות ממתינות לתורן.",queueingHintShared: "התור נשמר.",},+ rewind: {+ menuItem: "החזרה לאחור…",+ title: "החזרה לאחור",+ pickDescription: "בחרו הודעה לחזור אליה.",+ pickEmpty: "עדיין אין הודעות לחזור אליהן.",+ attachmentOnly: "קבצים מצורפים בלבד",+ chooseDescription: "ההודעה תיפתח לעריכה כדי שתוכלו לשלוח אותה שוב. התשובות הנוכחיות יישארו זמינות דרך חיצי הענפים.",+ modeBoth: "שיחה וקבצים",+ modeConversation: "שיחה בלבד",+ modeFiles: "קבצים בלבד",+ checking: "בודק שינויים בקבצים…",+ checkFailed: "לא ניתן היה לבדוק שינויים בקבצים: {error}",+ noFileChanges: "אין שינויים בקבצים אחרי הודעה זו",+ summary: "קבצים לשחזור: {restore}. להסרה: {remove}. ליצירה מחדש: {recreate}.",+ conflicts: "השתנו מאז, ידולגו",+ untracked: "לא ניתן לשחזר",+ scopeNote: "תוכנות פועלות, חבילות מותקנות וכל מה שמחוץ לתיקייה של הצ'אט הזה לא משתנים.",+ back: "חזרה",+ cancel: "ביטול",+ confirm: "החזרה לאחור",+ waitForResponse: "המתינו לסיום התשובה הנוכחית",+ restoredOne: "שוחזר קובץ אחד",+ restoredMany: "שוחזרו {count} קבצים",+ nothingRestored: "לא היו קבצים לשחזור",+ skippedCount: "{count} דולגו",+ restoreFailed: "לא ניתן היה לשחזר את הקבצים",+ undo: "ביטול פעולה",+ undone: "שחזור הקבצים בוטל",+ undoFailed: "לא ניתן היה לבטל את שחזור הקבצים",+ },chatMenu: {more: "אפשרויות צ'אט",copy: "העתקה",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex db6129301ad..70e7400cd42 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -547,6 +547,36 @@ export const hi = {queueingOnHint: "नए संदेश अपनी बारी का इंतज़ार करते हैं।",queueingHintShared: "कतार बनी रहती है।",},+ rewind: {+ menuItem: "रिवाइंड करें…",+ title: "रिवाइंड करें",+ pickDescription: "वह संदेश चुनें जिस पर वापस जाना है।",+ pickEmpty: "अभी वापस जाने के लिए कोई संदेश नहीं है।",+ attachmentOnly: "केवल अटैचमेंट",+ chooseDescription: "संदेश संपादन के लिए खुलता है ताकि आप उसे फिर से भेज सकें। मौजूदा जवाब ब्रांच तीरों से उपलब्ध रहते हैं।",+ modeBoth: "बातचीत और फ़ाइलें",+ modeConversation: "केवल बातचीत",+ modeFiles: "केवल फ़ाइलें",+ checking: "फ़ाइल बदलाव जाँचे जा रहे हैं…",+ checkFailed: "फ़ाइल बदलाव जाँचे नहीं जा सके: {error}",+ noFileChanges: "इस संदेश के बाद कोई फ़ाइल बदलाव नहीं",+ summary: "पुनर्स्थापित करने वाली फ़ाइलें: {restore}। हटाने वाली: {remove}। फिर से बनाने वाली: {recreate}।",+ conflicts: "बाद में बदली गई, छोड़ दी जाएँगी",+ untracked: "पुनर्स्थापित नहीं की जा सकतीं",+ scopeNote: "चल रहे प्रोग्राम, इंस्टॉल किए गए पैकेज और इस चैट के फ़ोल्डर के बाहर की कोई भी चीज़ नहीं बदलती।",+ back: "वापस",+ cancel: "रद्द करें",+ confirm: "रिवाइंड करें",+ waitForResponse: "मौजूदा जवाब पूरा होने तक प्रतीक्षा करें",+ restoredOne: "1 फ़ाइल पुनर्स्थापित की गई",+ restoredMany: "{count} फ़ाइलें पुनर्स्थापित की गईं",+ nothingRestored: "किसी फ़ाइल को पुनर्स्थापित करने की ज़रूरत नहीं थी",+ skippedCount: "{count} छोड़ी गईं",+ restoreFailed: "फ़ाइलें पुनर्स्थापित नहीं की जा सकीं",+ undo: "पूर्ववत करें",+ undone: "फ़ाइल पुनर्स्थापना पूर्ववत की गई",+ undoFailed: "फ़ाइल पुनर्स्थापना पूर्ववत नहीं की जा सकी",+ },// The chat header's "…" menu.chatMenu: {more: "चैट विकल्प",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 5dcd44e64c5..470b4560584 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -3095,6 +3095,36 @@ export const it = {},},},+ rewind: {+ menuItem: "Riavvolgi…",+ title: "Riavvolgi",+ pickDescription: "Scegli un messaggio a cui tornare.",+ pickEmpty: "Non ci sono ancora messaggi a cui tornare.",+ attachmentOnly: "Solo allegati",+ chooseDescription: "Il messaggio si apre in modifica così puoi inviarlo di nuovo. Le risposte attuali restano disponibili con le frecce dei rami.",+ modeBoth: "Conversazione e file",+ modeConversation: "Solo conversazione",+ modeFiles: "Solo file",+ checking: "Controllo delle modifiche ai file…",+ checkFailed: "Impossibile controllare le modifiche ai file: {error}",+ noFileChanges: "Nessuna modifica ai file dopo questo messaggio",+ summary: "File da ripristinare: {restore}. Da rimuovere: {remove}. Da ricreare: {recreate}.",+ conflicts: "Modificati nel frattempo, verranno saltati",+ untracked: "Non ripristinabili",+ scopeNote: "Programmi in esecuzione, pacchetti installati e tutto ciò che è fuori dalla cartella di questa chat non vengono modificati.",+ back: "Indietro",+ cancel: "Annulla",+ confirm: "Riavvolgi",+ waitForResponse: "Attendi che la risposta in corso finisca",+ restoredOne: "1 file ripristinato",+ restoredMany: "{count} file ripristinati",+ nothingRestored: "Nessun file da ripristinare",+ skippedCount: "{count} saltati",+ restoreFailed: "Impossibile ripristinare i file",+ undo: "Annulla",+ undone: "Ripristino dei file annullato",+ undoFailed: "Impossibile annullare il ripristino dei file",+ },// The chat header's "…" menu.chatMenu: {more: "Opzioni chat",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex dcd507219cf..097356efda2 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -548,6 +548,36 @@ export const ja = {queueingOnHint: "新しいメッセージは順番待ちになります。",queueingHintShared: "キューは保持されます。",},+ rewind: {+ menuItem: "巻き戻す…",+ title: "巻き戻す",+ pickDescription: "巻き戻す先のメッセージを選択してください。",+ pickEmpty: "巻き戻せるメッセージはまだありません。",+ attachmentOnly: "添付ファイルのみ",+ chooseDescription: "メッセージが編集モードで開き、再送信できます。現在の返信はブランチの矢印からいつでも表示できます。",+ modeBoth: "会話とファイル",+ modeConversation: "会話のみ",+ modeFiles: "ファイルのみ",+ checking: "ファイルの変更を確認しています…",+ checkFailed: "ファイルの変更を確認できませんでした: {error}",+ noFileChanges: "このメッセージ以降のファイル変更はありません",+ summary: "復元するファイル: {restore}。削除: {remove}。再作成: {recreate}。",+ conflicts: "その後変更されたためスキップします",+ untracked: "復元できません",+ scopeNote: "実行中のプログラム、インストール済みのパッケージ、このチャットのフォルダー外のものは変更されません。",+ back: "戻る",+ cancel: "キャンセル",+ confirm: "巻き戻す",+ waitForResponse: "現在の応答が終わるまでお待ちください",+ restoredOne: "1 件のファイルを復元しました",+ restoredMany: "{count} 件のファイルを復元しました",+ nothingRestored: "復元が必要なファイルはありませんでした",+ skippedCount: "{count} 件をスキップしました",+ restoreFailed: "ファイルを復元できませんでした",+ undo: "元に戻す",+ undone: "ファイルの復元を元に戻しました",+ undoFailed: "ファイルの復元を元に戻せませんでした",+ },// The chat header's "…" menu.chatMenu: {more: "チャットのオプション",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 4b08c986238..290bfb7b750 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -547,6 +547,36 @@ export const ko = {queueingOnHint: "새 메시지는 순서를 기다립니다.",queueingHintShared: "대기열은 유지됩니다.",},+ rewind: {+ menuItem: "되감기…",+ title: "되감기",+ pickDescription: "되돌아갈 메시지를 선택하세요.",+ pickEmpty: "아직 되돌아갈 메시지가 없습니다.",+ attachmentOnly: "첨부 파일만",+ chooseDescription: "메시지가 편집 모드로 열려 다시 보낼 수 있습니다. 현재 답변은 브랜치 화살표로 계속 볼 수 있습니다.",+ modeBoth: "대화와 파일",+ modeConversation: "대화만",+ modeFiles: "파일만",+ checking: "파일 변경 사항 확인 중…",+ checkFailed: "파일 변경 사항을 확인하지 못했습니다: {error}",+ noFileChanges: "이 메시지 이후 파일 변경 사항이 없습니다",+ summary: "복원할 파일: {restore}. 삭제: {remove}. 다시 만들기: {recreate}.",+ conflicts: "이후 변경되어 건너뜀",+ untracked: "복원할 수 없음",+ scopeNote: "실행 중인 프로그램, 설치된 패키지, 이 채팅 폴더 밖의 항목은 변경되지 않습니다.",+ back: "뒤로",+ cancel: "취소",+ confirm: "되감기",+ waitForResponse: "현재 응답이 끝날 때까지 기다려 주세요",+ restoredOne: "파일 1개를 복원했습니다",+ restoredMany: "파일 {count}개를 복원했습니다",+ nothingRestored: "복원할 파일이 없었습니다",+ skippedCount: "{count}개 건너뜀",+ restoreFailed: "파일을 복원하지 못했습니다",+ undo: "실행 취소",+ undone: "파일 복원을 취소했습니다",+ undoFailed: "파일 복원을 취소하지 못했습니다",+ },// The chat header's "…" menu.chatMenu: {more: "채팅 옵션",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex fcf1304b521..5359e1eeda5 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -547,6 +547,36 @@ export const ptBR = {queueingOnHint: "Mensagens novas esperam a vez.",queueingHintShared: "A fila é mantida.",},+ rewind: {+ menuItem: "Voltar no tempo…",+ title: "Voltar no tempo",+ pickDescription: "Escolha uma mensagem para a qual voltar.",+ pickEmpty: "Ainda não há mensagens para as quais voltar.",+ attachmentOnly: "Somente anexos",+ chooseDescription: "A mensagem abre para edição para que você possa reenviá-la. As respostas atuais continuam disponíveis pelas setas de ramificação.",+ modeBoth: "Conversa e arquivos",+ modeConversation: "Somente conversa",+ modeFiles: "Somente arquivos",+ checking: "Verificando alterações nos arquivos…",+ checkFailed: "Não foi possível verificar as alterações nos arquivos: {error}",+ noFileChanges: "Nenhuma alteração de arquivo após esta mensagem",+ summary: "Arquivos a restaurar: {restore}. A remover: {remove}. A recriar: {recreate}.",+ conflicts: "Alterados desde então, serão ignorados",+ untracked: "Não podem ser restaurados",+ scopeNote: "Programas em execução, pacotes instalados e tudo fora da pasta deste chat não são alterados.",+ back: "Voltar",+ cancel: "Cancelar",+ confirm: "Voltar no tempo",+ waitForResponse: "Aguarde a resposta atual terminar",+ restoredOne: "1 arquivo restaurado",+ restoredMany: "{count} arquivos restaurados",+ nothingRestored: "Nenhum arquivo precisou ser restaurado",+ skippedCount: "{count} ignorados",+ restoreFailed: "Não foi possível restaurar os arquivos",+ undo: "Desfazer",+ undone: "Restauração dos arquivos desfeita",+ undoFailed: "Não foi possível desfazer a restauração dos arquivos",+ },// The chat header's "…" menu.chatMenu: {more: "Opções do chat",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 9c821f40a43..3f58d9cc690 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -547,6 +547,36 @@ export const ru = {queueingOnHint: "Новые сообщения ждут своей очереди.",queueingHintShared: "Очередь сохраняется.",},+ rewind: {+ menuItem: "Откатить…",+ title: "Откатить",+ pickDescription: "Выберите сообщение, к которому нужно вернуться.",+ pickEmpty: "Пока нет сообщений, к которым можно вернуться.",+ attachmentOnly: "Только вложения",+ chooseDescription: "Сообщение откроется для редактирования, чтобы вы могли отправить его снова. Текущие ответы останутся доступны через стрелки ветвей.",+ modeBoth: "Беседу и файлы",+ modeConversation: "Только беседу",+ modeFiles: "Только файлы",+ checking: "Проверка изменений файлов…",+ checkFailed: "Не удалось проверить изменения файлов: {error}",+ noFileChanges: "После этого сообщения файлы не менялись",+ summary: "Файлов к восстановлению: {restore}. К удалению: {remove}. К воссозданию: {recreate}.",+ conflicts: "Изменены с тех пор, будут пропущены",+ untracked: "Невозможно восстановить",+ scopeNote: "Запущенные программы, установленные пакеты и всё за пределами папки этого чата не изменяются.",+ back: "Назад",+ cancel: "Отмена",+ confirm: "Откатить",+ waitForResponse: "Дождитесь окончания текущего ответа",+ restoredOne: "Восстановлен 1 файл",+ restoredMany: "Восстановлено файлов: {count}",+ nothingRestored: "Восстанавливать было нечего",+ skippedCount: "Пропущено: {count}",+ restoreFailed: "Не удалось восстановить файлы",+ undo: "Отменить",+ undone: "Восстановление файлов отменено",+ undoFailed: "Не удалось отменить восстановление файлов",+ },// The chat header's "…" menu.chatMenu: {more: "Параметры чата",diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.tsindex 697bf34cec2..b4e5f55b0be 100644--- a/studio/frontend/src/i18n/locales/sv.ts+++ b/studio/frontend/src/i18n/locales/sv.ts@@ -638,6 +638,36 @@ export const sv = {queueingOnHint: "Nya meddelanden väntar på sin tur.",queueingHintShared: "Kön behålls.",},+ rewind: {+ menuItem: "Spola tillbaka…",+ title: "Spola tillbaka",+ pickDescription: "Välj ett meddelande att spola tillbaka till.",+ pickEmpty: "Det finns inga meddelanden att spola tillbaka till än.",+ attachmentOnly: "Endast bilagor",+ chooseDescription: "Meddelandet öppnas för redigering så att du kan skicka det igen. De nuvarande svaren finns kvar via grenpilarna.",+ modeBoth: "Konversation och filer",+ modeConversation: "Endast konversation",+ modeFiles: "Endast filer",+ checking: "Kontrollerar filändringar…",+ checkFailed: "Det gick inte att kontrollera filändringar: {error}",+ noFileChanges: "Inga filändringar efter det här meddelandet",+ summary: "Filer att återställa: {restore}. Att ta bort: {remove}. Att återskapa: {recreate}.",+ conflicts: "Ändrade sedan dess, hoppas över",+ untracked: "Kan inte återställas",+ scopeNote: "Program som körs, installerade paket och allt utanför den här chattens mapp ändras inte.",+ back: "Tillbaka",+ cancel: "Avbryt",+ confirm: "Spola tillbaka",+ waitForResponse: "Vänta tills det aktuella svaret är klart",+ restoredOne: "Återställde 1 fil",+ restoredMany: "Återställde {count} filer",+ nothingRestored: "Inga filer behövde återställas",+ skippedCount: "{count} överhoppade",+ restoreFailed: "Det gick inte att återställa filerna",+ undo: "Ångra",+ undone: "Filåterställningen ångrades",+ undoFailed: "Det gick inte att ångra filåterställningen",+ },chatMenu: {more: "Chattalternativ",copy: "Kopiera",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex fcfcfd1b2ab..d1a57254a2c 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -547,6 +547,36 @@ export const zhCN = {queueingOnHint: "新消息会排队并按顺序执行。",queueingHintShared: "队列会保留。",},+ rewind: {+ menuItem: "回退…",+ title: "回退",+ pickDescription: "选择要回退到的消息。",+ pickEmpty: "还没有可以回退到的消息。",+ attachmentOnly: "仅附件",+ chooseDescription: "该消息会进入编辑状态,方便你重新发送。当前回复仍可通过分支箭头查看。",+ modeBoth: "对话和文件",+ modeConversation: "仅对话",+ modeFiles: "仅文件",+ checking: "正在检查文件更改…",+ checkFailed: "无法检查文件更改:{error}",+ noFileChanges: "此消息之后没有文件更改",+ summary: "要恢复的文件:{restore}。要删除:{remove}。要重新创建:{recreate}。",+ conflicts: "之后已被更改,将跳过",+ untracked: "无法恢复",+ scopeNote: "正在运行的程序、已安装的软件包以及此聊天文件夹之外的内容都不会更改。",+ back: "返回",+ cancel: "取消",+ confirm: "回退",+ waitForResponse: "请等待当前回复完成",+ restoredOne: "已恢复 1 个文件",+ restoredMany: "已恢复 {count} 个文件",+ nothingRestored: "没有需要恢复的文件",+ skippedCount: "已跳过 {count} 个",+ restoreFailed: "无法恢复文件",+ undo: "撤销",+ undone: "已撤销文件恢复",+ undoFailed: "无法撤销文件恢复",+ },// The chat header's "…" menu.chatMenu: {more: "聊天选项",diff --git a/studio/frontend/tests/chat-rewind.test.ts b/studio/frontend/tests/chat-rewind.test.tsnew file mode 100644index 00000000000..cbcc0b1fc02--- /dev/null+++ b/studio/frontend/tests/chat-rewind.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// /rewind: the command match, the turn ids sent to POST /rewind, and the turn id every+// completion carries so the backend can key a turn's file checkpoints to its prompt.++import assert from "node:assert/strict";+import test from "node:test";+import { readSrc } from "./helpers/kit.ts";+import {+ collectRewindTurnIds,+ defaultRewindMode,+ isRewindCommand,+ rewindPickerEntries,+ userMessageIdRequestField,+} from "../src/features/chat/utils/rewind.ts";++test("only the bare /rewind command matches", () => {+ for (const text of ["/rewind", " /rewind\n", "/REWIND", "/Rewind "]) {+ assert.equal(isRewindCommand(text), true, JSON.stringify(text));+ }+ for (const text of ["", "/rewind now", "rewind", "/rewinds", "please /rewind", "/ rewind"]) {+ assert.equal(isRewindCommand(text), false, JSON.stringify(text));+ }+});++const branch = [+ { id: "u1", role: "user", content: [{ type: "text", text: "first" }] },+ { id: "a1", role: "assistant", content: [] },+ { id: "u2", role: "user", content: [{ type: "text", text: "second\n line" }] },+ { id: "a2", role: "assistant", content: [] },+ { id: "u3", role: "user", content: [{ type: "image", image: "x" }] },+ { id: "a3", role: "assistant", content: [] },+];++test("turn ids run from the chosen prompt to the end of the branch, in order", () => {+ assert.deepEqual(collectRewindTurnIds(branch, "u1"), ["u1", "u2", "u3"]);+ assert.deepEqual(collectRewindTurnIds(branch, "u2"), ["u2", "u3"]);+ assert.deepEqual(collectRewindTurnIds(branch, "u3"), ["u3"]);+});++test("an assistant id or a message off the branch yields no turns", () => {+ assert.deepEqual(collectRewindTurnIds(branch, "a1"), []);+ assert.deepEqual(collectRewindTurnIds(branch, "missing"), []);+});++test("the picker lists prompts newest first on one line", () => {+ assert.deepEqual(rewindPickerEntries(branch), [+ { id: "u3", preview: "" },+ { id: "u2", preview: "second line" },+ { id: "u1", preview: "first" },+ ]);+ const long = rewindPickerEntries([{ id: "u", role: "user", content: "x".repeat(200) }]);+ assert.ok(long[0].preview.length <= 80);+ assert.ok(long[0].preview.endsWith("…"));+});++test("files are offered by default only when the turns changed files", () => {+ assert.equal(defaultRewindMode(true), "both");+ assert.equal(defaultRewindMode(false), "conversation");+});++test("user_message_id is omitted without a user message", () => {+ assert.deepEqual(userMessageIdRequestField("m1"), { user_message_id: "m1" });+ assert.deepEqual(userMessageIdRequestField(undefined), {});+ assert.deepEqual(userMessageIdRequestField(""), {});+});++test("the completion payload carries user_message_id on the local and external tool paths", () => {+ const adapter = readSrc("features/chat/api/chat-adapter.ts");+ assert.match(+ adapter,+ /const userMessageIdField = userMessageIdRequestField\(\s*resolvedThreadId && isThreadIncognito\(resolvedThreadId\)\s*\? undefined\s*: generationUserMessage\?\.id,?\s*\);/,+ );+ // Local body (also the durable run's requestPayload): beside thread_id.+ assert.match(+ adapter,+ /\.\.\.\(resolvedThreadId \? \{ thread_id: resolvedThreadId \} : \{\}\),\s*\.\.\.userMessageIdField,\s*\.\.\.\(useAdapter === undefined/,+ );+ // External provider with Studio-run tools: beside session_id.+ assert.match(+ adapter,+ /\? \{ session_id: sandboxSessionId \}\s*: \{\}\),\s*\.\.\.userMessageIdField,/,+ );+ // The durable run posts the same requestPayload, so the field rides inside it, not beside it.+ assert.match(+ adapter,+ /userMessageId: generationUserMessage!\.id,\s*assistantMessageId: unstable_assistantMessageId!,\s*requestPayload,/,+ );+});++test("the composer opens the rewind picker instead of sending /rewind", () => {+ const thread = readSrc("components/assistant-ui/thread.tsx");+ const submit = thread.slice(thread.indexOf("const handleSubmit = useCallback("));+ const intercept = submit.indexOf("isRewindCommand(composerText)");+ assert.ok(intercept > 0);+ assert.ok(intercept < submit.indexOf("if (disabled || shouldBlockSend())"));+ assert.ok(intercept < submit.indexOf("interceptSend(event)"));+ assert.match(thread, /<RewindMessageMenuItem \/>\s*<DeleteMessageMenuItem \/>/);+});