Skip to content

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.

Studio: rewind puts back files edit_file changed inside dot folders (#16017)

Nilay9d203e67eb3f
diff --git a/studio/backend/core/inference/file_history.py b/studio/backend/core/inference/file_history.py
index 55601391b55..46b2a6be194 100644
--- a/studio/backend/core/inference/file_history.py
+++ b/studio/backend/core/inference/file_history.py
@@ -135,10 +135,17 @@ def _probe(workdir: str, rels: "Iterable[str]") -> dict:
"""Regular files among *rels*, keyed as a walk keys them; one behind a linked folder counts as gone."""
root = os.path.realpath(workdir)
found = {}
+ listings: dict = {}
for rel in rels:
path = os.path.join(root, *rel.split("/"))
+ parent = os.path.dirname(path)
try:
- if os.path.realpath(os.path.dirname(path)) != os.path.dirname(path):
+ if os.path.realpath(parent) != parent:
+ continue
+ # A case-insensitive volume finds "Readme.md" after a rename to "README.md".
+ if parent not in listings:
+ listings[parent] = set(os.listdir(parent))
+ if os.path.basename(path) not in listings[parent]:
continue
info = os.lstat(path)
except OSError:
@@ -278,6 +285,9 @@ class FileHistory:
``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)
+ if paths is None and complete:
+ # edit_file records files no walk lists, such as .github/workflows/ci.yml.
+ snap = {**_probe(workdir, [rel for rel in state if rel not in snap]), **snap}
first = (
not state
and self._db.execute("SELECT 1 FROM workdirs WHERE workdir=?", (workdir,)).fetchone()
@@ -334,13 +344,20 @@ class FileHistory:
return {} # the baseline is where history starts, not a change
return changes
- def _walk_sync(self, workdir: str, walk) -> dict:
+ def _walk_sync(
+ self,
+ workdir: str,
+ walk,
+ extra = (),
+ ) -> dict:
snap, complete = walk(workdir)
changes = self._sync(workdir, snap, None, complete)
+ missed = {rel for rel in extra if rel not in snap}
if not complete:
# A capped walk never reached these: read them directly, or a rewind trusts a stale state
# and overwrites the user's later edit.
- missed = {rel for rel in self._load_state(workdir) if rel not in snap}
+ missed.update(rel for rel in self._load_state(workdir) if rel not in snap)
+ if missed:
changes.update(self._sync(workdir, _probe(workdir, missed), missed))
return changes
@@ -522,23 +539,23 @@ class FileHistory:
return report
def _rewind_folder(self, chat_id, workdir, rows, walk, report, dry_run, force, undo_turn):
+ 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)
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)
+ None, workdir, None, "external", self._walk_sync(workdir, walk, target)
),
)
- 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(
@@ -584,7 +601,7 @@ class FileHistory:
self._transaction(
workdir,
lambda: self._record(
- chat_id, workdir, undo_turn, "rewind", self._walk_sync(workdir, walk)
+ chat_id, workdir, undo_turn, "rewind", self._walk_sync(workdir, walk, target)
),
)
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 29a4163dd5f..fe4b8979e5a 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -21473,20 +21473,6 @@ def _snapshot_and_history_begin(
return before
-def _walk_lists(workdir: str, rel: str) -> bool:
- """Whether `_history_walk` 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 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:
@@ -21499,7 +21485,11 @@ def _history_begin_file(session_id: "str | None", target: str) -> dict:
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, ()):
+ if (
+ not all(map(_servable_segment, rel.split("/")))
+ or rel in _INTERNAL_SANDBOX_FILES
+ or not file_history.tracked(rel, ())
+ ):
return {}
try:
baseline = file_history.store().needs_baseline(workdir)
diff --git a/studio/backend/tests/test_file_history.py b/studio/backend/tests/test_file_history.py
index 29d55bd14fe..e1458c83936 100644
--- a/studio/backend/tests/test_file_history.py
+++ b/studio/backend/tests/test_file_history.py
@@ -417,6 +417,60 @@ def test_files_deep_in_the_folder_are_rewound(chat, monkeypatch):
assert route.read_text(encoding = "utf-8") == helpers.read_text(encoding = "utf-8") == "v1\n"
+def test_edit_file_changes_inside_dot_folders_are_rewound(chat):
+ workdir, history = chat
+ ci = workdir / ".github" / "workflows" / "ci.yml"
+ ci.parent.mkdir(parents = True)
+ ci.write_text("on: push\n", encoding = "utf-8")
+ file_history.set_turn("chat-1", "u1")
+ _edit(".github/workflows/ci.yml", "on: push", "on: [push, pull_request]")
+ execute_tool("python", {"code": "open('app.py', 'w').write('x = 1')"}, session_id = "s")
+
+ preview = _rewind(history, ["u1"], dry_run = True)
+ assert preview.restored == [".github/workflows/ci.yml"] and preview.deleted == ["app.py"]
+ assert _rewind(history, ["u1"]).restored == [".github/workflows/ci.yml"]
+ assert ci.read_text(encoding = "utf-8") == "on: push\n"
+
+
+def test_a_dot_folder_file_recreated_by_hand_is_a_conflict(chat):
+ workdir, history = chat
+ ci = workdir / ".github" / "ci.yml"
+ ci.parent.mkdir()
+ ci.write_text("a\n", encoding = "utf-8")
+ file_history.set_turn("chat-1", "u1")
+ _edit(".github/ci.yml", "a", "b")
+ file_history.set_turn("chat-1", "u2")
+ execute_tool("python", {"code": "import os; os.remove('.github/ci.yml')"}, session_id = "s")
+ ci.write_text("user\n", encoding = "utf-8")
+
+ assert _rewind(history, ["u2"]).conflicts == [".github/ci.yml"]
+ assert ci.read_text(encoding = "utf-8") == "user\n"
+
+ ci.unlink()
+ report = _rewind(history, ["u2"])
+ assert report.recreated == [".github/ci.yml"]
+ assert _rewind(history, [report.undo_turn_id]).deleted == [".github/ci.yml"]
+ assert not ci.exists()
+ assert _rewind(history, ["u2"]).recreated == [".github/ci.yml"]
+ ci.write_text("user\n", encoding = "utf-8")
+ assert _rewind(history, ["u1"]).conflicts == [".github/ci.yml"]
+ assert ci.read_text(encoding = "utf-8") == "user\n"
+
+
+def test_a_rename_that_only_changes_case_is_rewound(chat):
+ workdir, history = chat
+ file_history.set_turn("chat-1", "u1")
+ execute_tool("python", {"code": "open('Readme.md', 'w').write('keep')"}, session_id = "s")
+ file_history.set_turn("chat-1", "u2")
+ execute_tool(
+ "python", {"code": "import os; os.rename('Readme.md', 'README.md')"}, session_id = "s"
+ )
+
+ _rewind(history, ["u2"])
+ assert [p.name for p in workdir.iterdir() if p.name.lower() == "readme.md"] == ["Readme.md"]
+ assert (workdir / "Readme.md").read_text(encoding = "utf-8") == "keep"
+
+
@pytest.mark.skipif(os.name != "posix", reason = "uses a POSIX shell")
def test_a_file_past_the_download_card_walk_is_rewound(chat, monkeypatch):
workdir, _history = chat