Merge commit 'a7900033f202ddd942aa203e799656d340b669bb' into codex/validate-reviewed-integration

This commit is contained in:
Bingxi Zhao (Frank)
2026-10-31 18:52:31 +08:00
3 changed files with 80 additions and 0 deletions

View File

@@ -73,6 +73,9 @@ export function useReadingWorkspace(
const [organizedNotes, setOrganizedNotes] =
useState<OrganizedReadingNotes | null>(null);
const sessionBootRef = useRef("");
// The conversation that was open when this collection started a new one; it
// belongs to wherever the learner came from, never to this collection.
const inheritedSessionRef = useRef<string | null>(null);
const transcriptRequestRef = useRef(0);
const refreshConversations = useCallback(async () => {
@@ -202,6 +205,7 @@ export function useReadingWorkspace(
await loadSession(sessionIdParam);
configureSession(sessionConfiguration, sessionIdParam);
} else {
inheritedSessionRef.current = state.sessionId;
newSession({ ...sessionConfiguration, capability: null });
}
} catch (caught) {
@@ -440,8 +444,16 @@ export function useReadingWorkspace(
// named. So the address bar is corrected in place and `usePathname` — which
// does follow the native API — keeps `sessionIdParam` honest for refreshes,
// links and the back button.
//
// Only once this collection has started its own draft. Until the boot above
// runs, `state.sessionId` is still whatever conversation was open before the
// learner came here (a /chat thread, say); naming it in the URL made the boot
// take it for this collection's conversation and keep it, so the reader's
// questions went to that unrelated thread without the page or selection.
useEffect(() => {
if (!state.sessionId || sessionIdParam) return;
if (sessionBootRef.current !== `${workspaceId}:new`) return;
if (state.sessionId === inheritedSessionRef.current) return;
window.history.replaceState(
null,
"",

View File

@@ -230,6 +230,22 @@ test("naming the first turn's conversation does not remount the reader", () => {
assert.doesNotMatch(page, /params\.sessionId/);
});
test("a conversation left open elsewhere is never named as the collection's", () => {
const hook = source(`${WORKSPACE_DIR}/useReadingWorkspace.ts`);
// The chat state is shared app-wide, so a /chat thread is still loaded when
// the learner opens a collection. Writing that id into the URL before the
// collection had started its own draft made the boot keep the /chat thread,
// and Explain / Translate / Guide went to it without the page or selection.
const binding = /if \(!state\.sessionId \|\| sessionIdParam\) return;[\s\S]{0,400}?\}, \[/.exec(
hook,
);
assert.ok(binding, "the session-id binding effect should still be here");
assert.match(binding[0], /sessionBootRef\.current !== `\$\{workspaceId\}:new`/);
assert.match(binding[0], /state\.sessionId === inheritedSessionRef\.current/);
assert.match(hook, /inheritedSessionRef\.current = state\.sessionId;\s*newSession\(/);
});
test("material hydration owns its loading state from the first request tick", () => {
const hook = source(`${WORKSPACE_DIR}/useReadingWorkspace.ts`);

View File

@@ -0,0 +1,52 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
import { useReadingWorkspace } from "@/components/reading/workspace/useReadingWorkspace";
const mocks = vi.hoisted(() => ({
state: { sessionId: "chat-old" as string | null },
newSession: vi.fn(), loadSession: vi.fn().mockResolvedValue(undefined),
configureSession: vi.fn(), getWorkspace: vi.fn(),
reading: { material: null, annotations: [], openMaterial: vi.fn(), closeMaterial: vi.fn(), reportViewport: vi.fn() },
router: { push: vi.fn() }, t: (key: string) => key,
}));
vi.mock("next/navigation", () => ({useRouter: () => mocks.router}));
vi.mock("react-i18next", () => ({useTranslation: () => ({t: mocks.t})}));
vi.mock("@/context/ReadingContext", () => ({useReading: () => mocks.reading}));
vi.mock("@/features/chat/ChatStateAdapter", () => ({useChatStateAdapter: () => mocks}));
vi.mock("@/lib/reading-turn-state", () => ({setReadingWorkspace: vi.fn()}));
vi.mock("@/lib/reading-workspace-api", async (original) => ({
...await original<typeof import("@/lib/reading-workspace-api")>(),
getReadingWorkspace: mocks.getWorkspace,
listReadingConversations: vi.fn().mockResolvedValue([]),
}));
const workspace = {workspace_id: "collection", title: "Book", active_material_id: null, tabs: []};
beforeEach(() => {
vi.clearAllMocks();
mocks.state.sessionId = "chat-old";
window.history.replaceState(null, "", "/learning/reading/collection");
});
it("does not adopt an inherited chat before or after asynchronous collection hydration", async () => {
let resolve!: (value: unknown) => void;
mocks.getWorkspace.mockReturnValue(new Promise(r => {resolve = r;}));
const {rerender} = renderHook(() => useReadingWorkspace("collection", null));
expect(window.location.pathname).toBe("/learning/reading/collection");
expect(mocks.newSession).not.toHaveBeenCalled();
await act(async () => {resolve({workspace});});
await waitFor(() => expect(mocks.newSession).toHaveBeenCalledTimes(1));
// The shared adapter can still expose the old id until its update renders.
rerender();
expect(window.location.pathname).toBe("/learning/reading/collection");
mocks.state.sessionId = null;
rerender();
mocks.state.sessionId = "reading-new";
rerender();
expect(window.location.pathname).toBe("/learning/reading/collection/sessions/reading-new");
expect(mocks.loadSession).not.toHaveBeenCalled();
});
it("loads an explicitly linked reading session instead of starting a draft", async () => {
mocks.getWorkspace.mockResolvedValue({workspace});
renderHook(() => useReadingWorkspace("collection", "reading-existing"));
await waitFor(() => expect(mocks.loadSession).toHaveBeenCalledWith("reading-existing"));
expect(mocks.newSession).not.toHaveBeenCalled();
expect(mocks.configureSession).toHaveBeenCalledWith(expect.anything(), "reading-existing");
});