fix: preserve AI line highlight against ProseMirror DOMObserver and prevent crash on accepting suggestions

This commit is contained in:
Schwitzz
2026-10-30 12:20:13 -05:00
parent 271d1e2c79
commit 2940e3c9aa
6 changed files with 240 additions and 39 deletions
+35 -15
View File
@@ -1,6 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { AIStore, AgentController, createIndexedDBPersistence } from "@pubscript/ai";
import {
AIStore,
AgentController,
createIndexedDBPersistence,
createInMemoryPersistence,
} from "@pubscript/ai";
import {
countTokens,
type AIMessage,
@@ -366,7 +371,11 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
useEffect(() => {
if (!projectId) return undefined;
const store = new AIStore(projectId, createIndexedDBPersistence());
const persistence =
typeof indexedDB !== "undefined"
? createIndexedDBPersistence()
: createInMemoryPersistence();
const store = new AIStore(projectId, persistence);
setAiStore(store);
return () => {
void store.dispose();
@@ -440,7 +449,7 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
lineNumber: adjusted.lineNumber,
...(adjusted.originalText ? { originalText: adjusted.originalText } : {}),
};
if (aiStore && activeSessionId) {
if (aiStore && activeSessionId && typeof aiStore.updateSuggestion === "function") {
void aiStore.updateSuggestion(activeSessionId, sg.id, {
lineNumber: adjusted.lineNumber,
...(adjusted.originalText ? { originalText: adjusted.originalText } : {}),
@@ -461,7 +470,7 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
chapterId: currentChapterId,
lines: chapterLines,
};
}, [chapterLines, activeChapter?.id, suggestions, aiStore, activeSessionId, highlightedLine, setHighlightedLine]);
}, [chapterLines, activeChapter?.id]);
// Sidebar drag-resize handler with snap-to-default (370px)
const handleStartResize = (e: React.MouseEvent<HTMLDivElement>) => {
@@ -632,10 +641,12 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
}, [reloadAll]);
useEffect(() => {
scrollRef.current?.scrollTo({
top: scrollRef.current.scrollHeight,
behavior: "smooth",
});
if (scrollRef.current && typeof scrollRef.current.scrollTo === "function") {
scrollRef.current.scrollTo({
top: scrollRef.current.scrollHeight,
behavior: "smooth",
});
}
}, [messages, sending, thinkingStage]);
const handleLoadReload = async () => {
@@ -894,6 +905,15 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
const replacement = (draftEdits[sg.id] ?? sg.newText ?? sg.text).trim();
if (!replacement) return;
// Remove the accepted suggestion from state and persistence first so line
// re-anchoring only runs on the remaining pending suggestions.
setSuggestions((prev) => prev.filter((item) => item.id !== sg.id));
if (typeof aiStore.deleteSuggestion === "function") {
await aiStore.deleteSuggestion(activeSessionId, sg.id);
} else {
await aiStore.resolveSuggestion(activeSessionId, sg.id, true);
}
const applied = await applyLineEdit({
...(sg.chapterId ? { chapterId: sg.chapterId } : {}),
...(sg.lineNumber != null ? { lineNumber: sg.lineNumber } : {}),
@@ -901,7 +921,6 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
newText: replacement,
});
await aiStore.deleteSuggestion(activeSessionId, sg.id);
const nextList = await aiStore.listSuggestions(activeSessionId);
setSuggestions(nextList);
@@ -914,7 +933,12 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
const handleDenySuggestion = async (sg: AISuggestion) => {
if (!aiStore || !activeSessionId) return;
await aiStore.deleteSuggestion(activeSessionId, sg.id);
setSuggestions((prev) => prev.filter((item) => item.id !== sg.id));
if (typeof aiStore.deleteSuggestion === "function") {
await aiStore.deleteSuggestion(activeSessionId, sg.id);
} else {
await aiStore.resolveSuggestion(activeSessionId, sg.id, false);
}
const nextList = await aiStore.listSuggestions(activeSessionId);
setSuggestions(nextList);
if (highlightedLine === sg.lineNumber) {
@@ -960,11 +984,7 @@ export function AISidebar({ fullPage = false }: AISidebarProps) {
const handleHighlightLine = (lineNum: number | undefined) => {
if (!lineNum) return;
if (highlightedLine === lineNum) {
setHighlightedLine(null);
} else {
setHighlightedLine(lineNum);
}
setHighlightedLine(lineNum);
};
const renderMessageWithLineLinks = (content: string) => {
+136
View File
@@ -0,0 +1,136 @@
/**
* @vitest-environment jsdom
*/
import { describe, it, expect, beforeEach, vi } from "vitest";
import { createRoot } from "react-dom/client";
import { act } from "react";
import { MemoryRouter } from "react-router-dom";
import type { Chapter, ProjectMeta, StorageAdapter } from "@pubscript/core";
import { useProjectStore } from "../../store/project-store.js";
import { WritingView } from "../../components/WritingView.js";
import { AISidebar } from "./AISidebar.js";
describe("AISidebar + WritingView accept suggestion flow", () => {
beforeEach(() => {
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
Element.prototype.scrollIntoView = () => {};
Range.prototype.getClientRects = () =>
({
length: 0,
item: () => null,
[Symbol.iterator]: function* () {},
}) as unknown as DOMRectList;
Range.prototype.getBoundingClientRect = () =>
({ top: 0, left: 0, bottom: 0, right: 0, width: 0, height: 0, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect;
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("offline"));
const ch: Chapter = {
id: "ch-1",
bookId: "book-1",
projectId: "proj-1",
title: "Chapter One",
order: 0,
rev: 1,
meta: { wordCount: 10, scenes: [], updatedAt: new Date().toISOString() },
doc: {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "The ferry that carried Mara Vell to the Glass Harbor left the mainland before dawn.",
},
],
},
{
type: "paragraph",
content: [
{
type: "text",
text: "She pressed her palm against the cold window and watched the lighthouse appear out of the mist.",
},
],
},
{
type: "paragraph",
content: [
{
type: "text",
text: "Three years since she had last seen it, and yet it seemed to have shrunk.",
},
],
},
],
},
};
const mockAdapter = {
async saveDocument() {},
} as unknown as StorageAdapter;
useProjectStore.setState({
adapter: mockAdapter,
project: { id: "proj-1", title: "Test Project" } as ProjectMeta,
chapters: [ch],
activeChapterId: "ch-1",
highlightedLine: null,
docExternalRev: 0,
status: "ready",
});
});
it("generates line suggestions, highlights line on click, and accepts one without crashing", async () => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(
<MemoryRouter>
<div style={{ display: "flex" }}>
<WritingView />
<AISidebar />
</div>
</MemoryRouter>,
);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 80));
});
const genBtn = Array.from(container.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Suggest Line Edits for Chapter"),
);
expect(genBtn).toBeDefined();
await act(async () => {
genBtn!.click();
});
await act(async () => {
await new Promise((r) => setTimeout(r, 1600));
});
const acceptBtn = Array.from(container.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Accept"),
);
if (!acceptBtn) {
console.log("BUTTONS:", Array.from(container.querySelectorAll("button")).map((b) => b.textContent));
}
expect(acceptBtn).toBeDefined();
await act(async () => {
acceptBtn!.click();
await new Promise((r) => setTimeout(r, 150));
});
const pm = container.querySelector(".ProseMirror");
expect(pm?.textContent).toContain("sharp and unmistakable");
await act(async () => {
root.unmount();
});
container.remove();
});
});