Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): keep open editor tabs and unsaved text across a restart
rubenluetke10-beep9d2935f16147
diff --git a/jarvis/agentic_ide/editor_backups.py b/jarvis/agentic_ide/editor_backups.pynew file mode 100644index 0000000000..d814804d2b--- /dev/null+++ b/jarvis/agentic_ide/editor_backups.py@@ -0,0 +1,150 @@+"""Keep the code editor's open tabs and unsaved text across an app restart.++Closing or restarting the desktop app must not cost the user typed code. The+editor therefore mirrors two things here, per workspace folder:++* the open tabs (path, edit/diff mode, preview flag) and the active one, and+* a backup of every buffer with unsaved edits, together with the version of+ the file the edits were made on.++On the next start the editor reopens the tabs and lays each backup over the+file it belongs to. If the file changed on disk meanwhile, the restored buffer+shows the usual conflict bar instead of overwriting anything.++Storage is the per-user data directory (one folder per IDE instance, so the+dev app never restores the live app's buffers), keyed by a hash of the+workspace folder: a workspace id may change between runs, its folder does not.+Every write is atomic; a backup is one small file per edited path, so typing+in one file never rewrites another's backup.+"""++from __future__ import annotations++import hashlib+import json+import os+import tempfile+import time+from pathlib import Path+from typing import Any++from loguru import logger++from jarvis.core.instance import current_instance+from jarvis.core.paths import user_data_dir++from .file_editing import MAX_EDITABLE_BYTES, EditError, _normalise_relative++__all__ = [+ "MAX_TABS",+ "drop_backup",+ "load_state",+ "save_backup",+ "save_tabs",+]++#: More open tabs than this are not worth restoring; the oldest are dropped.+MAX_TABS = 60+_MODES = ("edit", "diff")+++def _store_root() -> Path:+ return user_data_dir() / f"editor-backups{current_instance().state_file_suffix}"+++def _folder_dir(folder: str | os.PathLike[str]) -> Path:+ real = os.path.normcase(os.path.realpath(os.fspath(folder)))+ return _store_root() / hashlib.sha256(real.encode("utf-8")).hexdigest()[:24]+++def _backup_file(folder: str | os.PathLike[str], path: str) -> Path:+ digest = hashlib.sha256(path.encode("utf-8")).hexdigest()[:24]+ return _folder_dir(folder) / "backups" / f"{digest}.json"+++def _write_json(target: Path, payload: dict[str, Any]) -> None:+ target.parent.mkdir(parents=True, exist_ok=True)+ handle, temp_name = tempfile.mkstemp(prefix=".", suffix=".tmp", dir=target.parent)+ try:+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(payload, stream, ensure_ascii=False)+ os.replace(temp_name, target)+ finally:+ if os.path.exists(temp_name):+ try:+ os.unlink(temp_name)+ except OSError as exc:+ logger.warning("Editor backup: could not remove temp file: {}", exc)+++def _read_json(source: Path) -> dict[str, Any] | None:+ try:+ data = json.loads(source.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError) as exc:+ # A damaged backup must not keep the editor from starting.+ logger.warning("Editor backup: ignoring unreadable {}: {}", source.name, exc)+ return None+ return data if isinstance(data, dict) else None+++def save_tabs(+ folder: str | os.PathLike[str], tabs: list[dict[str, Any]], active: str | None+) -> None:+ """Remember the open tabs of one workspace, in order."""+ clean: list[dict[str, Any]] = []+ for tab in tabs[-MAX_TABS:]:+ path = _normalise_relative(str(tab.get("path", "")))+ mode = tab.get("mode") if tab.get("mode") in _MODES else "edit"+ clean.append({"path": path, "mode": mode, "preview": bool(tab.get("preview"))})+ active_path = _normalise_relative(active) if active else None+ _write_json(_folder_dir(folder) / "tabs.json", {"tabs": clean, "active": active_path})+++def save_backup(+ folder: str | os.PathLike[str],+ path: str,+ text: str,+ *,+ base_version: str | None,+ encoding: str,+) -> None:+ """Keep the unsaved text of one file until it is saved or discarded."""+ relative = _normalise_relative(path)+ if len(text.encode("utf-8")) > MAX_EDITABLE_BYTES:+ raise EditError("That buffer is too large to back up.")+ _write_json(+ _backup_file(folder, relative),+ {+ "path": relative,+ "text": text,+ "base_version": base_version,+ "encoding": encoding,+ "saved_at": time.time(),+ },+ )+++def drop_backup(folder: str | os.PathLike[str], path: str) -> None:+ """Forget a backup: the buffer was saved, reverted or discarded."""+ target = _backup_file(folder, _normalise_relative(path))+ try:+ target.unlink()+ except FileNotFoundError:+ return+++def load_state(folder: str | os.PathLike[str]) -> dict[str, Any]:+ """The tabs and backups to restore for one workspace folder."""+ root = _folder_dir(folder)+ tabs_doc = _read_json(root / "tabs.json") or {}+ tabs = [tab for tab in tabs_doc.get("tabs", []) if isinstance(tab, dict)]+ backups: list[dict[str, Any]] = []+ backup_dir = root / "backups"+ if backup_dir.is_dir():+ for entry in sorted(backup_dir.glob("*.json")):+ doc = _read_json(entry)+ if doc and isinstance(doc.get("path"), str) and isinstance(doc.get("text"), str):+ backups.append(doc)+ return {"tabs": tabs, "active": tabs_doc.get("active"), "backups": backups}diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 73d6945984..dc9d7f1739 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -84,6 +84,7 @@ from jarvis.agentic_ide import (change_authors,drop_analysis,drops,+ editor_backups,file_editing,git_changes,layout_tree,@@ -999,6 +1000,28 @@ class MoveWorkspaceEntryRequest(BaseModel):destination: str = Field(min_length=1, max_length=4096)+class EditorTabState(BaseModel):+ path: str = Field(min_length=1, max_length=4096)+ mode: Literal["edit", "diff"] = "edit"+ preview: bool = False+++class EditorTabsRequest(BaseModel):+ """The code editor's open tabs for one workspace, in order."""++ tabs: list[EditorTabState] = Field(default_factory=list, max_length=200)+ active: str | None = Field(default=None, max_length=4096)+++class EditorBackupRequest(BaseModel):+ """Unsaved editor text, kept until it is saved or discarded."""++ path: str = Field(min_length=1, max_length=4096)+ text: str+ base_version: str | None = Field(default=None, max_length=128)+ encoding: str = Field(default="utf-8", max_length=40)++class DeleteWorkspaceEntryRequest(BaseModel):"""Delete one file or folder; it goes to the system trash unless permanent."""@@ -2126,6 +2149,68 @@ async def move_workspace_entry(return {"workspace_id": workspace_id, "path": moved}+ "/workspaces/{workspace_id}/editor-state",+ summary="The code editor's open tabs and unsaved text to restore",+)+async def get_editor_state(workspace_id: str) -> dict[str, object]:+ """What the editor had open, and every buffer that was not saved, last run."""+ folder = _workspace_folder(workspace_id)+ state = await asyncio.to_thread(editor_backups.load_state, folder)+ return {"workspace_id": workspace_id, **state}+++ "/workspaces/{workspace_id}/editor-state/tabs",+ summary="Remember the code editor's open tabs",+)+async def put_editor_tabs(workspace_id: str, req: EditorTabsRequest) -> dict[str, object]:+ folder = _workspace_folder(workspace_id)+ try:+ await asyncio.to_thread(+ editor_backups.save_tabs,+ folder,+ [tab.model_dump() for tab in req.tabs],+ req.active,+ )+ except file_editing.EditError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True}+++ "/workspaces/{workspace_id}/editor-state/backup",+ summary="Keep unsaved editor text across a restart",+)+async def put_editor_backup(workspace_id: str, req: EditorBackupRequest) -> dict[str, object]:+ folder = _workspace_folder(workspace_id)+ try:+ await asyncio.to_thread(+ editor_backups.save_backup,+ folder,+ req.path,+ req.text,+ base_version=req.base_version,+ encoding=req.encoding,+ )+ except file_editing.EditError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True}+++ "/workspaces/{workspace_id}/editor-state/backup",+ summary="Forget the unsaved-text backup of one file",+)+async def delete_editor_backup(workspace_id: str, path: str) -> dict[str, object]:+ folder = _workspace_folder(workspace_id)+ try:+ await asyncio.to_thread(editor_backups.drop_backup, folder, path)+ except file_editing.EditError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"ok": True}++@router.post("/workspaces/{workspace_id}/entries/delete",summary="Delete a file or folder in a workspace",diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsxindex 23e40be9f9..b4dd14577d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx@@ -27,6 +27,7 @@ import { absoluteWorkspacePath } from "@/components/agentic/sidePanel/explorer/eimport { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";import { checkDisk, discardFile, languageName, revertFile, saveAll, saveFile } from "./editorModels";import { QuickOpen } from "./QuickOpen";+import { restoreWorkspace } from "./editorPersistence";import { renderKindOf } from "./fileKinds";const EditorSurface = lazy(() => import("./EditorSurface"));@@ -92,6 +93,11 @@ export function CodeEditorStage({const activeFile = activeTab ? files[activeTab.fileKey] : undefined;const shown = visible && activeTab !== null;+ // Reopen what this workspace had open last run, unsaved text included.+ useEffect(() => {+ if (workspaceId) void restoreWorkspace(workspaceId);+ }, [workspaceId]);+// Closing the last tab hands the stage back to the terminals.useEffect(() => {if (visible && workspaceId && tabs.length === 0) useCodeEditorStore.getState().setVisible(false);diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.tsindex f98d24a1b0..f722bd4c03 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts@@ -140,3 +140,50 @@ export async function deleteEntry(workspaceId: string, path: string, permanent =if (!res.ok) throw new Error((await failure(res)).message);return (await res.json()) as { trashed: boolean };}++export interface EditorTabRecord {+ path: string;+ mode: "edit" | "diff";+ preview: boolean;+}++export interface EditorBackup {+ path: string;+ text: string;+ /** The file version the unsaved edits were made on; null for a file not on disk. */+ base_version: string | null;+ encoding: TextEncoding;+ saved_at: number;+}++export interface EditorState {+ tabs: EditorTabRecord[];+ active: string | null;+ backups: EditorBackup[];+}++export function fetchEditorState(workspaceId: string): Promise<EditorState> {+ return send<EditorState>(`${base(workspaceId)}/editor-state`);+}++/** `keepalive` lets the request finish while the window is closing. */+export async function putEditorTabs(+ workspaceId: string,+ tabs: EditorTabRecord[],+ active: string | null,+ keepalive = false,+): Promise<void> {+ await send(`${base(workspaceId)}/editor-state/tabs`, { ...json("PUT", { tabs, active }), keepalive });+}++export async function putEditorBackup(+ workspaceId: string,+ backup: Omit<EditorBackup, "saved_at">,+ keepalive = false,+): Promise<void> {+ await send(`${base(workspaceId)}/editor-state/backup`, { ...json("PUT", backup), keepalive });+}++export async function deleteEditorBackup(workspaceId: string, path: string): Promise<void> {+ await send(`${base(workspaceId)}/editor-state/backup?${query(path)}`, { method: "DELETE" });+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.tsindex 9c37c602e7..a84fdbafb4 100644--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts@@ -5,6 +5,9 @@ import { useCodeEditorStore, type EditorFile } from "@/store/codeEditor";import { viewKindOf } from "./fileKinds";import {SaveConflictError,+ deleteEditorBackup,+ putEditorBackup,+ type EditorBackup,fetchFileVersion,fetchHeadText,loadTextFile,@@ -107,7 +110,10 @@ function createEntry(const entry: Entry = {model,saved: saved ? model.getAlternativeVersionId() : -1,- listener: model.onDidChangeContent(() => syncDirty(fileKey)),+ listener: model.onDidChangeContent(() => {+ syncDirty(fileKey);+ scheduleBackup(fileKey);+ }),};entries.set(fileKey, entry);return entry;@@ -159,6 +165,85 @@ function toast(message: string): void {useEventStore.getState().pushToast("error", message);}+// ---- Hot exit: unsaved text survives closing the app ----------------------++/** How long typing has to pause before the unsaved text is backed up. */+const BACKUP_DELAY_MS = 600;+const backupTimers = new Map<string, number>();+/** Files that have a backup on the server, so a clean buffer knows to drop it. */+const backedUp = new Set<string>();+/** Backups from last run, laid over their file when it loads. */+const pendingRestores = new Map<string, EditorBackup>();++export function queueRestore(fileKey: string, backup: EditorBackup): void {+ pendingRestores.set(fileKey, backup);+ backedUp.add(fileKey);+}++function sendBackup(fileKey: string, keepalive = false): void {+ backupTimers.delete(fileKey);+ const file = store().files[fileKey];+ const entry = entries.get(fileKey);+ if (!file || !entry) return;+ if (file.dirty) {+ backedUp.add(fileKey);+ void putEditorBackup(+ file.workspaceId,+ { path: file.path, text: entry.model.getValue(), base_version: file.version, encoding: file.encoding },+ keepalive,+ ).catch((error: unknown) => console.warn("Editor backup failed:", (error as Error).message));+ } else {+ forgetBackup(fileKey);+ }+}++function scheduleBackup(fileKey: string): void {+ window.clearTimeout(backupTimers.get(fileKey));+ backupTimers.set(fileKey, window.setTimeout(() => sendBackup(fileKey), BACKUP_DELAY_MS));+}++/** The buffer was saved, reverted or discarded: its backup is no longer needed. */+function forgetBackup(fileKey: string, file = store().files[fileKey]): void {+ window.clearTimeout(backupTimers.get(fileKey));+ backupTimers.delete(fileKey);+ if (!backedUp.delete(fileKey) || !file) return;+ void deleteEditorBackup(file.workspaceId, file.path).catch((error: unknown) =>+ console.warn("Editor backup cleanup failed:", (error as Error).message),+ );+}++/** Send every backup still waiting for its typing pause, now (the window is closing). */+export function flushBackups(): void {+ for (const fileKey of [...backupTimers.keys()]) {+ window.clearTimeout(backupTimers.get(fileKey));+ sendBackup(fileKey, true);+ }+}++/**+ * Lay last run's unsaved text over the freshly loaded file. The buffer keeps+ * the version the edits were made on, so if the file changed on disk since,+ * a save meets the usual conflict instead of overwriting the newer file.+ */+function applyRestore(fileKey: string, diskVersion: string | null): void {+ const backup = pendingRestores.get(fileKey);+ const entry = entries.get(fileKey);+ if (!backup || !entry) return;+ pendingRestores.delete(fileKey);+ const { model } = entry;+ if (model.getValue() !== backup.text) {+ model.pushEditOperations([], [{ range: model.getFullModelRange(), text: backup.text }], () => null);+ model.pushStackElement();+ }+ const changedOnDisk = backup.base_version !== diskVersion;+ store().patchFile(fileKey, {+ version: backup.base_version,+ deleted: diskVersion === null && backup.base_version !== null,+ conflict: changedOnDisk && diskVersion !== null ? { diskVersion } : null,+ });+ syncDirty(fileKey);+}+/** Load a file's text from disk into its model (or record why it cannot be edited). */export async function loadFile(fileKey: string): Promise<void> {const file = store().files[fileKey];@@ -188,6 +273,7 @@ export async function loadFile(fileKey: string): Promise<void> {conflict: null,dirty: false,});+ applyRestore(fileKey, loaded.version);} catch (error) {if (!store().files[fileKey]) return;// A file deleted on disk (a deleted entry in Changes) opens as an empty@@ -200,6 +286,7 @@ export async function loadFile(fileKey: string): Promise<void> {if (missing && store().files[fileKey] && !entries.has(fileKey)) {createEntry(fileKey, file, "", "\n", true);store().patchFile(fileKey, { status: "ready", error: "", version: null, deleted: true, dirty: false });+ applyRestore(fileKey, null);return;}if (store().files[fileKey]) store().patchFile(fileKey, { status: "error", error: (error as Error).message });@@ -261,6 +348,7 @@ export async function saveFile(fileKey: string, { overwrite = false } = {}): Procreate,});entry.saved = sent;+ if (entry.model.getAlternativeVersionId() === sent) forgetBackup(fileKey);bumpEpoch(fileKey);store().patchFile(fileKey, {saving: false,@@ -327,6 +415,7 @@ export async function revertFile(fileKey: string, { follow = false } = {}): Prom/** Forget unsaved edits without touching disk (closing with "Don't save"). */export function discardFile(fileKey: string): void {+ forgetBackup(fileKey);disposeFile(fileKey);if (store().files[fileKey]) store().patchFile(fileKey, { dirty: false, status: "loading" });}@@ -378,7 +467,10 @@ export function moveModels(workspaceId: string, from: string, to: string): voidconst text = entry.model.getValue();const eol = entry.model.getEOL() === "\r\n" ? "\r\n" : "\n";const dirty = entry.model.getAlternativeVersionId() !== entry.saved;+ forgetBackup(fileKey);disposeFile(fileKey);createEntry(`${prefix}${moved}`, { workspaceId, path: moved }, text, eol, !dirty);+ // The backup follows the file to its new name once the store has moved it.+ if (dirty) scheduleBackup(`${prefix}${moved}`);}}diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.tsnew file mode 100644index 0000000000..1de42d53d1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorPersistence.ts@@ -0,0 +1,78 @@+import { useCodeEditorStore, fileKeyOf, tabsOf } from "@/store/codeEditor";+import { fetchEditorState, putEditorTabs } from "./editorApi";+import { flushBackups, queueRestore } from "./editorModels";++/**+ * Hot exit: the editor's open tabs and unsaved text come back after the app+ * closes or restarts (backend: jarvis/agentic_ide/editor_backups.py).+ *+ * Tabs are written shortly after they change; unsaved text is backed up by+ * editorModels after each pause in typing; anything still waiting is sent with+ * `keepalive` when the window goes away.+ */+const TABS_DELAY_MS = 800;+const restored = new Set<string>();+const restoring = new Set<string>();+const tabTimers = new Map<string, number>();+const lastSent = new Map<string, string>();++function snapshot(workspaceId: string) {+ const state = useCodeEditorStore.getState();+ const tabs = tabsOf(state, workspaceId).map(({ path, mode, preview }) => ({ path, mode, preview }));+ const active = tabsOf(state, workspaceId).find((tab) => tab.key === state.active[workspaceId])?.path ?? null;+ return { tabs, active, key: JSON.stringify([tabs, active]) };+}++function sendTabs(workspaceId: string, keepalive = false): void {+ tabTimers.delete(workspaceId);+ const { tabs, active, key } = snapshot(workspaceId);+ if (lastSent.get(workspaceId) === key) return;+ lastSent.set(workspaceId, key);+ void putEditorTabs(workspaceId, tabs, active, keepalive).catch((error: unknown) => {+ lastSent.delete(workspaceId);+ console.warn("Editor tabs could not be remembered:", (error as Error).message);+ });+}++// Only workspaces whose last state has been read are written back, so an empty+// editor at start-up never overwrites the tabs it is about to restore.+useCodeEditorStore.subscribe((state, previous) => {+ if (state.tabs === previous.tabs && state.active === previous.active) return;+ for (const workspaceId of restored) {+ window.clearTimeout(tabTimers.get(workspaceId));+ tabTimers.set(workspaceId, window.setTimeout(() => sendTabs(workspaceId), TABS_DELAY_MS));+ }+});++/** Put back what a workspace had open last run (once per window). */+export async function restoreWorkspace(workspaceId: string): Promise<void> {+ if (restored.has(workspaceId) || restoring.has(workspaceId)) return;+ restoring.add(workspaceId);+ try {+ const state = await fetchEditorState(workspaceId);+ const paths = new Set(state.tabs.map((tab) => tab.path));+ for (const backup of state.backups) {+ queueRestore(fileKeyOf(workspaceId, backup.path), backup);+ // A backup always gets a tab, even if its tab record was lost.+ if (!paths.has(backup.path)) state.tabs.push({ path: backup.path, mode: "edit", preview: false });+ }+ const store = useCodeEditorStore.getState();+ store.restoreTabs(workspaceId, state.tabs, state.active);+ // The dot shows (and the bundle reload waits) before the file is opened.+ for (const backup of state.backups) store.patchFile(fileKeyOf(workspaceId, backup.path), { dirty: true });+ lastSent.set(workspaceId, snapshot(workspaceId).key);+ restored.add(workspaceId);+ } catch (error) {+ // Nothing to restore is a normal first run; the next mount asks again.+ console.warn("Editor state could not be restored:", (error as Error).message);+ } finally {+ restoring.delete(workspaceId);+ }+}++if (typeof window !== "undefined") {+ window.addEventListener("pagehide", () => {+ flushBackups();+ for (const workspaceId of restored) sendTabs(workspaceId, true);+ });+}diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.test.ts b/jarvis/ui/web/frontend/src/store/codeEditor.test.tsindex 4ecc71d1e6..db5c9e0499 100644--- a/jarvis/ui/web/frontend/src/store/codeEditor.test.ts+++ b/jarvis/ui/web/frontend/src/store/codeEditor.test.ts@@ -74,6 +74,26 @@ describe("code editor tabs", () => {expect(store().files[fileKeyOf("w1", "srcx/b.ts")].deleted).toBe(false);});+ it("restores last run's tabs without bringing the editor forward", () => {+ store().openFile("w1", "open.ts", { preview: false });+ useCodeEditorStore.setState({ visible: false });+ store().restoreTabs(+ "w1",+ [+ { path: "open.ts", mode: "edit", preview: false },+ { path: "b.md", mode: "diff", preview: true },+ ],+ "b.md",+ );+ expect(paths()).toEqual(["open.ts", "b.md*"]);+ expect(store().visible).toBe(false);+ // A tab that was already active stays active.+ expect(store().active.w1).toBe(tabKeyOf("edit", fileKeyOf("w1", "open.ts")));++ store().restoreTabs("w2", [{ path: "x.ts", mode: "edit", preview: false }], "x.ts");+ expect(store().active.w2).toBe(tabKeyOf("edit", fileKeyOf("w2", "x.ts")));+ });+it("asks the editor to reveal a line", () => {store().openFile("w1", "a.ts", { line: 42, column: 3 });expect(store().reveal).toMatchObject({ fileKey: fileKeyOf("w1", "a.ts"), line: 42, column: 3 });diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.tsindex 925144cd6e..1a2d324e9a 100644--- a/jarvis/ui/web/frontend/src/store/codeEditor.ts+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts@@ -105,6 +105,11 @@ interface CodeEditorState {renamePath: (workspaceId: string, from: string, to: string) => void;/** After a delete in the explorer: open files under `path` are marked deleted. */markDeleted: (workspaceId: string, path: string) => void;+ /**+ * Put back the tabs a workspace had open last run, without bringing the+ * editor forward; tabs already open stay as they are.+ */+ restoreTabs: (workspaceId: string, tabs: { path: string; mode: EditorMode; preview: boolean }[], active: string | null) => void;}export const fileKeyOf = (workspaceId: string, path: string) => `${workspaceId}\u0000${path}`;@@ -287,6 +292,29 @@ export const useCodeEditorStore = create<CodeEditorState>((set, get) => ({};}),+ restoreTabs: (workspaceId, restored, activePath) =>+ set((state) => {+ const known = new Set(state.tabs.map((tab) => tab.key));+ const files = { ...state.files };+ const added: EditorTab[] = [];+ for (const entry of restored) {+ const fileKey = fileKeyOf(workspaceId, entry.path);+ const key = tabKeyOf(entry.mode, fileKey);+ if (known.has(key)) continue;+ known.add(key);+ added.push({ key, fileKey, workspaceId, path: entry.path, mode: entry.mode, preview: entry.preview });+ files[fileKey] ??= newFile(workspaceId, entry.path);+ }+ if (added.length === 0) return {};+ const tabs = [...state.tabs, ...added];+ const activeKey =+ state.active[workspaceId] ??+ added.find((tab) => tab.path === activePath && tab.mode === "edit")?.key ??+ added.find((tab) => tab.path === activePath)?.key ??+ added[0].key;+ return { tabs, files, active: { ...state.active, [workspaceId]: activeKey } };+ }),+markDeleted: (workspaceId, path) =>set((state) => {const files = { ...state.files };diff --git a/tests/unit/agentic_ide/test_editor_backups.py b/tests/unit/agentic_ide/test_editor_backups.pynew file mode 100644index 0000000000..c1ab50465f--- /dev/null+++ b/tests/unit/agentic_ide/test_editor_backups.py@@ -0,0 +1,99 @@+"""Open tabs and unsaved editor text survive an app restart."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.agentic_ide import editor_backups+from jarvis.agentic_ide.file_editing import EditError+from jarvis.ui.web import agentic_ide_routes as routes++[email protected](autouse=True)+def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ root = tmp_path / "store"+ monkeypatch.setattr(editor_backups, "_store_root", lambda: root)+ return root+++def test_tabs_and_backups_round_trip(tmp_path: Path) -> None:+ folder = tmp_path / "project"+ folder.mkdir()++ editor_backups.save_tabs(+ folder,+ [{"path": "src/a.py", "mode": "edit", "preview": False}, {"path": "b.md", "mode": "diff"}],+ "b.md",+ )+ editor_backups.save_backup(folder, "src/a.py", "x = 1\r\n", base_version="v1", encoding="utf-8")++ state = editor_backups.load_state(folder)+ assert state["tabs"] == [+ {"path": "src/a.py", "mode": "edit", "preview": False},+ {"path": "b.md", "mode": "diff", "preview": False},+ ]+ assert state["active"] == "b.md"+ assert [(b["path"], b["text"], b["base_version"]) for b in state["backups"]] == [+ ("src/a.py", "x = 1\r\n", "v1")+ ]++ editor_backups.drop_backup(folder, "src/a.py")+ editor_backups.drop_backup(folder, "src/a.py") # a second drop is harmless+ assert editor_backups.load_state(folder)["backups"] == []+++def test_each_workspace_folder_keeps_its_own_state(tmp_path: Path) -> None:+ one, two = tmp_path / "one", tmp_path / "two"+ one.mkdir()+ two.mkdir()+ editor_backups.save_tabs(one, [{"path": "a.txt"}], None)++ assert editor_backups.load_state(two) == {"tabs": [], "active": None, "backups": []}+++def test_a_damaged_backup_is_skipped_not_fatal(tmp_path: Path, store: Path) -> None:+ folder = tmp_path / "project"+ folder.mkdir()+ editor_backups.save_backup(folder, "a.txt", "ok", base_version=None, encoding="utf-8")+ broken = next(store.rglob("*.json")).parent / "zzz.json"+ broken.write_text("{not json", encoding="utf-8")++ assert [b["path"] for b in editor_backups.load_state(folder)["backups"]] == ["a.txt"]+++def test_paths_are_validated(tmp_path: Path) -> None:+ with pytest.raises(EditError):+ editor_backups.save_backup(tmp_path, "../x", "t", base_version=None, encoding="utf-8")+ with pytest.raises(EditError):+ editor_backups.save_tabs(tmp_path, [{"path": ".git/config"}], None)+++async def test_routes_store_and_return_state(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ folder = tmp_path / "project"+ folder.mkdir()+ session = SimpleNamespace(folder=str(folder))+ registry = SimpleNamespace(get=lambda wid: session if wid == "w1" else None)+ monkeypatch.setattr(routes, "get_registry", lambda: registry)++ await routes.put_editor_tabs(+ "w1", routes.EditorTabsRequest(tabs=[routes.EditorTabState(path="a.py")], active="a.py")+ )+ await routes.put_editor_backup(+ "w1", routes.EditorBackupRequest(path="a.py", text="draft", base_version="v1")+ )+ state = await routes.get_editor_state("w1")+ assert state["active"] == "a.py"+ assert state["backups"][0]["text"] == "draft"++ await routes.delete_editor_backup("w1", "a.py")+ assert (await routes.get_editor_state("w1"))["backups"] == []++ with pytest.raises(HTTPException) as caught:+ await routes.put_editor_backup("w1", routes.EditorBackupRequest(path="../evil", text="x"))+ assert caught.value.status_code == 400