Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix: preserve one undo step per agent turn

wuzixuan067632d5c93302
diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts
index 3cd1c53f6..081e25463 100644
--- a/electron/ai-edition/chat-service.ts
+++ b/electron/ai-edition/chat-service.ts
@@ -523,9 +523,8 @@ export async function runChat(
success: true,
assistantMessage,
cancelled: result.cancelled,
- // Non-streaming callers still receive the completed document. Both this
- // fallback and the document event above enforce the edit setting; the
- // panel never reapplies this aggregate after individual streamed edits.
+ // Return the accumulated edits even on Stop. The panel applies this once
+ // at the end of the turn, preserving one save and one undo step per turn.
document: result.mutated && editsAllowed ? result.document : undefined,
toolCalls: appliedToolCalls.length ? appliedToolCalls : undefined,
userMessageCheckpointId: userMessage.checkpointId ?? undefined,
diff --git a/src/components/ai-edition/LeftPanel.stop.test.tsx b/src/components/ai-edition/LeftPanel.stop.test.tsx
index 60e07823b..b6dea34b0 100644
--- a/src/components/ai-edition/LeftPanel.stop.test.tsx
+++ b/src/components/ai-edition/LeftPanel.stop.test.tsx
@@ -6,7 +6,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
import { EditorDialogsProvider } from "@/contexts/EditorDialogsContext";
import { createEmptyDocument } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
-import { clearHistory, undo } from "@/lib/ai-edition/store/undo";
+import { clearHistory, redo, undo } from "@/lib/ai-edition/store/undo";
import { past } from "@/lib/ai-edition/store/undoStack";
import type { AiEditionChatEvent, AiEditionChatResult } from "@/native/contracts";
import { ChatStripPanel } from "./LeftPanel";
@@ -19,6 +19,7 @@ const api = vi.hoisted(() => ({
select: vi.fn(),
create: vi.fn(),
error: vi.fn(),
+ warning: vi.fn(),
}));
vi.mock("@/native/client", () => ({
nativeBridgeClient: {
@@ -41,7 +42,7 @@ vi.mock("@/contexts/I18nContext", () => ({
useI18n: () => ({ locale: "en" }),
useScopedT: () => (key: string) => key,
}));
-vi.mock("sonner", () => ({ toast: { error: api.error, warning: vi.fn() } }));
+vi.mock("sonner", () => ({ toast: { error: api.error, warning: api.warning } }));
let onEvent: (event: AiEditionChatEvent) => void;
let replies: ((value: AiEditionChatResult) => void)[];
const doc = (title: string, projectId = "p") => createEmptyDocument({ projectId, title });
@@ -125,27 +126,39 @@ function emit(
}
describe("composer Stop", () => {
- it("keeps edits and undo steps, retains partial reply, ignores old events and starts the next turn", async () => {
+ it("commits stopped edits once, retains the live reply, ignores old events and starts the next turn", async () => {
panel();
const id = await start();
expect(screen.getByRole("button", { name: "chat.stop" })).toBeEnabled();
emit(id, { kind: "document", document: doc("First") });
emit(id, { kind: "document", document: doc("Second") });
emit(id, { kind: "text", delta: "Partial" });
- await waitFor(() => expect(past).toHaveLength(2));
+ await act(async () => {
+ // Flush event work before checking that no intermediate edits were saved.
+ });
+ expect(screen.getByText("Partial")).toBeVisible();
+ expect(api.save).not.toHaveBeenCalled();
+ expect(past).toHaveLength(0);
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
fireEvent.click(screen.getByRole("button", { name: "chat.stop" }));
fireEvent.click(screen.getByRole("button", { name: "chat.stop" }));
expect(api.cancel).toHaveBeenCalledOnce();
expect(api.cancel).toHaveBeenCalledWith("p", "s", id);
- await act(async () => replies[0](result("Partial", true)));
+ await act(async () => replies[0]({ ...result("Partial", true), document: doc("Second") }));
expect(screen.getByText("chat.stopped")).toBeVisible();
expect(screen.getByText("Partial")).toBeVisible();
expect(screen.getByRole("button", { name: "chat.send" })).toBeInTheDocument();
- expect(api.save).toHaveBeenCalledTimes(2);
+ expect(api.save).toHaveBeenCalledOnce();
+ expect(past).toHaveLength(1);
+ expect(useProjectStore.getState().document?.project.title).toBe("Second");
act(() => {
undo();
});
- expect(useProjectStore.getState().document?.project.title).toBe("First");
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
+ act(() => {
+ redo();
+ });
+ expect(useProjectStore.getState().document?.project.title).toBe("Second");
const nextId = await start();
expect(nextId).not.toBe(id);
emit(id, { kind: "text", delta: "STALE" });
@@ -157,6 +170,70 @@ describe("composer Stop", () => {
expect(api.error).not.toHaveBeenCalled();
});
+ it.each([false, true])("keeps a long turn in one undo step (stopped: %s)", async (stopped) => {
+ useProjectStore.getState().setDocument(doc("Pre-turn"), { history: true });
+ panel();
+ const id = await start();
+ for (let i = 0; i < 60; i++) {
+ emit(id, { kind: "document", document: doc(`Tool ${i}`) });
+ }
+ await act(async () => {
+ // Let any queued per-tool writes run so the regression cannot hide in microtasks.
+ });
+ expect(api.save).not.toHaveBeenCalled();
+ expect(past).toHaveLength(1);
+ if (stopped) fireEvent.click(screen.getByRole("button", { name: "chat.stop" }));
+ await act(async () =>
+ replies[0]({ ...result("Done", stopped), document: doc("Final aggregate") }),
+ );
+ expect(api.save).toHaveBeenCalledOnce();
+ expect(past).toHaveLength(2);
+ expect(useProjectStore.getState().document?.project.title).toBe("Final aggregate");
+ act(() => {
+ undo();
+ });
+ expect(useProjectStore.getState().document?.project.title).toBe("Pre-turn");
+ act(() => {
+ undo();
+ });
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
+ });
+
+ it("applies a stopped aggregate when no document event arrived", async () => {
+ panel();
+ await start();
+ fireEvent.click(screen.getByRole("button", { name: "chat.stop" }));
+ await act(async () =>
+ replies[0]({ ...result("Partial", true), document: doc("Completed edit") }),
+ );
+ expect(api.save).toHaveBeenCalledOnce();
+ expect(past).toHaveLength(1);
+ expect(useProjectStore.getState().document?.project.title).toBe("Completed edit");
+ act(() => {
+ undo();
+ });
+ expect(useProjectStore.getState().document?.project.title).toBe("Before");
+ });
+
+ it("keeps manual edits during a turn until Apply anyway commits the aggregate once", async () => {
+ panel();
+ const id = await start();
+ emit(id, { kind: "document", document: doc("First") });
+ act(() => useProjectStore.getState().setDocument(doc("Manual"), { history: true }));
+ emit(id, { kind: "document", document: doc("Second") });
+ await act(async () => replies[0]({ ...result("Done"), document: doc("Second") }));
+ expect(api.save).not.toHaveBeenCalled();
+ expect(useProjectStore.getState().document?.project.title).toBe("Manual");
+ expect(api.warning).toHaveBeenCalledWith("chat.agentEditConflict", expect.any(Object));
+ await act(async () => api.warning.mock.calls[0][1].action.onClick());
+ await waitFor(() => expect(api.save).toHaveBeenCalledOnce());
+ expect(useProjectStore.getState().document?.project.title).toBe("Second");
+ act(() => {
+ undo();
+ });
+ expect(useProjectStore.getState().document?.project.title).toBe("Manual");
+ });
+
it("stops while creating the first session without sending a model request", async () => {
api.list.mockResolvedValue([]);
let created!: (value: ReturnType<typeof session>) => void;
@@ -184,11 +261,12 @@ describe("composer Stop", () => {
act(() => useProjectStore.setState({ projectId: "other", document: doc("Other", "other") }));
await waitFor(() => expect(api.cancel).toHaveBeenCalledWith("p", "s", id));
await start();
- await act(async () => replies[0](result("Old reply", true)));
+ await act(async () => replies[0]({ ...result("Old reply", true), document: doc("Old") }));
emit(id, { kind: "document", document: doc("Old") });
expect(screen.queryByText("Old reply")).toBeNull();
expect(screen.getByRole("button", { name: "chat.stop" })).toBeEnabled();
expect(useProjectStore.getState().document?.project.title).toBe("Other");
+ expect(api.save).not.toHaveBeenCalled();
await act(async () => replies[1](result("New reply")));
});
@@ -197,14 +275,16 @@ describe("composer Stop", () => {
const id = await start();
fireEvent.click(screen.getByRole("button", { name: "chat.newConversation" }));
await waitFor(() => expect(api.cancel).toHaveBeenCalledWith("p", "s", id));
- await act(async () => replies[0](result("Old", true)));
+ await act(async () => replies[0]({ ...result("Old", true), document: doc("Old") }));
expect(screen.queryByText("Old")).toBeNull();
+ expect(api.save).not.toHaveBeenCalled();
fireEvent.change(screen.getByRole("textbox"), { target: { value: "Next" } });
fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" });
await waitFor(() => expect(api.run).toHaveBeenCalledTimes(2));
const nextId = api.run.mock.calls[1][4];
view.unmount();
expect(api.cancel).toHaveBeenLastCalledWith("p", "new", nextId);
- await act(async () => replies[1](result("Disposed", true)));
+ await act(async () => replies[1]({ ...result("Disposed", true), document: doc("Disposed") }));
+ expect(api.save).not.toHaveBeenCalled();
});
});
diff --git a/src/components/ai-edition/LeftPanel.tsx b/src/components/ai-edition/LeftPanel.tsx
index 21e43ab9b..059abe205 100644
--- a/src/components/ai-edition/LeftPanel.tsx
+++ b/src/components/ai-edition/LeftPanel.tsx
@@ -6,8 +6,10 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Tooltip } from "@/components/ui/tooltip";
import { useEditorDialogActions, useEditorDialogSection } from "@/contexts/EditorDialogsContext";
import { useScopedT } from "@/contexts/I18nContext";
-import { applyAgentDocumentIfCurrent } from "@/lib/ai-edition/store/agentDocumentApply";
-import { AgentDocumentStream } from "@/lib/ai-edition/store/agentDocumentStream";
+import {
+ applyAgentDocumentIfCurrent,
+ runAgentTurn,
+} from "@/lib/ai-edition/store/agentDocumentApply";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useChatPromptBus } from "@/lib/ai-edition/store/useChatPromptBus";
import { nativeBridgeClient } from "@/native/client";
@@ -446,7 +448,6 @@ export function ChatStripPanel() {
sessionId: string | null;
stopping: boolean;
thinking: string;
- stream: AgentDocumentStream;
} | null>(null);
const viewRef = useRef({ projectId, sessionId: null as string | null });
const [llmConfig, setLlmConfig] = useState<AiEditionLlmConfig | null>(null);
@@ -535,7 +536,6 @@ export function ChatStripPanel() {
const run = runRef.current;
if (!run) return;
runRef.current = null;
- run.stream.close();
if (run.sessionId) {
void nativeBridgeClient.aiEdition
.chatCancel(run.projectId, run.sessionId, run.id)
@@ -558,8 +558,7 @@ export function ChatStripPanel() {
viewRef.current.sessionId !== run.sessionId
)
return;
- if (event.kind === "document") run.stream.push(event.document);
- else if (event.kind === "thinking") {
+ if (event.kind === "thinking") {
run.thinking += event.delta;
setThinkingText(run.thinking);
} else if (event.kind === "text") setLiveText((prev) => prev + event.delta);
@@ -673,7 +672,6 @@ export function ChatStripPanel() {
sessionId: activeSessionId,
stopping: false,
thinking: "",
- stream: new AgentDocumentStream(),
};
runRef.current = run;
latestRunIdRef.current = run.id;
@@ -726,41 +724,45 @@ export function ChatStripPanel() {
}
if (!isCurrent() || run.stopping) return;
run.sessionId = sessionId;
- run.stream = new AgentDocumentStream();
- const documentSnapshot = useProjectStore.getState().document ?? undefined;
- const result = await nativeBridgeClient.aiEdition.chatRun(
- projectId,
- sessionId,
- text,
- documentSnapshot,
- run.id,
+ // Capture the document and its revision together before awaiting the turn.
+ // Stop returns the completed tools' aggregate too: commit it once so the
+ // entire turn has one save and one undo step, regardless of tool count.
+ const { result, applyDocument } = await runAgentTurn((documentSnapshot) =>
+ nativeBridgeClient.aiEdition.chatRun(projectId, sessionId, text, documentSnapshot, run.id),
);
if (!isCurrent()) return;
- // Non-streaming callers keep their existing result path. Completed tool
- // edits already in history are never saved again as one aggregate.
- if (!run.stream.seen && result.document && !result.cancelled)
- run.stream.push(result.document);
- await run.stream.finish();
- if (!isCurrent()) return;
- if (run.stream.failure === "conflict")
- toast.warning(t("chat.agentEditConflict"), {
- duration: Number.POSITIVE_INFINITY,
- action: {
- label: t("chat.applyAnyway"),
- onClick: () => {
- if (
- latestRunIdRef.current !== run.id ||
- viewRef.current.projectId !== projectId ||
- viewRef.current.sessionId !== sessionId
- )
- return;
- void run.stream.applyRemaining().then(() => {
- if (run.stream.failure === "save-failed") toast.error(t("chat.applyEditsFailed"));
- });
+ if (result.document) {
+ const applyEdits = async (options?: { ignoreConflict?: boolean }) => {
+ try {
+ const applied = await applyDocument(options);
+ if (applied === "save-failed") toast.error(t("chat.applyEditsFailed"));
+ return applied;
+ } catch (error) {
+ toast.error(t("chat.applyEditsFailed"), {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ return "malformed" as const;
+ }
+ };
+ const applied = await applyEdits();
+ if (!isCurrent()) return;
+ if (applied === "conflict")
+ toast.warning(t("chat.agentEditConflict"), {
+ duration: Number.POSITIVE_INFINITY,
+ action: {
+ label: t("chat.applyAnyway"),
+ onClick: () => {
+ if (
+ latestRunIdRef.current !== run.id ||
+ viewRef.current.projectId !== projectId ||
+ viewRef.current.sessionId !== sessionId
+ )
+ return;
+ void applyEdits({ ignoreConflict: true });
+ },
},
- },
- });
- else if (run.stream.failure === "save-failed") toast.error(t("chat.applyEditsFailed"));
+ });
+ }
setMessages((prev) => adoptStoredUserMessage(prev, optimisticUserId, result));
// A rewind confirmation opened during the turn names the message too. Stored without a
// checkpoint, the message has nothing to rewind to and the confirmation closes.
@@ -801,7 +803,6 @@ export function ChatStripPanel() {
description: err instanceof Error ? err.message : String(err),
});
} finally {
- run.stream.close();
if (isCurrent()) {
runRef.current = null;
setBusy(false);
diff --git a/src/lib/ai-edition/store/agentDocumentStream.test.ts b/src/lib/ai-edition/store/agentDocumentStream.test.ts
deleted file mode 100644
index 713c0ce73..000000000
--- a/src/lib/ai-edition/store/agentDocumentStream.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-// @vitest-environment jsdom
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { createEmptyDocument } from "../schema";
-import { AgentDocumentStream } from "./agentDocumentStream";
-import { useProjectStore } from "./projectStore";
-import { clearHistory, redo, undo } from "./undo";
-import { past } from "./undoStack";
-
-const save = vi.hoisted(() => vi.fn());
-vi.mock("@/native/client", () => ({ nativeBridgeClient: { aiEdition: { save } } }));
-const document = (title: string, projectId = "p") => createEmptyDocument({ projectId, title });
-beforeEach(() => {
- useProjectStore.getState().clear();
- clearHistory();
- useProjectStore.setState({ projectId: "p", document: document("Before"), revision: 1 });
- save.mockReset().mockImplementation(async (doc) => ({ success: true, document: doc }));
-});
-
-describe("completed agent edits", () => {
- it("keeps each applied edit as its existing undo step after stop, without an aggregate resave", async () => {
- const stream = new AgentDocumentStream();
- stream.push(document("First"));
- stream.push(document("Second"));
- await stream.finish();
- stream.push(document("Late"));
- expect(save).toHaveBeenCalledTimes(2);
- expect(past).toHaveLength(2);
- expect(useProjectStore.getState().document?.project.title).toBe("Second");
- expect(undo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("First");
- expect(undo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("Before");
- expect(redo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("First");
- });
-
- it("drops queued edits after abandonment and never writes into a switched project", async () => {
- const stream = new AgentDocumentStream();
- stream.push(document("Old"));
- stream.close();
- useProjectStore.setState({ projectId: "other", document: document("Other", "other") });
- await stream.finish();
- expect(save).not.toHaveBeenCalled();
- expect(useProjectStore.getState().document?.project.title).toBe("Other");
- });
-
- it("detects an undo between tool edits instead of overwriting it", async () => {
- const stream = new AgentDocumentStream();
- stream.push(document("First"));
- await vi.waitFor(() => expect(past).toHaveLength(1));
- undo();
- stream.push(document("Second"));
- stream.push(document("Third"));
- await stream.finish();
- expect(stream.failure).toBe("conflict");
- expect(save).toHaveBeenCalledOnce();
- expect(useProjectStore.getState().document?.project.title).toBe("Before");
- // The existing Apply anyway action resumes only the unapplied steps.
- await stream.applyRemaining();
- expect(save).toHaveBeenCalledTimes(3);
- expect(useProjectStore.getState().document?.project.title).toBe("Third");
- expect(undo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("Second");
- expect(undo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("Before");
- });
-
- it("can start another stream on the stopped turn's applied document", async () => {
- const first = new AgentDocumentStream();
- first.push(document("First"));
- await first.finish();
- const next = new AgentDocumentStream();
- next.push(document("Next"));
- await next.finish();
- expect(next.failure).toBeNull();
- expect(past).toHaveLength(2);
- expect(undo()).toBe(true);
- expect(useProjectStore.getState().document?.project.title).toBe("First");
- });
-});
diff --git a/src/lib/ai-edition/store/agentDocumentStream.ts b/src/lib/ai-edition/store/agentDocumentStream.ts
deleted file mode 100644
index 3626b7318..000000000
--- a/src/lib/ai-edition/store/agentDocumentStream.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { type AgentDocumentApplyResult, applyAgentDocumentIfCurrent } from "./agentDocumentApply";
-import { useProjectStore } from "./projectStore";
-
-/** Serialises completed tool edits through the existing save/undo boundary.
- * Finishing a turn drains these writes; abandoning its panel discards queued edits.
- * Never reapply the final aggregate after individual edits have reached history. */
-export class AgentDocumentStream {
- private queue: Promise<void> = Promise.resolve();
- private closed = false;
- private readonly pending: unknown[] = [];
- private revision: number;
- private readonly projectId: string | null;
- private readonly hasDocument: boolean;
- seen = false;
- failure: AgentDocumentApplyResult | null = null;
-
- constructor() {
- const state = useProjectStore.getState();
- this.revision = state.revision;
- this.projectId = state.projectId;
- this.hasDocument = state.document !== null;
- }
-
- push(document: unknown): void {
- if (this.closed) return;
- this.seen = true;
- this.queue = this.queue
- .then(async () => {
- if (this.closed) return;
- if (this.failure) {
- this.pending.push(document);
- return;
- }
- if (!this.hasDocument || useProjectStore.getState().projectId !== this.projectId) {
- this.failure = "no-live-document";
- return;
- }
- const applying = applyAgentDocumentIfCurrent(document, this.revision);
- // An applied edit bumps once for its optimistic setDocument and once for
- // its save. A manual edit/undo during that save remains a conflict for
- // the NEXT tool too; don't adopt an unrelated new revision as our own.
- const result = await applying;
- if (result === "applied") this.revision += 2;
- else {
- this.failure = result;
- this.pending.push(document);
- }
- })
- .catch(() => {
- this.failure = "save-failed";
- });
- }
-
- /** Explicit user consent to apply the remaining edits over a conflicting revision. */
- async applyRemaining(): Promise<void> {
- if (useProjectStore.getState().projectId !== this.projectId) return;
- this.revision = useProjectStore.getState().revision;
- this.failure = null;
- this.closed = false;
- for (const document of this.pending.splice(0)) this.push(document);
- await this.finish();
- }
-
- close(): void {
- this.closed = true;
- }
-
- async finish(): Promise<void> {
- await this.queue;
- this.close();
- }
-}