Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: undo keeps files saved in the editor

ogsamrat4465ec59789a
diff --git a/apps/server/src/editor-saves.test.ts b/apps/server/src/editor-saves.test.ts
new file mode 100644
index 00000000..a9f464e6
--- /dev/null
+++ b/apps/server/src/editor-saves.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, test } from "bun:test";
+import { resolve } from "node:path";
+
+import { EDITOR_SAVES_MAX_FILES, EditorSaveLog, revertBodyWithEditorSaves, revertMessageId, withRevertKeep } from "./editor-saves.js";
+
+const encode = (value: unknown) => {
+ const bytes = new TextEncoder().encode(JSON.stringify(value));
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
+};
+const decode = (body: ArrayBuffer | undefined) => (body ? JSON.parse(new TextDecoder().decode(body)) : undefined);
+
+const root = resolve("/tmp/editor-saves-project");
+
+describe("EditorSaveLog", () => {
+ test("remembers each file's newest save per folder, as absolute paths", () => {
+ const log = new EditorSaveLog();
+ expect(log.has(root)).toBe(false);
+ log.record(root, "src/a.ts", 100);
+ log.record(root, "b.md", 200);
+ log.record(root, "src/a.ts", 300);
+ log.record(resolve("/tmp/other"), "c.txt", 400);
+ expect(log.has(root)).toBe(true);
+ expect(log.savedSince(root, 0).sort()).toEqual([resolve(root, "b.md"), resolve(root, "src/a.ts")]);
+ expect(log.savedSince(root, 250)).toEqual([resolve(root, "src/a.ts")]);
+ expect(log.savedSince(root, 301)).toEqual([]);
+ expect(log.savedSince(`${root}/`, 0)).toHaveLength(2);
+ });
+
+ test("lets the oldest saves go past its limit", () => {
+ const log = new EditorSaveLog();
+ for (let i = 0; i <= EDITOR_SAVES_MAX_FILES; i += 1) log.record(root, `f${i}.txt`, i);
+ const saved = log.savedSince(root, 0);
+ expect(saved).toHaveLength(EDITOR_SAVES_MAX_FILES);
+ expect(saved).not.toContain(resolve(root, "f0.txt"));
+ });
+});
+
+describe("undo request bodies", () => {
+ test("revertMessageId reads the rewound message", () => {
+ expect(revertMessageId(encode({ messageID: "msg_1" }))).toBe("msg_1");
+ expect(revertMessageId(encode({ messageID: "" }))).toBeNull();
+ expect(revertMessageId(encode({}))).toBeNull();
+ expect(revertMessageId(new TextEncoder().encode("nope").buffer as ArrayBuffer)).toBeNull();
+ expect(revertMessageId(undefined)).toBeNull();
+ });
+
+ test("withRevertKeep merges the saves into the body's keep list", () => {
+ expect(decode(withRevertKeep(encode({ messageID: "m", partID: "p" }), ["/x/a"])!)).toEqual({ messageID: "m", partID: "p", keep: ["/x/a"] });
+ expect(decode(withRevertKeep(encode({ messageID: "m", keep: ["b.txt", "/x/a"] }), ["/x/a", "/x/c"])!)).toEqual({ messageID: "m", keep: ["b.txt", "/x/a", "/x/c"] });
+ // Nothing new: the body goes as it came.
+ expect(withRevertKeep(encode({ messageID: "m", keep: ["/x/a"] }), ["/x/a"])).toBeNull();
+ expect(withRevertKeep(encode({ messageID: "m" }), [])).toBeNull();
+ expect(withRevertKeep(undefined, ["/x/a"])).toBeNull();
+ });
+});
+
+describe("revertBodyWithEditorSaves", () => {
+ const body = encode({ messageID: "msg_turn" });
+
+ test("keeps the files saved at or after the rewound message was sent", async () => {
+ const saves = new EditorSaveLog();
+ saves.record(root, "before.txt", 900);
+ saves.record(root, "during.txt", 1_000);
+ saves.record(root, "later.txt", 1_500);
+ const asked: string[] = [];
+ const out = await revertBodyWithEditorSaves({
+ saves,
+ root,
+ body,
+ messageCreated: async (id) => {
+ asked.push(id);
+ return 1_000;
+ },
+ });
+ expect(asked).toEqual(["msg_turn"]);
+ expect(decode(out)).toEqual({ messageID: "msg_turn", keep: [resolve(root, "during.txt"), resolve(root, "later.txt")] });
+ });
+
+ test("a folder without editor saves, an unknown message time or no message: the body is unchanged and the engine is not asked", async () => {
+ let asked = 0;
+ const messageCreated = async () => {
+ asked += 1;
+ return null;
+ };
+ const empty = new EditorSaveLog();
+ expect(await revertBodyWithEditorSaves({ saves: empty, root, body, messageCreated })).toBe(body);
+ expect(asked).toBe(0);
+
+ const saves = new EditorSaveLog();
+ saves.record(root, "a.txt", 5);
+ expect(await revertBodyWithEditorSaves({ saves, root, body, messageCreated })).toBe(body);
+ expect(asked).toBe(1);
+ const noMessage = encode({});
+ expect(await revertBodyWithEditorSaves({ saves, root, body: noMessage, messageCreated })).toBe(noMessage);
+ expect(asked).toBe(1);
+ // Saved only before the turn: nothing to keep.
+ expect(await revertBodyWithEditorSaves({ saves, root, body, messageCreated: async () => 10 })).toBe(body);
+ });
+});
diff --git a/apps/server/src/editor-saves.ts b/apps/server/src/editor-saves.ts
new file mode 100644
index 00000000..f3ef6e27
--- /dev/null
+++ b/apps/server/src/editor-saves.ts
@@ -0,0 +1,104 @@
+/**
+ * The files the person saved through the desktop editor, per workspace folder
+ * (in memory, while the server runs), and what an undo of a chat's turns does
+ * with them: an undo ("revert") of turns during or after which the person
+ * saved a file passes that file to the engine as `keep`, so the undo never
+ * takes the person's save back (the engine still merges a file that one of
+ * the turns' edit/write/patch tools named too; redo skips kept files as well).
+ *
+ * Nothing in a chat's trace changes: `keep` only goes to the engine.
+ */
+import { resolve } from "node:path";
+
+/** The most files remembered per folder (the oldest saves are let go first). */
+export const EDITOR_SAVES_MAX_FILES = 2_000;
+/** The most paths one undo passes to the engine. */
+export const REVERT_KEEP_MAX = 2_000;
+
+export class EditorSaveLog {
+ private byRoot = new Map<string, Map<string, number>>();
+
+ /** A save (or delete) of `relativePath` in the workspace folder `root`. */
+ record(root: string, relativePath: string, at: number = Date.now()): void {
+ const key = resolve(root);
+ let files = this.byRoot.get(key);
+ if (!files) {
+ files = new Map();
+ this.byRoot.set(key, files);
+ }
+ const absolute = resolve(key, relativePath);
+ // Re-inserted so the map's order is the save order (the oldest is let go first).
+ files.delete(absolute);
+ files.set(absolute, at);
+ while (files.size > EDITOR_SAVES_MAX_FILES) {
+ const oldest = files.keys().next().value;
+ if (oldest === undefined) break;
+ files.delete(oldest);
+ }
+ }
+
+ /** Whether anything in `root` was saved through the editor (an undo elsewhere asks the engine nothing more). */
+ has(root: string): boolean {
+ return (this.byRoot.get(resolve(root))?.size ?? 0) > 0;
+ }
+
+ /** The absolute paths of files in `root` last saved at or after `since` (ms). */
+ savedSince(root: string, since: number): string[] {
+ const files = this.byRoot.get(resolve(root));
+ if (!files) return [];
+ const out: string[] = [];
+ for (const [path, at] of files) if (at >= since) out.push(path);
+ return out;
+ }
+}
+
+function decode(body: ArrayBuffer | undefined): Record<string, unknown> | null {
+ if (!body) return null;
+ try {
+ const parsed = JSON.parse(new TextDecoder().decode(body)) as unknown;
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The message an undo request ("revert") rewinds to, or null when the body names none. */
+export function revertMessageId(body: ArrayBuffer | undefined): string | null {
+ const parsed = decode(body);
+ return typeof parsed?.messageID === "string" && parsed.messageID ? parsed.messageID : null;
+}
+
+/**
+ * The undo request's body with `saved` added to its `keep` list (merged with
+ * any it already has), or null when there is nothing to add (the body is then
+ * sent unchanged).
+ */
+export function withRevertKeep(body: ArrayBuffer | undefined, saved: readonly string[]): ArrayBuffer | null {
+ if (saved.length === 0) return null;
+ const parsed = decode(body);
+ if (!parsed) return null;
+ const existing = Array.isArray(parsed.keep) ? parsed.keep.filter((item): item is string => typeof item === "string") : [];
+ const keep = [...new Set([...existing, ...saved])].slice(0, Math.max(REVERT_KEEP_MAX, existing.length));
+ if (keep.length === existing.length) return null;
+ const encoded = new TextEncoder().encode(JSON.stringify({ ...parsed, keep }));
+ return encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength) as ArrayBuffer;
+}
+
+/**
+ * An undo request's body with the files the person saved through the editor
+ * since the rewound message was sent added to its `keep` list (the engine then
+ * leaves them as saved), or the body unchanged.
+ */
+export async function revertBodyWithEditorSaves(input: {
+ saves: EditorSaveLog;
+ root: string;
+ body: ArrayBuffer | undefined;
+ messageCreated: (messageId: string) => Promise<number | null>;
+}): Promise<ArrayBuffer | undefined> {
+ if (!input.saves.has(input.root)) return input.body;
+ const messageId = revertMessageId(input.body);
+ if (!messageId) return input.body;
+ const created = await input.messageCreated(messageId);
+ if (created === null) return input.body;
+ return withRevertKeep(input.body, input.saves.savedSince(input.root, created)) ?? input.body;
+}
diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.ts
index 2bb5a2a6..26601bca 100644
--- a/apps/server/src/routes/editor.ts
+++ b/apps/server/src/routes/editor.ts
@@ -60,6 +60,8 @@ type RegisterEditorRoutesOptions = {
resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
onUserEdit?: (edit: EditorUserEdit) => void;
onUserReview?: (review: EditorUserReview) => void;
+ /** Every save or delete the editor made, with or without a chat (editor-saves.ts). */
+ onSaved?: (workspace: WorkspaceInfo, path: string) => void;
};
type GitResult = { code: number | null; stdout: Buffer; stderr: string };
@@ -396,6 +398,11 @@ export function registerEditorRoutes(options: RegisterEditorRoutesOptions): void
await writeFile(absolute, content, "utf8");
}
const after = remove ? null : await stat(absolute);
+ try {
+ options.onSaved?.(workspace, path);
+ } catch {
+ // Remembering a save never fails it.
+ }
// A file whose old text could not be read (binary, too large) is not reported.
if (sessionId && options.onUserEdit && (!current || before !== null)) {
const source = body.source === "review" ? "review" : "editor";
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 26fc1a5b..fa9adea3 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -213,6 +213,7 @@ import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTar
import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord } from "./turn-steer.js";
import { FOLDER_NOT_WRITABLE, folderWriteGate, readOnlyPrompt } from "./folder-write-check.js";
import { commandEvent, revertEvent, revertRequest } from "./command-events.js";
+import { EditorSaveLog, revertBodyWithEditorSaves } from "./editor-saves.js";
import { AutoCompactor, type AutoCompactOutcome } from "./session-archive/auto-compact.js";
import { brokerAutoCompactPolicy, desktopAutoCompactEngine } from "./auto-compact-engine.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
@@ -245,6 +246,16 @@ const agentDiagnosticsLastRunByServer = new WeakMap<ServerConfig, Map<string, nu
const agentDiagnosticsInFlightByServer = new WeakMap<ServerConfig, Set<string>>();
const commandAdmissionsByServer = new WeakMap<ServerConfig, Map<string, { fingerprint: string; admittedAt: number }>>();
const captureServicesByServer = new WeakMap<ServerConfig, CaptureService>();
+/** The files the person saved through the desktop editor: an undo of the turns they were saved in keeps them (editor-saves.ts). */
+const editorSavesByServer = new WeakMap<ServerConfig, EditorSaveLog>();
+function editorSavesFor(config: ServerConfig): EditorSaveLog {
+ let log = editorSavesByServer.get(config);
+ if (!log) {
+ log = new EditorSaveLog();
+ editorSavesByServer.set(config, log);
+ }
+ return log;
+}
/** Automatic compaction (session-archive/auto-compact.ts), one per server: its counts live as long as the app. */
const autoCompactorsByServer = new WeakMap<ServerConfig, AutoCompactor>();
/**
@@ -1096,6 +1107,29 @@ async function engineRevertPoint(baseUrl: string, auth: string | null, directory
}
}
+/** When the engine created a chat's message (ms), or null when it cannot say. */
+async function engineMessageCreated(baseUrl: string, auth: string | null, directory: string | null, sessionId: string, messageId: string): Promise<number | null> {
+ const headers = new Headers();
+ if (auth) headers.set("Authorization", auth);
+ const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
+ try {
+ const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}/message/${encodeURIComponent(messageId)}`, scoped.search), {
+ method: "GET",
+ headers: scoped.headers,
+ signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return null;
+ }
+ const message = await response.json() as { info?: { time?: { created?: unknown } } } | null;
+ const created = message?.info?.time?.created;
+ return typeof created === "number" && Number.isFinite(created) ? created : null;
+ } catch {
+ return null;
+ }
+}
+
const SESSION_STOP_TIMEOUT_MS = 5_000;
const SESSION_STOP_MAX_SESSIONS = 100;
@@ -2349,9 +2383,25 @@ export async function proxyOpencodeRequest(input: {
// Buffer the request body so it can be forwarded reliably across Node.js
// stream boundaries (Readable.toWeb streams from the HTTP adapter aren't
// always accepted directly by Node's global fetch as a body).
- const body = method === "GET" || method === "HEAD"
+ let body = method === "GET" || method === "HEAD"
? undefined
: await input.request.arrayBuffer().then((buf) => (buf.byteLength > 0 ? buf : undefined));
+ // An undo keeps the files the person saved in the editor during or after the turns it takes back.
+ const undoCall = workspace && workspace.workspaceType !== "remote" ? revertRequest(method, normalizeOpencodeProxyPath(proxyPath)) : null;
+ if (undoCall?.kind === "revert" && workspace) {
+ const undoSessionId = decodeEngineRouteParam(undoCall.sessionId) ?? undoCall.sessionId;
+ const kept = await revertBodyWithEditorSaves({
+ saves: editorSavesFor(input.config),
+ root: workspace.path,
+ body,
+ messageCreated: (messageId) => engineMessageCreated(baseUrl, auth, directory, undoSessionId, messageId),
+ });
+ if (kept !== body) {
+ body = kept;
+ headers.delete("content-length");
+ headers.set("content-type", "application/json");
+ }
+ }
const capture = workspace ? captureServicesByServer.get(input.config) : undefined;
const uploadedSessionId = uploadSessionId(proxyPath, method);
// The agent works from here (the prompt is on its way) until the engine runs no session.
@@ -2437,9 +2487,7 @@ export async function proxyOpencodeRequest(input: {
: null;
// Undo of the last turn and its redo (command-events.ts) of a chat the uploader tracks: the revert
// point before it is read first; the engine's answer says what happened to each file.
- const revertCall = capture?.uploadEnabled && workspace && workspace.workspaceType !== "remote"
- ? revertRequest(method, normalizeOpencodeProxyPath(proxyPath))
- : null;
+ const revertCall = capture?.uploadEnabled ? undoCall : null;
const revertSessionId = revertCall ? decodeEngineRouteParam(revertCall.sessionId) : null;
const revertTracked = Boolean(revertSessionId && capture?.hasSession(revertSessionId));
const revertBefore = revertTracked && revertSessionId ? await engineRevertPoint(baseUrl, auth, directory, revertSessionId) : null;
@@ -4787,6 +4835,7 @@ function createRoutes(
requireApproval,
requireClientScope,
resolveWorkspace,
+ onSaved: (workspace, path) => editorSavesFor(config).record(workspace.path, path),
onUserEdit: (edit) => {
const capture = captureServicesByServer.get(config);
if (!capture?.uploadEnabled || !capture.hasSession(edit.sessionId) || isUploadFileDenied(edit.path)) return;