A desktop coding agent with free access to frontier models.
TypeScript
fix(engine2): make revert reversible on the 2.x engine, as in 1.x
Samrat Talukdareded94037c8d
diff --git a/apps/server/src/engine2/events.ts b/apps/server/src/engine2/events.tsindex 101fd57d..abdf8449 100644--- a/apps/server/src/engine2/events.ts+++ b/apps/server/src/engine2/events.ts@@ -48,6 +48,8 @@ type SessionState = {lastUserID: string;status: JsonRecord;info?: JsonRecord;+ /** The 1.x ids of the messages a staged revert hides (removed when it is committed). */+ reverted?: string[];};export type EventTranslatorOptions = {@@ -56,6 +58,8 @@ export type EventTranslatorOptions = {rootFor?: (directory: string) => string | undefined;/** Looks up a session the stream has not described yet (its directory and parent). */lookupSession?: (sessionID: string) => Promise<unknown>;+ /** The 1.x ids of a session's messages, oldest first (what a staged revert hides). */+ messageIDs?: (sessionID: string) => Promise<string[]>;now?: () => number;};@@ -120,6 +124,19 @@ export class EventTranslator {return Boolean(this.sessions.get(sessionID)?.parentID);}+ /** The session's 1.x info, read fresh when possible (else the last one seen). */+ private async currentInfo(sessionID: string): Promise<JsonRecord | null> {+ if (this.options.lookupSession) {+ try {+ const info = v1Session(await this.options.lookupSession(sessionID), { version: this.options.version });+ if (info) return info;+ } catch {+ // fall back to the last info seen+ }+ }+ return this.session(sessionID).info ?? null;+ }+private session(sessionID: string): SessionState {let state = this.sessions.get(sessionID);if (!state) {@@ -236,6 +253,43 @@ export class EventTranslator {this.noteSession(sessionID, { info, directory: String(info.directory || "") || null });return [this.scoped(sessionID, "session.updated", { sessionID, info })];}+ case "session.revert.staged":+ case "session.revert.cleared":+ case "session.revert.committed": {+ // 2.x stages a revert (files restored, later messages kept), clears it+ // (files back) or commits it (the later messages are deleted, which a+ // prompt does first). 1.x showed the same through session.revert.+ if (!sessionID) return [];+ const state = this.session(sessionID);+ const out: ScopedV1Event[] = [];+ let revert: JsonRecord | undefined;+ if (type === "session.revert.staged") {+ const staged = record(data, "revert");+ const boundary = str(staged, "messageID");+ if (boundary) {+ revert = omitUndefined({ messageID: boundary, partID: str(staged, "partID"), snapshot: str(staged, "snapshot") });+ const ids = this.options.messageIDs ? await this.options.messageIDs(sessionID).catch(() => []) : [];+ const index = ids.indexOf(boundary);+ state.reverted = index >= 0 ? ids.slice(index) : [boundary];+ }+ } else if (type === "session.revert.committed") {+ const boundary = str(data, "to");+ const removed = state.reverted ?? (boundary ? [boundary] : []);+ for (const messageID of removed) out.push(this.scoped(sessionID, "message.removed", { sessionID, messageID }));+ state.reverted = undefined;+ } else {+ state.reverted = undefined;+ }+ const info = await this.currentInfo(sessionID);+ if (info) {+ const next = { ...info, time: { ...(record(info, "time") ?? {}), updated: num(raw, "created") ?? this.now() } } as JsonRecord;+ if (revert) next.revert = revert;+ else delete next.revert;+ this.noteSession(sessionID, { info: next });+ out.push(this.scoped(sessionID, "session.updated", { sessionID, info: next }));+ }+ return out;+ }case "session.deleted": {if (!sessionID) return [];const info = this.session(sessionID).info ?? { id: sessionID };diff --git a/apps/server/src/engine2/facade.test.ts b/apps/server/src/engine2/facade.test.tsindex 6106daec..4a072724 100644--- a/apps/server/src/engine2/facade.test.ts+++ b/apps/server/src/engine2/facade.test.ts@@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { EventTranslator } from "./events.js";import { startEngineFacade, type EngineFacade } from "./facade.js";type Tree = { session: Record<string, unknown>; messages: Array<Record<string, unknown>>; children: Tree[] };@@ -220,6 +221,25 @@ describe("1.x engine adapter over the 2.x engine", () => {expect(config.providers.mock.settings.apiKey).toBe("sk-1");});+ test("revert stages a reversible revert and unrevert clears it; neither commits", async () => {+ recorded.length = 0;+ const reverted = await post(`/session/${SESSION}/revert`, { messageID: "msg_b" });+ expect(reverted.status).toBe(200);+ const unreverted = await post(`/session/${SESSION}/unrevert`, {});+ expect(unreverted.status).toBe(200);+ const calls = recorded.filter((entry) => entry.path.includes("/revert")).map((entry) => `${entry.method} ${entry.path}`);+ expect(calls).toEqual([`POST /api/session/${SESSION}/revert/stage`, `DELETE /api/session/${SESSION}/revert`]);+ expect(recorded.find((entry) => entry.path.endsWith("/revert/stage"))!.body).toEqual({ messageID: "msg_b" });+ });++ test("a shell command or slash command makes a staged revert final first", async () => {+ recorded.length = 0;+ expect((await post(`/session/${SESSION}/shell`, { command: "ls", agent: "build" })).status).toBe(200);+ expect((await post(`/session/${SESSION}/command`, { command: "/review", arguments: "" })).status).toBe(204);+ const calls = recorded.filter((entry) => entry.method === "POST" && /\/(revert\/commit|shell|command)$/.test(entry.path)).map((entry) => entry.path.split("/").slice(4).join("/"));+ expect(calls).toEqual(["revert/commit", "shell", "revert/commit", "command"]);+ });+test("the event stream speaks 1.x and keeps to the request's directory", async () => {const controller = new AbortController();const response = await fetch(`${facade.url}/event`, { headers: auth, signal: controller.signal });@@ -255,3 +275,41 @@ describe("1.x engine adapter over the 2.x engine", () => {]);});});++describe("revert events", () => {+ const info = (revert?: Record<string, unknown>) => ({ data: { id: "ses_r", title: "T", location: { directory: DIRECTORY }, time: { created: 1, updated: 1 }, ...(revert ? { revert } : {}) } });+ const make = (current: { revert?: Record<string, unknown> }) => new EventTranslator({+ version: "2.0.18",+ lookupSession: async () => info(current.revert),+ messageIDs: async () => ["msg_a", "msg_a2", "msg_b", "msg_b2", "msg_c", "msg_c2"],+ });++ test("staged, cleared and committed reach the app as session.updated and message.removed", async () => {+ const current: { revert?: Record<string, unknown> } = {};+ const translator = make(current);+ const summary = (out: Awaited<ReturnType<EventTranslator["translate"]>>) => out.map((item) => {+ const properties = item.event.properties as Record<string, any>;+ return item.event.type === "message.removed" ? `removed:${properties.messageID}` : `${item.event.type}:${properties.info?.revert?.messageID ?? "-"}`;+ });++ current.revert = { messageID: "msg_b", snapshot: "abc" };+ const staged = await translator.translate({ type: "session.revert.staged", data: { sessionID: "ses_r", revert: { messageID: "msg_b", snapshot: "abc", files: [] } } });+ expect(summary(staged)).toEqual(["session.updated:msg_b"]);+ expect((staged[0]!.event.properties as any).info.revert).toEqual({ messageID: "msg_b", snapshot: "abc" });++ current.revert = undefined;+ expect(summary(await translator.translate({ type: "session.revert.cleared", data: { sessionID: "ses_r" } }))).toEqual(["session.updated:-"]);++ current.revert = { messageID: "msg_b" };+ await translator.translate({ type: "session.revert.staged", data: { sessionID: "ses_r", revert: { messageID: "msg_b" } } });+ current.revert = undefined;+ const committed = await translator.translate({ type: "session.revert.committed", data: { sessionID: "ses_r", to: "msg_b" } });+ expect(summary(committed)).toEqual(["removed:msg_b", "removed:msg_b2", "removed:msg_c", "removed:msg_c2", "session.updated:-"]);+ });++ test("a revert committed without a staged one seen removes the boundary message", async () => {+ const translator = make({});+ const out = await translator.translate({ type: "session.revert.committed", data: { sessionID: "ses_r", to: "msg_c" } });+ expect(out.map((item) => item.event.type)).toEqual(["message.removed", "session.updated"]);+ });+});diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.tsindex 745f2018..00ba6de3 100644--- a/apps/server/src/engine2/facade.ts+++ b/apps/server/src/engine2/facade.ts@@ -233,7 +233,19 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eversion: options.version,rootFor: worktreeRoot,lookupSession: (sessionID) => call("GET", `/api/session/${encodeURIComponent(sessionID)}`),+ messageIDs: async (sessionID) => (await sessionMessages(sessionID)).map((message) => String(message.info.id)),});+ /**+ * Makes a staged revert final (as a 2.x prompt does before it runs); a+ * no-op without one. A busy session (409) cannot hold a staged revert: the+ * app stops a run before it reverts, and a prompt commits it.+ */+ const commitRevert = async (encodedSessionID: string) => {+ await call("POST", `/api/session/${encodedSessionID}/revert/commit`, { body: {} }).catch((error) => {+ if (error instanceof UpstreamError && (error.status === 404 || error.status === 409)) return undefined;+ throw error;+ });+ };// ---- config rendering ---------------------------------------------------const readV1Config = async (): Promise<JsonRecord> => {@@ -907,6 +919,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eif (method !== "POST") break;const body = ((await readBody(req)) ?? {}) as JsonRecord;await prepareSession(sessionID, body, dir);+ await commitRevert(encoded);const name = String(body.command ?? "").replace(/^\//, "");if (name === "compact" || name === "summarize") {await call("POST", `/api/session/${encoded}/compact`, { body: {} });@@ -919,6 +932,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Ecase "shell": {if (method !== "POST") break;const body = ((await readBody(req)) ?? {}) as JsonRecord;+ await commitRevert(encoded);await call("POST", `/api/session/${encoded}/shell`, { body: { command: String(body.command ?? "") } });json(res, 200, { id: "", sessionID, role: "assistant" });return;@@ -939,17 +953,20 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Ereturn;}case "revert": {+ // 2.x stages a reversible revert: the files go back to before the+ // message, the session carries the revert point and the later+ // messages stay until a prompt commits it (1.x's cleanup) or+ // unrevert clears it. 1.x's partID (a revert inside a message)+ // has no 2.x equivalent: the whole message is the boundary.const body = ((await readBody(req)) ?? {}) as JsonRecord;const messageID = str(body, "messageID");- if (messageID) {- await call("POST", `/api/session/${encoded}/revert/stage`, { body: { messageID } });- await call("POST", `/api/session/${encoded}/revert/commit`, { body: {} }).catch(() => undefined);- }+ if (messageID) await call("POST", `/api/session/${encoded}/revert/stage`, { body: { messageID } });json(res, 200, await sessionInfo(sessionID, directory));return;}case "unrevert": {- await call("DELETE", `/api/session/${encoded}/revert`).catch(() => undefined);+ // Restores the files and the hidden messages; a no-op once a prompt committed the revert.+ await call("DELETE", `/api/session/${encoded}/revert`);json(res, 200, await sessionInfo(sessionID, directory));return;}diff --git a/apps/server/src/engine2/revert.e2e.test.ts b/apps/server/src/engine2/revert.e2e.test.tsnew file mode 100644index 00000000..d81eccb1--- /dev/null+++ b/apps/server/src/engine2/revert.e2e.test.ts@@ -0,0 +1,255 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";++/**+ * Revert, undo revert and a prompt after a revert on the real 2.x engine+ * (the bundled sidecar behind the 1.x adapter) against a mock provider whose+ * turns edit a file in a git project:+ *+ * - revert restores the files to the chosen point and reports the revert+ * point on the session, keeping the later messages until it is final;+ * - undo revert brings the files and the revert-free session back;+ * - a prompt after a revert finalises it: the reverted turns are gone from+ * the history (`message.removed` for each), the model never sees them and+ * the new turn continues from the reverted files.+ *+ * Skipped when the sidecar binary is not present (prepare:sidecar not run).+ */++const repoRoot = resolve(import.meta.dir, "../../../..");+const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");+function findSidecar(): string | null {+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64";+ const name = process.platform === "darwin" ? `opencode-${arch}-apple-darwin` : process.platform === "linux" ? `opencode-${arch}-unknown-linux-gnu` : "";+ const candidate = join(sidecarDir, name);+ return name && existsSync(candidate) ? candidate : null;+}+const enginePath = findSidecar();+const describeMaybe = enginePath ? describe : describe.skip;++type Body = { messages?: Array<{ role: string; content: unknown }>; tools?: Array<{ type: string; function: { name: string } }> };+type V1Message = { info: { id: string; role: string; time?: { completed?: number } }; parts: Array<{ type: string; text?: string }> };++function text(content: unknown): string {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content.map((part) => (part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("\n");+}++function sse(chunks: object[]): Response {+ const frame = (payload: object) => `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", ...payload })}\n\n`;+ const body = chunks.map((choice) => frame({ choices: [choice] })).join("")+ + frame({ choices: [], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } })+ + "data: [DONE]\n\n";+ return new Response(body, { headers: { "content-type": "text/event-stream" } });+}+const say = (content: string) => sse([{ index: 0, delta: { role: "assistant", content } }, { index: 0, delta: {}, finish_reason: "stop" }]);+const callTool = (id: string, name: string, args: object) => sse([+ { index: 0, delta: { role: "assistant", content: "" } },+ { index: 0, delta: { tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: JSON.stringify(args) } }] } },+ { index: 0, delta: {}, finish_reason: "tool_calls" },+]);++describeMaybe("revert on the 2.x engine (mock provider, real files)", () => {+ let engine: ManagedOpencodeServer;+ let provider: ReturnType<typeof Bun.serve>;+ let work = "";+ let data = "";+ const seen: Body[] = [];+ const events: Array<{ type: string; properties: Record<string, any> }> = [];+ const eventAbort = new AbortController();++ const engineFetch = async (path: string, init?: RequestInit) => {+ const headers = new Headers(init?.headers);+ headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);+ headers.set("x-opencode-directory", encodeURIComponent(work));+ if (init?.body) headers.set("content-type", "application/json");+ return fetch(`${engine.url}${path}`, { ...init, headers });+ };+ const getJson = async <T>(path: string): Promise<T> => (await (await engineFetch(path)).json()) as T;+ const postJson = async <T>(path: string, body: object): Promise<T> => {+ const response = await engineFetch(path, { method: "POST", body: JSON.stringify(body) });+ if (!response.ok) throw new Error(`${path} answered ${response.status}: ${await response.text()}`);+ return (await response.json()) as T;+ };+ const waitFor = async <T>(read: () => Promise<T | null | undefined | false>, label: string, ms = 60_000): Promise<T> => {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ const value = await read().catch(() => null);+ if (value) return value as T;+ await Bun.sleep(250);+ }+ throw new Error(`timed out waiting for ${label}`);+ };+ const file = () => readFileSync(join(work, "a.txt"), "utf8");+ const messages = (sessionID: string) => getJson<V1Message[]>(`/session/${sessionID}/message`);+ const userTexts = async (sessionID: string) => (await messages(sessionID))+ .filter((message) => message.info.role === "user")+ .map((message) => message.parts.filter((part) => part.type === "text").map((part) => part.text).join(""));+ /** Sends `EDIT n` and waits for the turn that writes `v{n}` to a.txt and answers `ok n`. */+ const edit = async (sessionID: string, n: number) => {+ const sent = await engineFetch(`/session/${sessionID}/prompt_async`, {+ method: "POST",+ body: JSON.stringify({ model: { providerID: "mock", modelID: "mock-model" }, parts: [{ type: "text", text: `EDIT ${n}` }] }),+ });+ expect(sent.status).toBe(204);+ await waitFor(async () => {+ const list = await messages(sessionID);+ const last = list.at(-1);+ return last?.info.role === "assistant" && last.info.time?.completed && last.parts.some((part) => part.type === "text" && part.text === `ok ${n}`);+ }, `turn ${n}`);+ await waitFor(async () => {+ const status = await getJson<Record<string, { type: string }>>("/session/status");+ return !status[sessionID] || status[sessionID]!.type === "idle";+ }, `idle after turn ${n}`);+ expect(file()).toBe(`v${n}\n`);+ };++ beforeAll(async () => {+ work = mkdtempSync(join(tmpdir(), "revert-ws-"));+ data = mkdtempSync(join(tmpdir(), "revert-data-"));+ writeFileSync(join(work, "a.txt"), "v0\n");+ const git = (...args: string[]) => execFileSync("git", args, { cwd: work, stdio: "ignore", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });+ git("init", "-q");+ git("add", ".");+ git("-c", "commit.gpgsign=false", "commit", "-q", "-m", "init");+ provider = Bun.serve({+ port: 0,+ async fetch(request) {+ const url = new URL(request.url);+ const body = request.method === "POST" ? ((await request.json().catch(() => ({}))) as Body) : {};+ if (url.pathname.startsWith("/managed-policy")) return Response.json({ allowed: true, approvalMode: "full" });+ if (!url.pathname.startsWith("/v1/")) return Response.json({});+ if (!Array.isArray(body.tools) || body.tools.length === 0) return say("Revert title");+ seen.push(body);+ const list = body.messages ?? [];+ const lastUser = [...list].reverse().find((message) => message.role === "user");+ const n = Number(/EDIT (\d+)/.exec(text(lastUser?.content))?.[1] ?? "0");+ if (list.at(-1)?.role === "tool") return say(`ok ${n}`);+ const write = body.tools.find((tool) => tool.function.name === "write") ? "write" : body.tools[0]!.function.name;+ return callTool(`call_${n}_${seen.length}`, write, { path: join(work, "a.txt"), content: `v${n}\n` });+ },+ });+ const base = `http://127.0.0.1:${provider.port}`;+ const configPath = join(data, "runtime-opencode-config.json");+ writeFileSync(configPath, JSON.stringify({+ model: "mock/mock-model",+ permission: { "*": "allow" },+ provider: {+ mock: { name: "Mock", npm: "@ai-sdk/openai-compatible", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "mock-model": { name: "Mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },+ },+ }));+ engine = await createManagedOpencodeServer({+ bin: enginePath!,+ cwd: work,+ env: {+ OPENCODE_CONFIG: configPath,+ OPENCODE_DISABLE_MODELS_FETCH: "1",+ OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),+ OMNIRUSH_SERVER_URL: base,+ OMNIRUSH_POLICY_TOKEN: "policy",+ OMNIRUSH_SERVER_TOKEN: "server",+ HOME: join(data, "home"),+ OPENCODE_TEST_HOME: join(data, "home"),+ XDG_DATA_HOME: join(data, "xdg-data"),+ XDG_CONFIG_HOME: join(data, "xdg-config"),+ XDG_STATE_HOME: join(data, "xdg-state"),+ XDG_CACHE_HOME: join(data, "xdg-cache"),+ },+ });+ await waitFor(async () => (await engineFetch("/session")).ok, "engine");+ // The 1.x event stream, as the app reads it.+ void (async () => {+ const response = await engineFetch("/event", { signal: eventAbort.signal });+ const reader = response.body!.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) return;+ buffer += decoder.decode(value, { stream: true });+ let index: number;+ while ((index = buffer.indexOf("\n\n")) >= 0) {+ const frame = buffer.slice(0, index);+ buffer = buffer.slice(index + 2);+ const line = frame.split("\n").find((entry) => entry.startsWith("data:"));+ if (!line) continue;+ try {+ const parsed = JSON.parse(line.slice(5));+ events.push(parsed.payload ?? parsed);+ } catch {+ // not JSON+ }+ }+ }+ })().catch(() => undefined);+ }, 120_000);++ afterAll(async () => {+ eventAbort.abort();+ await engine?.close();+ provider?.stop(true);+ rmSync(work, { recursive: true, force: true });+ rmSync(data, { recursive: true, force: true });+ }, 30_000);++ test("revert, undo revert, and a prompt after revert", async () => {+ const session = await postJson<{ id: string }>("/session", {});+ const sessionID = session.id;+ await edit(sessionID, 1);+ await edit(sessionID, 2);+ await edit(sessionID, 3);+ const before = await messages(sessionID);+ const users = before.filter((message) => message.info.role === "user");+ expect(users).toHaveLength(3);+ const boundary = users[1]!.info.id;+ const beforeIDs = before.map((message) => message.info.id);+ const reverted = beforeIDs.slice(beforeIDs.indexOf(boundary));++ // Revert to the second prompt: the files go back to before it, the session+ // carries the revert point, and the later messages are kept (hidden by the app).+ const afterRevert = await postJson<{ revert?: { messageID: string } }>(`/session/${sessionID}/revert`, { messageID: boundary });+ expect(afterRevert.revert?.messageID).toBe(boundary);+ expect(file()).toBe("v1\n");+ expect((await getJson<{ revert?: { messageID: string } }>(`/session/${sessionID}`)).revert?.messageID).toBe(boundary);+ expect((await messages(sessionID)).map((message) => message.info.id)).toEqual(beforeIDs);+ await waitFor(async () => events.some((event) => event.type === "session.updated" && event.properties.info?.id === sessionID && event.properties.info?.revert?.messageID === boundary), "session.updated with the revert point");++ // Undo: the files and the full history come back.+ const afterUnrevert = await postJson<{ revert?: unknown }>(`/session/${sessionID}/unrevert`, {});+ expect(afterUnrevert.revert).toBeUndefined();+ expect(file()).toBe("v3\n");+ expect((await getJson<{ revert?: unknown }>(`/session/${sessionID}`)).revert).toBeUndefined();+ expect((await messages(sessionID)).map((message) => message.info.id)).toEqual(beforeIDs);+ await waitFor(async () => {+ const last = events.filter((event) => event.type === "session.updated" && event.properties.info?.id === sessionID).at(-1);+ return last && !last.properties.info.revert;+ }, "session.updated without a revert point");++ // Revert again and send a new prompt: the revert becomes final.+ await postJson(`/session/${sessionID}/revert`, { messageID: boundary });+ expect(file()).toBe("v1\n");+ seen.length = 0;+ await edit(sessionID, 4);+ const sentToModel = seen.map((body) => (body.messages ?? []).map((message) => text(message.content)).join("\n")).join("\n");+ expect(sentToModel).toContain("EDIT 1");+ expect(sentToModel).toContain("EDIT 4");+ expect(sentToModel).not.toContain("EDIT 2");+ expect(sentToModel).not.toContain("EDIT 3");+ expect(await userTexts(sessionID)).toEqual(["EDIT 1", "EDIT 4"]);+ const after = await messages(sessionID);+ for (const id of reverted) expect(after.some((message) => message.info.id === id)).toBe(false);+ expect((await getJson<{ revert?: unknown }>(`/session/${sessionID}`)).revert).toBeUndefined();+ await waitFor(async () => reverted.every((id) => events.some((event) => event.type === "message.removed" && event.properties.messageID === id)), "message.removed for each reverted message");++ // Undo after the revert is final is a no-op: the new turn and its file stay.+ await postJson(`/session/${sessionID}/unrevert`, {});+ expect(file()).toBe("v4\n");+ expect(await userTexts(sessionID)).toEqual(["EDIT 1", "EDIT 4"]);+ }, 240_000);+});diff --git a/apps/server/src/session-upload-observer.test.ts b/apps/server/src/session-upload-observer.test.tsindex 262717c1..232ccc8b 100644--- a/apps/server/src/session-upload-observer.test.ts+++ b/apps/server/src/session-upload-observer.test.ts@@ -397,6 +397,35 @@ describe("session upload observer", () => {expect(archive.calls).toEqual(["followed", "completed", "followed", "completed"]);});+ test("a turn after a revert was made final says which messages the session kept, and sends the kept history", async () => {+ const clock = fakeClock();+ const engine = startEngine();+ const sessionUploader = new FakeUploader();+ const archive = fakeArchive();+ const observers = createSessionObservers();+ engine.control.messages = [message("msg_user_0001", "user"), message("msg_assistant_0001", "assistant"), message("msg_user_0002", "user"), message("msg_assistant_0002", "assistant")];+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });+ expect(sessionUploader.trace("session.reverted")).toEqual([]);+ expect(sessionUploader.checkpoint).toBe("msg_assistant_0002");++ // Reverted to the second prompt, then a new one: the engine deleted the second turn.+ engine.control.messages = [message("msg_user_0001", "user"), message("msg_assistant_0001", "assistant"), message("msg_user_0003", "user"), message("msg_assistant_0003", "assistant")];+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });+ expect(sessionUploader.trace("session.reverted")).toEqual([{+ missing_message_id: "msg_assistant_0002",+ kept_message_ids: ["msg_user_0001", "msg_assistant_0001", "msg_user_0003", "msg_assistant_0003"],+ }]);+ expect(sessionUploader.labels().slice(3)).toEqual(["session.reverted", "session.idle", "snapshot:turn_completed", "flush:turn"]);+ expect(sessionUploader.turnMessageIds().at(-1)).toEqual(["msg_user_0001", "msg_assistant_0001", "msg_user_0003", "msg_assistant_0003"]);+ expect(sessionUploader.checkpoint).toBe("msg_assistant_0003");++ // The next ordinary turn carries no marker.+ engine.control.messages.push(message("msg_user_0004", "user"), message("msg_assistant_0004", "assistant"));+ await observe({ sessionUploader, archive, observers, target: engine.target, timing: clock.timing });+ expect(sessionUploader.trace("session.reverted")).toHaveLength(1);+ expect(sessionUploader.turnMessageIds().at(-1)).toEqual(["msg_user_0004", "msg_assistant_0004"]);+ });+test("the server stopping mid-turn ends the observation quietly and leaves the checkpoint where it was", async () => {const clock = fakeClock();const engine = startEngine();diff --git a/apps/server/src/session-upload-observer.ts b/apps/server/src/session-upload-observer.tsindex e4dbe8b1..f6852d4d 100644--- a/apps/server/src/session-upload-observer.ts+++ b/apps/server/src/session-upload-observer.ts@@ -510,6 +510,12 @@ type EngineHistory = {sizes: number[];/** Messages after the checkpoint left out of `delta`: too large to read, or past the budget. */omitted: number;+ /**+ * The checkpoint, when the history no longer holds it: the messages it+ * ended were removed (a revert made final by the next prompt), and the+ * whole kept history is the delta.+ */+ checkpointMissing?: string;};/**@@ -560,7 +566,8 @@ async function readEngineHistory(}omitted += 1;}- return { outline: outline.reverse(), delta: delta.reverse(), sizes: sizes.reverse(), omitted };+ const checkpointMissing = checkpoint && afterCheckpoint && outline.length > 0 ? checkpoint : undefined;+ return { outline: outline.reverse(), delta: delta.reverse(), sizes: sizes.reverse(), omitted, ...(checkpointMissing ? { checkpointMissing } : {}) };}/** When the engine created a message (info.time.created, epoch milliseconds), if it says. */@@ -607,6 +614,7 @@ function historyBefore(history: EngineHistory, cutAt: number): { history: Enginedelta: history.delta.filter((_, index) => keep[index]),sizes: history.sizes.filter((_, index) => keep[index]),omitted: history.omitted,+ ...(history.checkpointMissing ? { checkpointMissing: history.checkpointMissing } : {}),},found: true,answered,@@ -790,6 +798,17 @@ export function observeUploadedSession(input: {observer.lastMessageIds.set(sessionId, lastId);void sessionUploader.setSessionCheckpoint(sessionId, lastId);}+ if (history.checkpointMissing && !v2) {+ // The messages the last upload ended with are gone: a revert was made+ // final. Earlier uploads still hold the reverted turns, so the trace+ // says which messages the session kept (every one, oldest first); any+ // other message an earlier upload carried was reverted. (The v2+ // daemon's context read drops compacted messages, so it is not asked.)+ sessionUploader.recordTrace(sessionId, "session.reverted", {+ missing_message_id: history.checkpointMissing,+ kept_message_ids: history.outline.map(traceMessageId).filter((id): id is string => id !== null),+ });+ }if (history.omitted > 0) sessionUploader.recordTrace(sessionId, "session.messages_omitted", { count: history.omitted });const model = turnModelFromMessages(history.delta);if (model) sessionUploader.recordSessionModel(sessionId, model);