Skip to content

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.

feat(agentic-ide): edit text in any encoding and handle mixed line endings

rubenluetke10-beep7191fd0a936e
diff --git a/jarvis/agentic_ide/file_editing.py b/jarvis/agentic_ide/file_editing.py
index 94ebb0fa3f..fb3afcc4e2 100644
--- a/jarvis/agentic_ide/file_editing.py
+++ b/jarvis/agentic_ide/file_editing.py
@@ -24,6 +24,7 @@ Safety rules every function follows:
from __future__ import annotations
+import codecs
import hashlib
import os
import shutil
@@ -64,7 +65,35 @@ _BINARY_SNIFF_BYTES = 8192
_UTF8_BOM = b"\xef\xbb\xbf"
-_ENCODINGS = ("utf-8", "utf-8-sig")
+#: Byte-order marks that name a UTF-16 file; such a file has NUL bytes by
+#: nature, so it is recognised before the binary check.
+_UTF16_BOMS = {b"\xff\xfe": "utf-16-le", b"\xfe\xff": "utf-16-be"}
+_UTF16_BOM_BY_CODEC = {codec: bom for bom, codec in _UTF16_BOMS.items()}
+#: How sure the detector must be before a non-UTF-8 file opens as text.
+_MAX_CHAOS = 0.25
+#: Single-byte code pages the detector cannot tell apart on short text, by
+#: script. When it lands in a family and the bytes are valid in that script's
+#: Windows code page — by far the most common legacy encodings — the Windows
+#: code page wins; the status bar's "Reopen with encoding" corrects a wrong guess.
+_FAMILIES: dict[str, frozenset[str]] = {
+ "cp1252": frozenset(
+ {
+ "cp1250",
+ "cp1252",
+ "cp1254",
+ "cp1257",
+ "iso8859-1",
+ "iso8859-2",
+ "iso8859-9",
+ "iso8859-13",
+ "iso8859-15",
+ "mac-latin2",
+ "mac-roman",
+ }
+ ),
+ "cp1251": frozenset({"cp1251", "cp866", "koi8-r", "koi8-u", "iso8859-5", "mac-cyrillic"}),
+ "cp1253": frozenset({"cp1253", "iso8859-7", "mac-greek"}),
+}
class EditError(ValueError):
@@ -91,6 +120,8 @@ class TextFile:
eol: str
binary: bool
too_large: bool
+ #: The file mixes line endings; a save writes ``eol`` throughout.
+ mixed_eol: bool = False
def _version_of(data: bytes) -> str:
@@ -175,8 +206,99 @@ def _detect_eol(text: str) -> str:
return "\r\n" if crlf > lf else "\n"
-def read_text_file(root: str | os.PathLike[str], path: str) -> TextFile:
- """Load one workspace file for editing, untouched."""
+def _mixed_eol(text: str) -> bool:
+ """True when more than one kind of line ending appears (CRLF, LF, lone CR)."""
+ crlf = text.count("\r\n")
+ lf = text.count("\n") - crlf
+ cr = text.count("\r") - crlf
+ return sum(1 for count in (crlf, lf, cr) if count) > 1
+
+
+def _canonical_codec(name: str) -> str | None:
+ try:
+ return codecs.lookup(name).name
+ except LookupError:
+ return None
+
+
+def _decode(data: bytes) -> tuple[str, str] | None:
+ """The text and the encoding to save it back in, or None for a binary file.
+
+ UTF-8 (with or without BOM) and BOM-marked UTF-16 are taken as they are.
+ Anything else is handed to the charset detector, and only a confident
+ answer opens as text: a wrong guess would garble the file on save.
+ """
+ for bom, codec in _UTF16_BOMS.items():
+ if data.startswith(bom):
+ try:
+ return data[len(bom) :].decode(codec), codec
+ except UnicodeDecodeError:
+ return None
+ if b"\x00" in data[:_BINARY_SNIFF_BYTES]:
+ return None
+ encoding = "utf-8-sig" if data.startswith(_UTF8_BOM) else "utf-8"
+ try:
+ return data.decode(encoding), encoding
+ except UnicodeDecodeError:
+ pass
+ # Lazy import: only a non-UTF-8 file pays for the detector.
+ from charset_normalizer import from_bytes
+
+ best = from_bytes(data).best()
+ if best is None or best.chaos > _MAX_CHAOS:
+ return None
+ codec = _canonical_codec(best.encoding)
+ if codec is None:
+ return None
+ for preferred, family in _FAMILIES.items():
+ if codec in family and codec != preferred:
+ try:
+ return data.decode(preferred), preferred
+ except UnicodeDecodeError:
+ break
+ try:
+ return data.decode(codec), codec
+ except UnicodeDecodeError:
+ return None
+
+
+def _decode_as(data: bytes, encoding: str) -> tuple[str, str]:
+ """Read the bytes in a chosen encoding, or say why that does not work."""
+ codec = _canonical_codec(encoding)
+ if codec is None:
+ raise EditError(f"The encoding {encoding!r} is not known.")
+ body = data
+ if codec in _UTF16_BOM_BY_CODEC and data.startswith(_UTF16_BOM_BY_CODEC[codec]):
+ body = data[2:]
+ try:
+ return body.decode(codec), codec
+ except UnicodeDecodeError as exc:
+ raise EditError(f"This file cannot be read as {codec}.") from exc
+
+
+def _encode(text: str, encoding: str) -> bytes:
+ """Text as bytes in the file's own encoding (UTF-16 keeps its BOM)."""
+ codec = _canonical_codec(encoding)
+ if codec is None:
+ raise EditError(f"The encoding {encoding!r} is not known.")
+ try:
+ if codec in _UTF16_BOM_BY_CODEC:
+ return _UTF16_BOM_BY_CODEC[codec] + text.encode(codec)
+ return text.encode(codec)
+ except UnicodeEncodeError as exc:
+ raise EditError(
+ f"Some characters cannot be stored as {codec}. Save the file as UTF-8 instead."
+ ) from exc
+
+
+def read_text_file(
+ root: str | os.PathLike[str], path: str, *, encoding: str | None = None
+) -> TextFile:
+ """Load one workspace file for editing, untouched.
+
+ ``encoding`` forces how the bytes are read ("Reopen with encoding");
+ without it the encoding is detected.
+ """
relative, target = _resolve(root, path)
if not target.is_file():
raise EditError("That file does not exist.")
@@ -185,14 +307,13 @@ def read_text_file(root: str | os.PathLike[str], path: str) -> TextFile:
return TextFile(relative, None, "", size, "utf-8", "\n", False, True)
data = target.read_bytes()
version = _version_of(data)
- if b"\x00" in data[:_BINARY_SNIFF_BYTES]:
+ decoded = _decode(data) if encoding is None else _decode_as(data, encoding)
+ if decoded is None:
return TextFile(relative, None, version, size, "utf-8", "\n", True, False)
- encoding = "utf-8-sig" if data.startswith(_UTF8_BOM) else "utf-8"
- try:
- text = data.decode(encoding)
- except UnicodeDecodeError:
- return TextFile(relative, None, version, size, encoding, "\n", True, False)
- return TextFile(relative, text, version, size, encoding, _detect_eol(text), False, False)
+ text, encoding = decoded
+ return TextFile(
+ relative, text, version, size, encoding, _detect_eol(text), False, False, _mixed_eol(text)
+ )
def file_version(root: str | os.PathLike[str], path: str) -> str | None:
@@ -259,11 +380,7 @@ def write_text_file(
and refused when a file already sits there.
"""
relative, target = _resolve(root, path)
- if encoding not in _ENCODINGS:
- raise EditError("Only UTF-8 files can be saved from the editor.")
- data = text.encode("utf-8")
- if encoding == "utf-8-sig":
- data = _UTF8_BOM + data
+ data = _encode(text, encoding)
if len(data) > MAX_EDITABLE_BYTES:
raise EditError("That file is too large to save from the editor.")
if target.is_dir():
@@ -282,10 +399,11 @@ def write_text_file(
None,
_version_of(data),
len(data),
- encoding,
+ _canonical_codec(encoding) or encoding,
_detect_eol(text),
False,
False,
+ _mixed_eol(text),
)
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 5888dac476..e530d0a3d7 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -967,10 +967,13 @@ class WorkspaceTextFileResponse(BaseModel):
)
version: str = Field(description="Content hash; send it back on save to detect conflicts.")
size: int
- encoding: Literal["utf-8", "utf-8-sig"]
+ encoding: str = Field(description="Python codec the file is saved back in, e.g. utf-8, cp1252.")
eol: Literal["\n", "\r\n"]
binary: bool = False
too_large: bool = False
+ mixed_eol: bool = Field(
+ default=False, description="The file mixes line endings; a save writes `eol` throughout."
+ )
class SaveWorkspaceFileRequest(BaseModel):
@@ -983,7 +986,7 @@ class SaveWorkspaceFileRequest(BaseModel):
max_length=128,
description="Version the editor loaded; null only when creating a new file.",
)
- encoding: Literal["utf-8", "utf-8-sig"] = "utf-8"
+ encoding: str = Field(default="utf-8", max_length=40)
create: bool = False
@@ -2013,15 +2016,22 @@ def _text_file_response(workspace_id: str, loaded: file_editing.TextFile) -> dic
response_model=WorkspaceTextFileResponse,
summary="Load one workspace file for the code editor",
)
-async def get_workspace_text_file(workspace_id: str, path: str) -> dict[str, object]:
+async def get_workspace_text_file(
+ workspace_id: str,
+ path: str,
+ encoding: Annotated[str | None, Query(max_length=40)] = None,
+) -> dict[str, object]:
"""The file's exact text plus the version a later save must name.
Unlike ``/file-preview`` nothing is normalised: indentation, line endings
- and a byte-order mark come back as they are on disk.
+ and a byte-order mark come back as they are on disk. ``encoding`` forces
+ how the bytes are read ("Reopen with encoding"); otherwise it is detected.
"""
folder = _workspace_folder(workspace_id)
try:
- loaded = await asyncio.to_thread(file_editing.read_text_file, folder, path)
+ loaded = await asyncio.to_thread(
+ file_editing.read_text_file, folder, path, encoding=encoding
+ )
except file_editing.EditError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except OSError as exc:
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
index fc9f8aa400..ca205c969e 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/CodeEditorStage.tsx
@@ -24,8 +24,9 @@ import { revealInExplorer } from "@/store/ideExplorer";
import { tabsOf, useCodeEditorStore, type EditorTab } from "@/store/codeEditor";
import { FileTypeIcon } from "@/components/agentic/sidePanel/explorer/FileTypeIcon";
import { absoluteWorkspacePath } from "@/components/agentic/sidePanel/explorer/explorerApi";
-import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
-import { checkDisk, discardFile, languageName, revertFile, saveAll, saveFile } from "./editorModels";
+import { ThreadMenuHeading, ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
+import { checkDisk, discardFile, languageName, reopenWithEncoding, revertFile, saveAll, saveFile, setLineEnding } from "./editorModels";
+import { ENCODINGS, encodingLabel } from "./encodings";
import { QuickOpen } from "./QuickOpen";
import { restoreWorkspace } from "./editorPersistence";
import { SEARCH_FOCUS_EVENT } from "@/components/agentic/sidePanel/search/SearchPanel";
@@ -368,6 +369,13 @@ export function CodeEditorStage({
<BannerButton onClick={() => void saveFile(activeTab.fileKey, { overwrite: true })}>{t("code_editor.conflict_keep_mine")}</BannerButton>
</Banner>
)}
+ {activeFile?.mixedEol && !activeFile.conflict && (
+ <Banner
+ tone="muted"
+ testId="code-editor-mixed-eol"
+ text={fill(t("code_editor.mixed_eol"), { eol: activeFile.eol === "\r\n" ? "CRLF" : "LF" })}
+ />
+ )}
{activeFile?.deleted && !activeFile.conflict && (
<Banner tone="muted" testId="code-editor-deleted" text={t("code_editor.deleted")} />
)}
@@ -488,8 +496,16 @@ function StatusBar({ fileKey }: { fileKey: string }) {
const t = useT();
const file = useCodeEditorStore((state) => state.files[fileKey]);
const cursor = useCodeEditorStore((state) => state.cursor);
+ const [menu, setMenu] = useState<"encoding" | "eol" | null>(null);
+ const anchor = useRef<HTMLElement | null>(null);
if (!file) return null;
const ready = file.status === "ready" && cursor;
+ const openMenu = (kind: "encoding" | "eol", target: HTMLElement) => {
+ anchor.current = target;
+ setMenu(kind);
+ };
+ const statusButton =
+ "rounded px-1 hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return (
<div
data-testid="code-editor-status"
@@ -505,11 +521,81 @@ function StatusBar({ fileKey }: { fileKey: string }) {
{cursor.selected > 0 && ` ${fill(t("code_editor.status.selected"), { count: String(cursor.selected) })}`}
</span>
<span>{cursor.insertSpaces ? fill(t("code_editor.status.spaces"), { size: String(cursor.tabSize) }) : fill(t("code_editor.status.tabs"), { size: String(cursor.tabSize) })}</span>
- <span>{file.encoding === "utf-8-sig" ? t("code_editor.status.utf8_bom") : "UTF-8"}</span>
- <span>{file.eol === "\r\n" ? "CRLF" : "LF"}</span>
+ <button
+ type="button"
+ data-testid="code-editor-encoding"
+ title={t("code_editor.status.change_encoding")}
+ onClick={(event) => openMenu("encoding", event.currentTarget)}
+ className={statusButton}
+ >
+ {encodingLabel(file.encoding)}
+ </button>
+ <button
+ type="button"
+ data-testid="code-editor-eol"
+ title={t("code_editor.status.line_endings")}
+ onClick={(event) => openMenu("eol", event.currentTarget)}
+ className={statusButton}
+ >
+ {file.eol === "\r\n" ? "CRLF" : "LF"}
+ </button>
<span>{languageName(cursor.language)}</span>
</>
)}
+ <ThreadPopover
+ anchor={anchor}
+ open={menu !== null}
+ onClose={() => setMenu(null)}
+ side="top"
+ align="end"
+ width={menu === "encoding" ? 300 : 200}
+ label={menu === "encoding" ? t("code_editor.status.change_encoding") : t("code_editor.status.line_endings")}
+ >
+ {menu === "eol" && (
+ <div role="menu">
+ {(["\n", "\r\n"] as const).map((eol) => (
+ <ThreadMenuItem
+ key={eol}
+ label={eol === "\r\n" ? "CRLF (Windows)" : "LF (macOS, Linux)"}
+ selected={file.eol === eol}
+ onSelect={() => {
+ setMenu(null);
+ setLineEnding(fileKey, eol);
+ }}
+ />
+ ))}
+ </div>
+ )}
+ {menu === "encoding" && (
+ <div role="menu" data-testid="code-editor-encoding-menu">
+ <ThreadMenuHeading>{t("code_editor.status.save_with")}</ThreadMenuHeading>
+ {ENCODINGS.map((entry) => (
+ <ThreadMenuItem
+ key={`save-${entry.id}`}
+ label={entry.label}
+ selected={file.encoding === entry.id}
+ onSelect={() => {
+ setMenu(null);
+ void saveFile(fileKey, { encoding: entry.id });
+ }}
+ />
+ ))}
+ <ThreadMenuSeparator />
+ <ThreadMenuHeading>{t("code_editor.status.reopen_with")}</ThreadMenuHeading>
+ {ENCODINGS.map((entry) => (
+ <ThreadMenuItem
+ key={`reopen-${entry.id}`}
+ label={entry.label}
+ disabled={file.dirty}
+ onSelect={() => {
+ setMenu(null);
+ void reopenWithEncoding(fileKey, entry.id);
+ }}
+ />
+ ))}
+ </div>
+ )}
+ </ThreadPopover>
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
index bd840d7912..b9e77f3eb9 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorApi.ts
@@ -1,6 +1,7 @@
/** The code editor's file reads and writes against an open workspace. */
-export type TextEncoding = "utf-8" | "utf-8-sig";
+/** A Python codec name: utf-8, utf-8-sig, utf-16-le, cp1252, … (see encodings.ts). */
+export type TextEncoding = string;
export type LineEnding = "\n" | "\r\n";
export interface TextFile {
@@ -16,6 +17,8 @@ export interface TextFile {
eol: LineEnding;
binary: boolean;
too_large: boolean;
+ /** The file mixes line endings; a save writes `eol` throughout. */
+ mixed_eol?: boolean;
}
/** A save was refused because the file changed on disk since it was loaded. */
@@ -67,8 +70,11 @@ function json(method: string, body: unknown): RequestInit {
return { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
}
-export function loadTextFile(workspaceId: string, path: string): Promise<TextFile> {
- return send<TextFile>(`${base(workspaceId)}/text-file?${query(path)}`);
+/** `encoding` forces how the bytes are read ("Reopen with encoding"). */
+export function loadTextFile(workspaceId: string, path: string, encoding?: string): Promise<TextFile> {
+ const params = new URLSearchParams({ path });
+ if (encoding) params.set("encoding", encoding);
+ return send<TextFile>(`${base(workspaceId)}/text-file?${params.toString()}`);
}
/** The file's version on disk now; null when it no longer exists. */
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
index a84fdbafb4..3d3c3999f8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/editorModels.ts
@@ -269,6 +269,7 @@ export async function loadFile(fileKey: string): Promise<void> {
version: loaded.version,
encoding: loaded.encoding,
eol: loaded.eol,
+ mixedEol: loaded.mixed_eol ?? false,
deleted: false,
conflict: null,
dirty: false,
@@ -330,7 +331,10 @@ export function loadHead(fileKey: string): Promise<Monaco.editor.ITextModel | nu
* disk now. Without it a save names the version it was based on, and a file an
* agent changed meanwhile turns into a conflict instead of being overwritten.
*/
-export async function saveFile(fileKey: string, { overwrite = false } = {}): Promise<boolean> {
+export async function saveFile(
+ fileKey: string,
+ { overwrite = false, encoding }: { overwrite?: boolean; encoding?: string } = {},
+): Promise<boolean> {
const file = store().files[fileKey];
const entry = entries.get(fileKey);
if (!file || !entry || file.saving) return false;
@@ -344,7 +348,7 @@ export async function saveFile(fileKey: string, { overwrite = false } = {}): Pro
path: file.path,
text: entry.model.getValue(),
expectedVersion: expected,
- encoding: file.encoding,
+ encoding: encoding ?? file.encoding,
create,
});
entry.saved = sent;
@@ -353,6 +357,8 @@ export async function saveFile(fileKey: string, { overwrite = false } = {}): Pro
store().patchFile(fileKey, {
saving: false,
version: saved.version,
+ encoding: saved.encoding,
+ mixedEol: false,
eol: saved.eol,
deleted: false,
conflict: null,
@@ -413,6 +419,42 @@ export async function revertFile(fileKey: string, { follow = false } = {}): Prom
}
}
+/**
+ * Read the file again in another encoding ("Reopen with encoding"). Only a
+ * buffer without unsaved edits can be reopened; its edits would be lost.
+ */
+export async function reopenWithEncoding(fileKey: string, encoding: string): Promise<void> {
+ const file = store().files[fileKey];
+ const entry = entries.get(fileKey);
+ if (!file || !entry) return;
+ if (file.dirty) {
+ toast("Save or discard the changes before reopening the file in another encoding.");
+ return;
+ }
+ try {
+ const loaded = await loadTextFile(file.workspaceId, file.path, encoding);
+ if (loaded.text === null || entries.get(fileKey) !== entry) return;
+ replaceFromDisk(entry, loaded.text, loaded.eol);
+ store().patchFile(fileKey, {
+ version: loaded.version,
+ encoding: loaded.encoding,
+ eol: loaded.eol,
+ mixedEol: loaded.mixed_eol ?? false,
+ dirty: false,
+ });
+ } catch (error) {
+ toast((error as Error).message);
+ }
+}
+
+/** Switch the buffer's line endings; the change is an edit and saves like one. */
+export function setLineEnding(fileKey: string, eol: LineEnding): void {
+ const entry = entries.get(fileKey);
+ if (!entry || !api) return;
+ entry.model.pushEOL(eolSequence(eol));
+ store().patchFile(fileKey, { eol, mixedEol: false });
+}
+
/** Forget unsaved edits without touching disk (closing with "Don't save"). */
export function discardFile(fileKey: string): void {
forgetBackup(fileKey);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/editor/encodings.ts b/jarvis/ui/web/frontend/src/components/agentic/editor/encodings.ts
new file mode 100644
index 0000000000..71a945741b
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/editor/encodings.ts
@@ -0,0 +1,30 @@
+/**
+ * The text encodings the editor offers for "Reopen with" and "Save with".
+ *
+ * Ids are the Python codec names the backend reports and accepts
+ * (`codecs.lookup(name).name`), so a detected encoding finds its label here.
+ */
+export const ENCODINGS: readonly { id: string; label: string }[] = [
+ { id: "utf-8", label: "UTF-8" },
+ { id: "utf-8-sig", label: "UTF-8 with BOM" },
+ { id: "utf-16-le", label: "UTF-16 LE" },
+ { id: "utf-16-be", label: "UTF-16 BE" },
+ { id: "cp1252", label: "Western (Windows 1252)" },
+ { id: "iso8859-1", label: "Western (ISO 8859-1)" },
+ { id: "iso8859-15", label: "Western (ISO 8859-15)" },
+ { id: "cp1250", label: "Central European (Windows 1250)" },
+ { id: "cp1251", label: "Cyrillic (Windows 1251)" },
+ { id: "koi8-r", label: "Cyrillic (KOI8-R)" },
+ { id: "cp1253", label: "Greek (Windows 1253)" },
+ { id: "cp1254", label: "Turkish (Windows 1254)" },
+ { id: "shift_jis", label: "Japanese (Shift JIS)" },
+ { id: "euc_jp", label: "Japanese (EUC-JP)" },
+ { id: "gb18030", label: "Chinese Simplified (GB 18030)" },
+ { id: "big5", label: "Chinese Traditional (Big5)" },
+ { id: "euc_kr", label: "Korean (EUC-KR)" },
+];
+
+/** A short status-bar label for an encoding id. */
+export function encodingLabel(id: string): string {
+ return ENCODINGS.find((entry) => entry.id === id)?.label ?? id.toUpperCase();
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 20e1a15ab3..ae4aa22f4b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -6188,6 +6188,7 @@
"document_note": "Aus diesem Dokument gelesener Text. Zum Bearbeiten auf diesem Computer öffnen.",
"truncated": "Nur der Anfang der Datei wird gezeigt.",
"empty": "Diese Datei hat keinen lesbaren Inhalt.",
+ "mixed_eol": "Diese Datei mischt Zeilenenden. Beim Speichern wird überall {eol} geschrieben.",
"tab_menu": "Tab-Aktionen",
"menu": {
"close": "Schließen",
@@ -6199,6 +6200,10 @@
"reveal": "Im Ordner zeigen"
},
"status": {
+ "reopen_with": "Mit Kodierung neu öffnen",
+ "save_with": "Mit Kodierung speichern",
+ "line_endings": "Zeilenenden",
+ "change_encoding": "Kodierung ändern",
"saving": "Speichert…",
"unsaved": "Ungespeicherte Änderungen",
"saved": "Gespeichert",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 81f90eb686..c1925f5cb2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -6188,6 +6188,7 @@
"document_note": "Text read out of this document. Open it on this computer to edit it.",
"truncated": "Only the beginning of the file is shown.",
"empty": "This file has no readable content.",
+ "mixed_eol": "This file mixes line endings. Saving it writes {eol} throughout.",
"tab_menu": "Tab actions",
"menu": {
"close": "Close",
@@ -6199,6 +6200,10 @@
"reveal": "Reveal in Folder"
},
"status": {
+ "reopen_with": "Reopen with encoding",
+ "save_with": "Save with encoding",
+ "line_endings": "Line endings",
+ "change_encoding": "Change the encoding",
"saving": "Saving…",
"unsaved": "Unsaved changes",
"saved": "Saved",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 60d6996513..2c7759b238 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -6188,6 +6188,7 @@
"document_note": "Texto leído de este documento. Ábrelo en este equipo para editarlo.",
"truncated": "Solo se muestra el comienzo del archivo.",
"empty": "Este archivo no tiene contenido legible.",
+ "mixed_eol": "Este archivo mezcla finales de línea. Al guardarlo se usa {eol} en todo.",
"tab_menu": "Acciones de pestaña",
"menu": {
"close": "Cerrar",
@@ -6199,6 +6200,10 @@
"reveal": "Mostrar en la carpeta"
},
"status": {
+ "reopen_with": "Reabrir con codificación",
+ "save_with": "Guardar con codificación",
+ "line_endings": "Finales de línea",
+ "change_encoding": "Cambiar la codificación",
"saving": "Guardando…",
"unsaved": "Cambios sin guardar",
"saved": "Guardado",
diff --git a/jarvis/ui/web/frontend/src/store/codeEditor.ts b/jarvis/ui/web/frontend/src/store/codeEditor.ts
index f4a834ae07..c46e7e391b 100644
--- a/jarvis/ui/web/frontend/src/store/codeEditor.ts
+++ b/jarvis/ui/web/frontend/src/store/codeEditor.ts
@@ -46,6 +46,8 @@ export interface EditorFile {
deleted: boolean;
/** The file changed on disk while the buffer had unsaved edits. */
conflict: { diskVersion: string | null } | null;
+ /** The file on disk mixes line endings; a save writes `eol` throughout. */
+ mixedEol: boolean;
saving: boolean;
}
@@ -134,6 +136,7 @@ const newFile = (workspaceId: string, path: string): EditorFile => ({
dirty: false,
deleted: false,
conflict: null,
+ mixedEol: false,
saving: false,
});
diff --git a/pyproject.toml b/pyproject.toml
index b4a4938eb8..d60408e118 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -65,6 +65,10 @@ dependencies = [
# malformed vision JSON; without it the repair path silently degrades on
# every fresh install (found 2026-07-18, was never declared).
"json-repair>=0.30",
+ # The code editor detects the encoding of non-UTF-8 text files with it
+ # (lazy import); already installed through requests, declared because
+ # Jarvis imports it directly.
+ "charset-normalizer>=3.4",
# The code editor's delete moves files to the system trash (Recycle Bin,
# macOS Trash, freedesktop trash) instead of erasing them; pure Python.
"Send2Trash>=1.8.3",
diff --git a/requirements.in b/requirements.in
index 723004257a..93b77ab0c1 100644
--- a/requirements.in
+++ b/requirements.in
@@ -29,6 +29,10 @@ anyio>=4.14.2
# malformed vision JSON; without it the repair path silently degrades on
# every fresh install (found 2026-07-18, was never declared).
json-repair>=0.30
+# The code editor detects the encoding of non-UTF-8 text files with it
+# (lazy import); already installed through requests, declared because
+# Jarvis imports it directly.
+charset-normalizer>=3.4
# The code editor's delete moves files to the system trash (Recycle Bin,
# macOS Trash, freedesktop trash) instead of erasing them; pure Python.
Send2Trash>=1.8.3
diff --git a/requirements.txt b/requirements.txt
index 83f4bd436c..979e933275 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -493,7 +493,9 @@ charset-normalizer==3.4.7 \
--hash=sha256:f59ad4c0e8f6bba240a9bb85504faa1ab438237199d4cce5f622761507b8f6a6 \
--hash=sha256:fbccdc05410c9ee21bbf16a35f4c1d16123dcdeb8a1d38f33654fa21d0234f79 \
--hash=sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464
- # via requests
+ # via
+ # personal-jarvis (pyproject.toml)
+ # requests
click==8.4.2 \
--hash=sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6 \
--hash=sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76
@@ -2126,7 +2128,7 @@ secretstorage==3.5.0 ; sys_platform == 'linux' \
send2trash==2.1.0 \
--hash=sha256:0da2f112e6d6bb22de6aa6daa7e144831a4febf2a87261451c4ad849fe9a873c \
--hash=sha256:1c72b39f09457db3c05ce1d19158c2cbef4c32b8bedd02c155e49282b7ea7459
- # via -r requirements.in
+ # via personal-jarvis (pyproject.toml)
shellingham==1.5.4 \
--hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \
--hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de
diff --git a/tests/unit/agentic_ide/test_file_editing.py b/tests/unit/agentic_ide/test_file_editing.py
index b8bebcd5d7..76c98a9df6 100644
--- a/tests/unit/agentic_ide/test_file_editing.py
+++ b/tests/unit/agentic_ide/test_file_editing.py
@@ -79,6 +79,85 @@ def test_save_without_version_never_overwrites_an_existing_file(tmp_path: Path)
assert (tmp_path / "b.txt").read_text(encoding="utf-8") == "new\n"
+def test_windows_1252_text_opens_and_saves_back_in_its_encoding(tmp_path: Path) -> None:
+ raw = "Déjà vu: café crème, naïve façade, résumé — señor.\r\n".encode("cp1252") * 4
+ (tmp_path / "legacy.txt").write_bytes(raw)
+
+ loaded = read_text_file(tmp_path, "legacy.txt")
+ assert loaded.binary is False
+ assert loaded.text is not None and "façade" in loaded.text
+ assert loaded.encoding not in ("utf-8", "utf-8-sig")
+
+ write_text_file(
+ tmp_path,
+ "legacy.txt",
+ loaded.text + "One more line.\r\n",
+ expected_version=loaded.version,
+ encoding=loaded.encoding,
+ )
+ assert (tmp_path / "legacy.txt").read_bytes() == raw + b"One more line.\r\n"
+
+
+def test_cyrillic_legacy_text_is_not_mistaken_for_western(tmp_path: Path) -> None:
+ raw = "Привет, мир! Это проверка кодировки файла.\n".encode("cp1251") * 6
+ (tmp_path / "ru.txt").write_bytes(raw)
+
+ loaded = read_text_file(tmp_path, "ru.txt")
+ assert loaded.text is not None and "Привет" in loaded.text
+
+
+def test_a_chosen_encoding_overrides_the_guess(tmp_path: Path) -> None:
+ (tmp_path / "a.txt").write_bytes("naïve\n".encode("cp1252"))
+
+ forced = read_text_file(tmp_path, "a.txt", encoding="iso8859-15")
+ assert forced.encoding == "iso8859-15"
+ assert forced.text == "naïve\n"
+ with pytest.raises(EditError):
+ read_text_file(tmp_path, "a.txt", encoding="utf-8")
+ with pytest.raises(EditError):
+ read_text_file(tmp_path, "a.txt", encoding="no-such-codec")
+
+
+def test_utf16_with_bom_round_trips(tmp_path: Path) -> None:
+ raw = b"\xff\xfe" + "line one\r\nline two\r\n".encode("utf-16-le")
+ (tmp_path / "wide.txt").write_bytes(raw)
+
+ loaded = read_text_file(tmp_path, "wide.txt")
+ assert loaded.text == "line one\r\nline two\r\n"
+ assert loaded.encoding == "utf-16-le"
+
+ write_text_file(
+ tmp_path, "wide.txt", loaded.text, expected_version=loaded.version, encoding="utf-16-le"
+ )
+ assert (tmp_path / "wide.txt").read_bytes() == raw
+
+
+def test_characters_the_encoding_cannot_hold_are_refused(tmp_path: Path) -> None:
+ (tmp_path / "legacy.txt").write_bytes("café\n".encode("cp1252"))
+ loaded = read_text_file(tmp_path, "legacy.txt")
+
+ with pytest.raises(EditError, match="UTF-8"):
+ write_text_file(
+ tmp_path,
+ "legacy.txt",
+ "emoji 🙂\n",
+ expected_version=loaded.version,
+ encoding="cp1252",
+ )
+ saved = write_text_file(
+ tmp_path, "legacy.txt", "emoji 🙂\n", expected_version=loaded.version, encoding="utf-8"
+ )
+ assert saved.encoding == "utf-8"
+
+
+def test_mixed_line_endings_are_reported(tmp_path: Path) -> None:
+ (tmp_path / "mixed.txt").write_bytes(b"a\r\nb\nc\r\n")
+ (tmp_path / "clean.txt").write_bytes(b"a\nb\n")
+
+ assert read_text_file(tmp_path, "mixed.txt").mixed_eol is True
+ assert read_text_file(tmp_path, "clean.txt").mixed_eol is False
+
+
def test_binary_and_large_files_are_not_loaded_as_text(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: