Compare commits
10 Commits
fix/260-co
...
docs/dev-s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef173f022d | ||
| 38f9a7938a | |||
|
|
30cdd65b92 | ||
|
|
b601c78c21 | ||
| 79394b3ef8 | |||
| e3ec9a2965 | |||
| 449a304657 | |||
|
|
42a1fa1d3a | ||
|
|
67312a3753 | ||
|
|
ef27b6d440 |
@@ -197,6 +197,12 @@ pnpm workspace (`pnpm@10.4.0`) orchestrated by **Nx**. Four workspace packages:
|
||||
|
||||
Run from the repo root unless noted. The dev workflow needs **Postgres (with the `pgvector` extension) and Redis** reachable per `.env` (copy `.env.example` → `.env`).
|
||||
|
||||
> **Bringing up a full local stand** (API + client + the separate realtime
|
||||
> collaboration process) has several non-obvious gotchas — a missing collab
|
||||
> server, `APP_SECRET` mismatch between processes, a stale `editor-ext` white-
|
||||
> screening the client, LAN exposure. See **[docs/dev-stand.md](docs/dev-stand.md)**
|
||||
> for the step-by-step and the traps.
|
||||
|
||||
```bash
|
||||
pnpm install # install all workspaces (uses pnpm patches; see package.json `pnpm.patchedDependencies`)
|
||||
pnpm dev # client (Vite) + server (Nest watch) concurrently — primary dev loop
|
||||
@@ -241,6 +247,8 @@ Migration files live in `apps/server/src/database/migrations/` and are named `YY
|
||||
- **API server** — `dist/main` (`apps/server/src/main.ts`), the Fastify HTTP app (`AppModule`).
|
||||
- **Collaboration server** — `dist/collaboration/server/collab-main` (`pnpm collab`), a Hocuspocus/Yjs WebSocket server (`apps/server/src/collaboration/`) handling real-time document editing, persistence, and page-history snapshots. It listens on `COLLAB_PORT` (default `3001`), separate from the API server's `PORT` (default `3000`), and shares state with the API server through Redis.
|
||||
|
||||
`pnpm dev` starts **only** the API server + client — the collaboration process is separate and must be started too, or the editor never connects. See **[docs/dev-stand.md](docs/dev-stand.md)** for running both locally (and why `APP_SECRET` must match between them).
|
||||
|
||||
The API server is a Fastify app with a global `/api` prefix (`main.ts` excludes `robots.txt`, public share pages, and `mcp` from the prefix). A `preHandler` hook enforces that a resolved `workspaceId` exists for most `/api` routes (multi-tenant by hostname/subdomain via `DomainMiddleware`). `GET /api/sb/:id` (the anonymous blob-sandbox read route) is listed in that preHandler's `excludedPaths`, so it is exempt from workspace resolution and carries no session auth at all (its capability is the unguessable UUID + TTL + TLS) — unlike `/api/files/public/...`, which still resolves a workspace and requires a workspace-bound attachment JWT. Auth is JWT (cookie + bearer); authorization is **CASL** (`core/casl`) — every data access is scoped to the user's abilities.
|
||||
|
||||
### Module structure (server)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
|
||||
// Shared, hoisted test state the module mocks write into. `onSpeechEnd` is the
|
||||
// VAD callback the hook registers on MicVAD.new — capturing it lets us drive
|
||||
// "a speech segment ended" deterministically. `pending` collects the deferred
|
||||
// transcription promises so the test controls their resolution order, which is
|
||||
// the whole point: out-of-order HTTP responses must NOT scramble the emitted
|
||||
// text (the in-order emitter under test).
|
||||
const h = vi.hoisted(() => {
|
||||
return {
|
||||
onSpeechEnd: null as null | ((audio: Float32Array) => void),
|
||||
pending: [] as { resolve: (s: string) => void; reject: (e: unknown) => void }[],
|
||||
notify: null as null | ReturnType<typeof Object>,
|
||||
};
|
||||
});
|
||||
|
||||
// Lazy-imported VAD: capture the onSpeechEnd handler and hand back a no-op
|
||||
// instance (start/pause/destroy all resolve).
|
||||
vi.mock("@ricky0123/vad-web", () => ({
|
||||
MicVAD: {
|
||||
new: vi.fn(async (opts: { onSpeechEnd: (a: Float32Array) => void }) => {
|
||||
h.onSpeechEnd = opts.onSpeechEnd;
|
||||
return {
|
||||
start: vi.fn(async () => {}),
|
||||
pause: vi.fn(async () => {}),
|
||||
destroy: vi.fn(async () => {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
// Each transcribeAudio call returns a promise we resolve/reject by index.
|
||||
vi.mock("@/features/dictation/services/dictation-service", () => ({
|
||||
transcribeAudio: vi.fn(
|
||||
() =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
h.pending.push({ resolve, reject });
|
||||
}),
|
||||
),
|
||||
}));
|
||||
|
||||
// Avoid real WAV encoding; the segment payload is irrelevant to ordering.
|
||||
vi.mock("@/features/dictation/utils/encode-wav", () => ({
|
||||
encodeWavPcm16: vi.fn(() => new Blob()),
|
||||
}));
|
||||
|
||||
const notifyShow = vi.fn();
|
||||
vi.mock("@mantine/notifications", () => ({
|
||||
notifications: { show: (...args: unknown[]) => notifyShow(...args) },
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (s: string) => s }),
|
||||
}));
|
||||
|
||||
import { useStreamingDictation } from "./use-streaming-dictation";
|
||||
|
||||
// jsdom has no AudioContext; the hook constructs one and calls resume(). A
|
||||
// trivial stub is enough — the real audio path is irrelevant to ordering.
|
||||
class FakeAudioContext {
|
||||
state = "running";
|
||||
resume() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
close() {
|
||||
this.state = "closed";
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
async function startRecording(onText: (t: string) => void) {
|
||||
const hook = renderHook(() => useStreamingDictation({ onText }));
|
||||
await act(async () => {
|
||||
await hook.result.current.start();
|
||||
});
|
||||
// The VAD registered its onSpeechEnd and start() resolved into "recording".
|
||||
expect(h.onSpeechEnd).toBeTypeOf("function");
|
||||
expect(hook.result.current.status).toBe("recording");
|
||||
return hook;
|
||||
}
|
||||
|
||||
// Fire N ended speech segments (seq 0..N-1), each kicking off one transcription.
|
||||
async function emitSegments(n: number) {
|
||||
await act(async () => {
|
||||
for (let i = 0; i < n; i++) h.onSpeechEnd!(new Float32Array(8));
|
||||
});
|
||||
}
|
||||
|
||||
describe("useStreamingDictation — in-order segment emitter", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
h.onSpeechEnd = null;
|
||||
h.pending = [];
|
||||
notifyShow.mockClear();
|
||||
(window as unknown as { AudioContext: unknown }).AudioContext =
|
||||
FakeAudioContext;
|
||||
});
|
||||
|
||||
it("emits transcriptions in segment order even when responses resolve out of order", async () => {
|
||||
const emitted: string[] = [];
|
||||
await startRecording((t) => emitted.push(t));
|
||||
await emitSegments(3);
|
||||
expect(h.pending).toHaveLength(3);
|
||||
|
||||
// Resolve seq 1 FIRST: it must be buffered, not emitted, because seq 0 is
|
||||
// still outstanding (nextEmit == 0).
|
||||
await act(async () => {
|
||||
h.pending[1].resolve("second");
|
||||
});
|
||||
expect(emitted).toEqual([]);
|
||||
|
||||
// Resolve seq 0: this unblocks the buffer and flushes 0 then 1 in order.
|
||||
await act(async () => {
|
||||
h.pending[0].resolve("first");
|
||||
});
|
||||
expect(emitted).toEqual(["first", "second"]);
|
||||
|
||||
// seq 2 resolves last and flushes immediately (it is now next).
|
||||
await act(async () => {
|
||||
h.pending[2].resolve("third");
|
||||
});
|
||||
expect(emitted).toEqual(["first", "second", "third"]);
|
||||
});
|
||||
|
||||
it("trims whitespace and drops empty/whitespace-only transcriptions while still advancing", async () => {
|
||||
const emitted: string[] = [];
|
||||
await startRecording((t) => emitted.push(t));
|
||||
await emitSegments(3);
|
||||
|
||||
await act(async () => {
|
||||
h.pending[0].resolve(" hello "); // leading/trailing space trimmed
|
||||
h.pending[1].resolve(" "); // whitespace-only -> not emitted, but seq advances
|
||||
h.pending[2].resolve("world");
|
||||
});
|
||||
|
||||
expect(emitted).toEqual(["hello", "world"]);
|
||||
});
|
||||
|
||||
it("a failed segment shows one notification and is skipped so later segments still flush in order", async () => {
|
||||
const emitted: string[] = [];
|
||||
await startRecording((t) => emitted.push(t));
|
||||
await emitSegments(2);
|
||||
|
||||
// seq 0 fails: the user sees a notification and the emitter advances past it.
|
||||
await act(async () => {
|
||||
h.pending[0].reject({ message: "boom" });
|
||||
});
|
||||
expect(notifyShow).toHaveBeenCalledTimes(1);
|
||||
expect(emitted).toEqual([]);
|
||||
|
||||
// seq 1 still flushes (it is now next), proving one failure did not stall.
|
||||
await act(async () => {
|
||||
h.pending[1].resolve("survivor");
|
||||
});
|
||||
expect(emitted).toEqual(["survivor"]);
|
||||
});
|
||||
|
||||
it("an OUT-OF-ORDER failed segment is buffered as empty and skipped without stalling later text", async () => {
|
||||
const emitted: string[] = [];
|
||||
await startRecording((t) => emitted.push(t));
|
||||
await emitSegments(3);
|
||||
|
||||
// seq 1 (NOT next-to-emit) fails first: it takes the else branch — an empty
|
||||
// placeholder is buffered (resultsRef.set(seq, "")) so the emitter can later
|
||||
// skip it. One notification, nothing emitted yet (seq 0 still gates).
|
||||
await act(async () => {
|
||||
h.pending[1].reject({ message: "boom" });
|
||||
});
|
||||
expect(notifyShow).toHaveBeenCalledTimes(1);
|
||||
expect(emitted).toEqual([]);
|
||||
|
||||
// seq 0 flushes; the drain then reaches the buffered empty seq 1 and SKIPS
|
||||
// past it to seq 2.
|
||||
await act(async () => {
|
||||
h.pending[0].resolve("alpha");
|
||||
});
|
||||
expect(emitted).toEqual(["alpha"]);
|
||||
|
||||
// seq 2 emits — proving the empty placeholder let the emitter advance past
|
||||
// the failed seq 1. Without the else branch's placeholder the drain would
|
||||
// stall at the missing seq 1 and "gamma" would never flush.
|
||||
await act(async () => {
|
||||
h.pending[2].resolve("gamma");
|
||||
});
|
||||
expect(emitted).toEqual(["alpha", "gamma"]);
|
||||
});
|
||||
|
||||
it("ignores a transcription that resolves AFTER cancel() (stale epoch — no emit)", async () => {
|
||||
const emitted: string[] = [];
|
||||
const hook = await startRecording((t) => emitted.push(t));
|
||||
await emitSegments(1);
|
||||
|
||||
// Hard discard the session: the in-flight request is now stale.
|
||||
act(() => {
|
||||
hook.result.current.cancel();
|
||||
});
|
||||
expect(hook.result.current.status).toBe("idle");
|
||||
|
||||
// Its late resolution must be dropped (no emit into the new/empty session).
|
||||
await act(async () => {
|
||||
h.pending[0].resolve("late");
|
||||
});
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Mock the page-service so importing the module under test does not pull in the
|
||||
// axios/api-client chain. `createMentionAction` is wired to `getPageById`; the
|
||||
// spy lets us assert that wiring without any network. `vi.hoisted` keeps the spy
|
||||
// available inside the hoisted vi.mock factory.
|
||||
const { getPageById } = vi.hoisted(() => ({ getPageById: vi.fn() }));
|
||||
vi.mock("@/features/page/services/page-service.ts", () => ({
|
||||
getPageById,
|
||||
}));
|
||||
|
||||
// `uuid` v7 is used for the mention node id; pin only v7 so assertions are
|
||||
// stable, keeping the rest (e.g. `validate`, used by extractPageSlugId) real.
|
||||
vi.mock("uuid", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("uuid")>()),
|
||||
v7: () => "fixed-mention-uuid",
|
||||
}));
|
||||
|
||||
import {
|
||||
handleInternalLink,
|
||||
createMentionAction,
|
||||
} from "./internal-link-paste";
|
||||
|
||||
// Minimal ProseMirror-ish EditorView fake. We record what handleInternalLink
|
||||
// builds and dispatches without standing up a real schema/state.
|
||||
function makeView() {
|
||||
const tr = {
|
||||
replaceWith: vi.fn(function (this: unknown) {
|
||||
return tr;
|
||||
}),
|
||||
insertText: vi.fn(function (this: unknown) {
|
||||
return tr;
|
||||
}),
|
||||
addMark: vi.fn(function (this: unknown) {
|
||||
return tr;
|
||||
}),
|
||||
};
|
||||
const schema = {
|
||||
nodes: {
|
||||
mention: {
|
||||
// Echo the attrs back so we can assert exactly what was created.
|
||||
create: vi.fn((attrs: Record<string, unknown>) => ({
|
||||
type: "mention",
|
||||
attrs,
|
||||
})),
|
||||
},
|
||||
},
|
||||
marks: {
|
||||
link: {
|
||||
create: vi.fn((attrs: Record<string, unknown>) => ({
|
||||
type: "link",
|
||||
attrs,
|
||||
})),
|
||||
},
|
||||
},
|
||||
};
|
||||
const view = {
|
||||
state: { schema, tr },
|
||||
dispatch: vi.fn(),
|
||||
};
|
||||
return { view, tr, schema };
|
||||
}
|
||||
|
||||
describe("handleInternalLink", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("does nothing when validateFn rejects the url (no resolve, no dispatch)", async () => {
|
||||
const onResolveLink = vi.fn();
|
||||
const validateFn = vi.fn(() => false);
|
||||
const { view } = makeView();
|
||||
|
||||
await handleInternalLink({ validateFn, onResolveLink })(
|
||||
"any-url",
|
||||
view as never,
|
||||
3,
|
||||
"creator-1",
|
||||
);
|
||||
|
||||
expect(validateFn).toHaveBeenCalledWith("any-url", view);
|
||||
expect(onResolveLink).not.toHaveBeenCalled();
|
||||
expect(view.dispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("on resolve: inserts a mention node carrying the resolved page + anchor and dispatches replaceWith at pos", async () => {
|
||||
const page = {
|
||||
id: "page-id-99",
|
||||
title: "My Page",
|
||||
slugId: "slugABC",
|
||||
};
|
||||
const onResolveLink = vi.fn().mockResolvedValue(page);
|
||||
const { view, tr, schema } = makeView();
|
||||
|
||||
// extractPageSlugId("doc-slug-xyz789") -> "xyz789" (last hyphen segment).
|
||||
await handleInternalLink({ validateFn: () => true, onResolveLink })(
|
||||
"doc-slug-xyz789",
|
||||
view as never,
|
||||
5,
|
||||
"creator-7",
|
||||
"anchor-42",
|
||||
);
|
||||
|
||||
// The linked page id is the extracted slug-id, not the whole url.
|
||||
expect(onResolveLink).toHaveBeenCalledWith("xyz789", "creator-7");
|
||||
expect(schema.nodes.mention.create).toHaveBeenCalledWith({
|
||||
id: "fixed-mention-uuid",
|
||||
label: "My Page",
|
||||
entityType: "page",
|
||||
entityId: "page-id-99",
|
||||
slugId: "slugABC",
|
||||
creatorId: "creator-7",
|
||||
anchorId: "anchor-42",
|
||||
});
|
||||
expect(tr.replaceWith).toHaveBeenCalledWith(5, 5, {
|
||||
type: "mention",
|
||||
attrs: expect.objectContaining({ entityId: "page-id-99" }),
|
||||
});
|
||||
expect(tr.insertText).not.toHaveBeenCalled();
|
||||
expect(view.dispatch).toHaveBeenCalledTimes(1);
|
||||
expect(view.dispatch).toHaveBeenCalledWith(tr);
|
||||
});
|
||||
|
||||
it("falls back to 'Untitled' label when the resolved page has no title", async () => {
|
||||
const onResolveLink = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: "p", title: "", slugId: "s" });
|
||||
const { view, schema } = makeView();
|
||||
|
||||
await handleInternalLink({ validateFn: () => true, onResolveLink })(
|
||||
"abc-id1",
|
||||
view as never,
|
||||
0,
|
||||
"c",
|
||||
);
|
||||
|
||||
expect(schema.nodes.mention.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ label: "Untitled" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("on reject: inserts the raw url as plain text with a link mark and dispatches", async () => {
|
||||
const onResolveLink = vi.fn().mockRejectedValue(new Error("not found"));
|
||||
const { view, tr, schema } = makeView();
|
||||
|
||||
await handleInternalLink({ validateFn: () => true, onResolveLink })(
|
||||
"http://x/page-id2",
|
||||
view as never,
|
||||
4,
|
||||
"creator-1",
|
||||
);
|
||||
|
||||
// No mention node on the failure path.
|
||||
expect(schema.nodes.mention.create).not.toHaveBeenCalled();
|
||||
expect(tr.insertText).toHaveBeenCalledWith("http://x/page-id2", 4);
|
||||
expect(schema.marks.link.create).toHaveBeenCalledWith({
|
||||
href: "http://x/page-id2",
|
||||
});
|
||||
// Mark spans exactly the inserted url text: [pos, pos + url.length].
|
||||
expect(tr.addMark).toHaveBeenCalledWith(4, 4 + "http://x/page-id2".length, {
|
||||
type: "link",
|
||||
attrs: { href: "http://x/page-id2" },
|
||||
});
|
||||
expect(view.dispatch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createMentionAction", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("resolves the link via getPageById and inserts the mention", async () => {
|
||||
getPageById.mockResolvedValue({
|
||||
id: "real-page",
|
||||
title: "Real",
|
||||
slugId: "rslug",
|
||||
});
|
||||
const { view, schema } = makeView();
|
||||
|
||||
await createMentionAction("ref-pageABC", view as never, 2, "creator-9");
|
||||
|
||||
expect(getPageById).toHaveBeenCalledWith({ pageId: "pageABC" });
|
||||
expect(schema.nodes.mention.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityId: "real-page", label: "Real" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("propagates a getPageById failure to the plain-link fallback", async () => {
|
||||
getPageById.mockRejectedValue(new Error("404"));
|
||||
const { view, tr } = makeView();
|
||||
|
||||
await createMentionAction("ref-pageABC", view as never, 1, "creator-9");
|
||||
|
||||
// Failure path: the url is inserted as text, not as a mention node.
|
||||
expect(tr.insertText).toHaveBeenCalledWith("ref-pageABC", 1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { useScrollPosition } from "./use-scroll-position";
|
||||
|
||||
const KEY_PREFIX = "gitmost:scroll-position:";
|
||||
|
||||
function setScrollY(value: number): void {
|
||||
Object.defineProperty(window, "scrollY", {
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
function setScrollHeight(value: number): void {
|
||||
Object.defineProperty(document.documentElement, "scrollHeight", {
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
function setInnerHeight(value: number): void {
|
||||
Object.defineProperty(window, "innerHeight", {
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
describe("useScrollPosition", () => {
|
||||
beforeEach(() => {
|
||||
window.sessionStorage.clear();
|
||||
setScrollY(0);
|
||||
setScrollHeight(0);
|
||||
setInnerHeight(800);
|
||||
// jsdom does not implement window.scrollTo; stub it.
|
||||
window.scrollTo = vi.fn();
|
||||
// Ensure no anchor leaks between tests.
|
||||
window.location.hash = "";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
window.location.hash = "";
|
||||
});
|
||||
|
||||
it("(a) saves window.scrollY to sessionStorage under the pageId key, throttled", () => {
|
||||
vi.useFakeTimers();
|
||||
const { unmount } = renderHook(() => useScrollPosition("p1"));
|
||||
|
||||
// Leading-edge save fires immediately.
|
||||
setScrollY(123);
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
expect(window.sessionStorage.getItem(`${KEY_PREFIX}p1`)).toBe("123");
|
||||
|
||||
// Within the throttle window the next scroll is suppressed.
|
||||
setScrollY(456);
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
expect(window.sessionStorage.getItem(`${KEY_PREFIX}p1`)).toBe("123");
|
||||
|
||||
// After the throttle window elapses, the next scroll persists again.
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(250);
|
||||
});
|
||||
setScrollY(789);
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
expect(window.sessionStorage.getItem(`${KEY_PREFIX}p1`)).toBe("789");
|
||||
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("(a2) the restore target is captured at mount and survives a fresh scroll@0 clobber", () => {
|
||||
vi.useFakeTimers();
|
||||
// A previous session saved 500.
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}clob`, "500");
|
||||
|
||||
const { result } = renderHook(() => useScrollPosition("clob"));
|
||||
|
||||
// On load the page is at the top; a scroll@0 fires and overwrites storage
|
||||
// with 0. This is exactly the clobber the synchronous mount-capture defends
|
||||
// against: the stored value becomes "0", but the target was already captured.
|
||||
setScrollY(0);
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
});
|
||||
expect(window.sessionStorage.getItem(`${KEY_PREFIX}clob`)).toBe("0");
|
||||
|
||||
// Restore still scrolls to 500 (the captured target), NOT the clobbered 0.
|
||||
// If the capture were moved into an effect (after handlers register), it
|
||||
// would read the clobbered 0 and this assertion would fail.
|
||||
setScrollHeight(2000); // maxScroll = 1200 >= 500
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
||||
});
|
||||
|
||||
it("(a3) restores at most once per mount even if called again", () => {
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}once`, "500");
|
||||
setScrollHeight(2000); // tall enough to restore synchronously
|
||||
|
||||
const { result } = renderHook(() => useScrollPosition("once"));
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A second call (e.g. the wiring effect re-running on [showStatic, editor,
|
||||
// restoreScrollPosition]) must NOT scroll again and yank the reader.
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("(b) does not restore when the URL has a #hash anchor", () => {
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}p2`, "500");
|
||||
// Content is ALREADY tall enough (maxScroll = 2000 - 800 = 1200 >= 500), so
|
||||
// without the hash guard tryRestore would call scrollTo synchronously on the
|
||||
// first tick. The assertion below therefore genuinely proves the hash guard
|
||||
// short-circuits before any scroll (not just that the poll has not fired).
|
||||
setScrollHeight(2000);
|
||||
window.location.hash = "#some-heading";
|
||||
|
||||
const { result } = renderHook(() => useScrollPosition("p2"));
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
|
||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("(f) cancels the in-flight restore poll on unmount (no scroll on the next page)", () => {
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}p7`, "500");
|
||||
setInnerHeight(800);
|
||||
setScrollHeight(100); // maxScroll = -700: target not reachable yet, so it polls.
|
||||
|
||||
const { result, unmount } = renderHook(() => useScrollPosition("p7"));
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).not.toHaveBeenCalled(); // still polling
|
||||
|
||||
// Navigate away (the hook unmounts) BEFORE the content grows tall enough.
|
||||
unmount();
|
||||
|
||||
// Content of the NEXT page becomes tall; advancing time must NOT resurrect
|
||||
// the cancelled poll (without the cleanup it would scroll the new page).
|
||||
setScrollHeight(2000);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("(c) does nothing when nothing is saved or the saved value is <= 0", () => {
|
||||
// Nothing saved.
|
||||
const a = renderHook(() => useScrollPosition("nope"));
|
||||
act(() => {
|
||||
a.result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||
|
||||
// Saved value <= 0.
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}zero`, "0");
|
||||
const b = renderHook(() => useScrollPosition("zero"));
|
||||
act(() => {
|
||||
b.result.current.restoreScrollPosition();
|
||||
});
|
||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("(d) scrolls to the saved Y once the content is tall enough", () => {
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}p4`, "500");
|
||||
setInnerHeight(800);
|
||||
setScrollHeight(100); // maxScroll = -700, target not yet reachable.
|
||||
|
||||
const { result } = renderHook(() => useScrollPosition("p4"));
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
|
||||
// Still polling: content not laid out yet.
|
||||
expect(window.scrollTo).not.toHaveBeenCalled();
|
||||
|
||||
// Content becomes tall enough: maxScroll = 2000 - 800 = 1200 >= 500.
|
||||
setScrollHeight(2000);
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(100);
|
||||
});
|
||||
|
||||
expect(window.scrollTo).toHaveBeenCalledWith({ top: 500, behavior: "auto" });
|
||||
});
|
||||
|
||||
it("(d2) clamps to the max reachable position after the timeout", () => {
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.setItem(`${KEY_PREFIX}p5`, "5000");
|
||||
setInnerHeight(800);
|
||||
setScrollHeight(1000); // maxScroll stays 200, never reaches 5000.
|
||||
|
||||
const { result } = renderHook(() => useScrollPosition("p5"));
|
||||
act(() => {
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
|
||||
// Advance past the 5s timeout; restore should fire clamped to maxScroll.
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(5000);
|
||||
});
|
||||
|
||||
expect(window.scrollTo).toHaveBeenCalledWith({ top: 200, behavior: "auto" });
|
||||
});
|
||||
|
||||
it("(e) never throws when storage access throws", () => {
|
||||
const err = new Error("storage denied");
|
||||
vi.spyOn(window.sessionStorage, "getItem").mockImplementation(() => {
|
||||
throw err;
|
||||
});
|
||||
vi.spyOn(window.sessionStorage, "setItem").mockImplementation(() => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
expect(() => {
|
||||
const { result, unmount } = renderHook(() => useScrollPosition("p6"));
|
||||
act(() => {
|
||||
setScrollY(42);
|
||||
window.dispatchEvent(new Event("scroll"));
|
||||
result.current.restoreScrollPosition();
|
||||
});
|
||||
unmount();
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
177
apps/client/src/features/editor/hooks/use-scroll-position.ts
Normal file
177
apps/client/src/features/editor/hooks/use-scroll-position.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
// Throttle interval for persisting the scroll position while the user reads.
|
||||
const SAVE_THROTTLE_MS = 250;
|
||||
// Give up polling for the live content height after this long and restore to
|
||||
// the furthest reachable position (handles "collab never finishes laying out").
|
||||
const MAX_RESTORE_WAIT_MS = 5000;
|
||||
// How often to re-check the document height while waiting for content to load.
|
||||
const RESTORE_POLL_MS = 100;
|
||||
|
||||
// sessionStorage key prefix. sessionStorage survives an F5 in the same tab and
|
||||
// is cleared on tab close, which is exactly the lifetime we want for an MVP
|
||||
// "remember where I was reading" feature (self-limiting, no cross-tab leak).
|
||||
const STORAGE_PREFIX = "gitmost:scroll-position:";
|
||||
|
||||
function storageKey(pageId: string): string {
|
||||
return `${STORAGE_PREFIX}${pageId}`;
|
||||
}
|
||||
|
||||
// All storage access is wrapped: private mode / quota / disabled storage must
|
||||
// never throw out of the hook and break the page.
|
||||
function readStorage(pageId: string): number | null {
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(storageKey(pageId));
|
||||
if (raw === null) return null;
|
||||
const value = Number.parseInt(raw, 10);
|
||||
return Number.isFinite(value) ? value : null;
|
||||
} catch (err) {
|
||||
// Best-effort feature: storage may be unavailable (private mode / quota).
|
||||
// No user-facing notification (a missed scroll restore is not actionable),
|
||||
// but log per the AGENTS.md "errors must never be swallowed" rule.
|
||||
console.warn("[useScrollPosition] sessionStorage read failed", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStorage(pageId: string, scrollY: number): void {
|
||||
try {
|
||||
window.sessionStorage.setItem(storageKey(pageId), String(Math.round(scrollY)));
|
||||
} catch (err) {
|
||||
// Storage unavailable (private mode / quota). Non-actionable for the user,
|
||||
// but log it rather than swallow silently (AGENTS.md error-handling rule).
|
||||
console.warn("[useScrollPosition] sessionStorage write failed", err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists and restores the window scroll position per page so a reader keeps
|
||||
* their place across a reload (F5) or reopening the document.
|
||||
*
|
||||
* Returns `restoreScrollPosition`, which the page editor calls once the live
|
||||
* (non-static) content is laid out. The two scroll mechanisms are mutually
|
||||
* exclusive: if the URL has a `#hash` anchor, the existing anchor-scroll logic
|
||||
* wins and restore is a no-op.
|
||||
*/
|
||||
export function useScrollPosition(pageId: string): {
|
||||
restoreScrollPosition: () => void;
|
||||
} {
|
||||
// CONTRACT: this hook assumes PageEditor REMOUNTS per page — page.tsx renders
|
||||
// `<MemoizedFullEditor key={page.id} ...>`, so switching pages creates a fresh
|
||||
// hook instance with fresh refs. These refs latch per-mount and are NOT reset
|
||||
// when `pageId` changes in place (only the effect re-runs on [pageId]). If that
|
||||
// `key={page.id}` is ever removed, restore would silently break on the 2nd page
|
||||
// (refs would hold the first page's target / already-restored flag) — in that
|
||||
// case the refs must be reset on a pageId change.
|
||||
//
|
||||
// The target Y captured synchronously at mount, BEFORE any scroll/visibility
|
||||
// handler can overwrite the stored value with a fresh 0 (the page starts
|
||||
// scrolled to top on load). `null` means "not yet captured".
|
||||
const initialTargetRef = useRef<number | null>(null);
|
||||
// Guards so restore runs at most once per page mount.
|
||||
const hasRestoredRef = useRef(false);
|
||||
// Holds the in-flight restore poll timer so the cleanup can cancel it: without
|
||||
// this, a fast SPA navigation away mid-poll would let the old page's poll fire
|
||||
// window.scrollTo against the NEW page's document (visible wrong-page scroll).
|
||||
const pollTimerRef = useRef<number | null>(null);
|
||||
|
||||
// Capture the previously-saved value synchronously during render, before the
|
||||
// effect below registers handlers that would persist the current (0) scrollY.
|
||||
if (initialTargetRef.current === null) {
|
||||
const saved = readStorage(pageId);
|
||||
// Store 0 when nothing is saved so the "already captured" check (!== null)
|
||||
// holds; restore treats targetY <= 0 as a no-op anyway.
|
||||
initialTargetRef.current = saved ?? 0;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
let throttleTimer: number | null = null;
|
||||
|
||||
const save = () => {
|
||||
writeStorage(pageId, window.scrollY);
|
||||
};
|
||||
|
||||
// Throttle the high-frequency scroll handler: persist immediately on the
|
||||
// leading edge, then at most once per SAVE_THROTTLE_MS.
|
||||
const onScroll = () => {
|
||||
if (throttleTimer !== null) return;
|
||||
save();
|
||||
throttleTimer = window.setTimeout(() => {
|
||||
throttleTimer = null;
|
||||
}, SAVE_THROTTLE_MS);
|
||||
};
|
||||
|
||||
// pagehide fires on reload/navigation (more reliable than unload); save now.
|
||||
const onPageHide = () => {
|
||||
save();
|
||||
};
|
||||
|
||||
// Save when the tab is being backgrounded — covers mobile where pagehide is
|
||||
// not always emitted.
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
save();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", onScroll, { passive: true });
|
||||
window.addEventListener("pagehide", onPageHide);
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("scroll", onScroll);
|
||||
window.removeEventListener("pagehide", onPageHide);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
if (throttleTimer !== null) {
|
||||
window.clearTimeout(throttleTimer);
|
||||
throttleTimer = null;
|
||||
}
|
||||
// Cancel any in-flight restore poll so it cannot scroll the next page.
|
||||
if (pollTimerRef.current !== null) {
|
||||
window.clearTimeout(pollTimerRef.current);
|
||||
pollTimerRef.current = null;
|
||||
}
|
||||
// SPA navigation away from this page: persist the final position.
|
||||
save();
|
||||
};
|
||||
}, [pageId]);
|
||||
|
||||
const restoreScrollPosition = useCallback(() => {
|
||||
// Run at most once per page mount.
|
||||
if (hasRestoredRef.current) return;
|
||||
hasRestoredRef.current = true;
|
||||
|
||||
// Anchor priority: a `#hash` in the URL is handled by useEditorScroll.
|
||||
if (window.location.hash) return;
|
||||
|
||||
const targetY = initialTargetRef.current ?? 0;
|
||||
// Nothing meaningful to restore to.
|
||||
if (targetY <= 0) return;
|
||||
|
||||
const start = Date.now();
|
||||
|
||||
const tryRestore = () => {
|
||||
const maxScroll =
|
||||
document.documentElement.scrollHeight - window.innerHeight;
|
||||
const timedOut = Date.now() - start >= MAX_RESTORE_WAIT_MS;
|
||||
|
||||
// Restore once the content is tall enough to reach the target, or bail out
|
||||
// after the timeout and scroll as far as currently possible.
|
||||
if (maxScroll >= targetY || timedOut) {
|
||||
window.scrollTo({
|
||||
top: Math.min(targetY, Math.max(maxScroll, 0)),
|
||||
behavior: "auto",
|
||||
});
|
||||
pollTimerRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Stored in a ref so the effect cleanup can cancel it on unmount.
|
||||
pollTimerRef.current = window.setTimeout(tryRestore, RESTORE_POLL_MS);
|
||||
};
|
||||
|
||||
tryRestore();
|
||||
}, []);
|
||||
|
||||
return { restoreScrollPosition };
|
||||
}
|
||||
@@ -77,6 +77,7 @@ import { PageEditMode } from "@/features/user/types/user.types.ts";
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
import { searchSpotlight } from "@/features/search/constants.ts";
|
||||
import { useEditorScroll } from "./hooks/use-editor-scroll";
|
||||
import { useScrollPosition } from "./hooks/use-scroll-position";
|
||||
import { EditorLinkMenu } from "@/features/editor/components/link/link-menu";
|
||||
import ColumnsMenu from "@/features/editor/components/columns/columns-menu.tsx";
|
||||
import { TransclusionLookupProvider } from "@/features/editor/components/transclusion/transclusion-lookup-context";
|
||||
@@ -141,6 +142,7 @@ export default function PageEditor({
|
||||
[isComponentMounted],
|
||||
);
|
||||
const { handleScrollTo } = useEditorScroll({ canScroll });
|
||||
const { restoreScrollPosition } = useScrollPosition(pageId);
|
||||
// Providers only created once per pageId
|
||||
const providersRef = useRef<{
|
||||
local: IndexeddbPersistence;
|
||||
@@ -479,6 +481,11 @@ export default function PageEditor({
|
||||
}
|
||||
}, [yjsConnectionStatus, isSynced]);
|
||||
|
||||
// Restore the saved reading position once the live content is laid out.
|
||||
useEffect(() => {
|
||||
if (!showStatic && editor) restoreScrollPosition();
|
||||
}, [showStatic, editor, restoreScrollPosition]);
|
||||
|
||||
return (
|
||||
<TransclusionLookupProvider>
|
||||
<PageEmbedLookupProvider>
|
||||
|
||||
@@ -77,7 +77,9 @@ describe('resolveKeyField (write-only key payload)', () => {
|
||||
|
||||
describe('nextReindexPollInterval', () => {
|
||||
const INTERVAL = 5000;
|
||||
const base = { now: 1_000, intervalMs: INTERVAL };
|
||||
// `seenActive: true` is the steady state for most of a run — a poll has
|
||||
// observed `reindexing === true` (the server pre-seeds it from enqueue time).
|
||||
const base = { now: 1_000, intervalMs: INTERVAL, seenActive: true };
|
||||
|
||||
it('does not poll when no reindex deadline is set', () => {
|
||||
expect(
|
||||
@@ -111,7 +113,7 @@ describe('nextReindexPollInterval', () => {
|
||||
).toBe(INTERVAL);
|
||||
});
|
||||
|
||||
it('stops once the run is finished AND fully indexed', () => {
|
||||
it('stops once the run is finished AND fully indexed (after having been active)', () => {
|
||||
expect(
|
||||
nextReindexPollInterval({
|
||||
...base,
|
||||
@@ -121,11 +123,29 @@ describe('nextReindexPollInterval', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT stop on the stale pre-reindex snapshot (fully indexed, never seen active)', () => {
|
||||
// Regression for #262: right after "Reindex now" the client still holds the
|
||||
// PRE-reindex settings (an already fully-indexed workspace reads as
|
||||
// reindexing=false, indexed>=total). Without the seenActive gate this looked
|
||||
// "done" and stopped polling on the very first tick, freezing the counter at
|
||||
// 0 until a manual reload. The fresh window has not observed the active run,
|
||||
// so polling must continue until the first real poll lands.
|
||||
expect(
|
||||
nextReindexPollInterval({
|
||||
...base,
|
||||
seenActive: false,
|
||||
deadline: 10_000,
|
||||
status: { reindexing: false, indexedPages: 478, totalPages: 478 },
|
||||
}),
|
||||
).toBe(INTERVAL);
|
||||
});
|
||||
|
||||
it('keeps polling within the deadline when not yet done and no active flag', () => {
|
||||
// First poll right after enqueue, before the worker publishes progress.
|
||||
expect(
|
||||
nextReindexPollInterval({
|
||||
...base,
|
||||
seenActive: false,
|
||||
deadline: 10_000,
|
||||
status: { reindexing: false, indexedPages: 0, totalPages: 478 },
|
||||
}),
|
||||
@@ -138,12 +158,15 @@ describe('nextReindexPollInterval', () => {
|
||||
deadline: 1_000,
|
||||
now: 2_000, // past the deadline
|
||||
intervalMs: INTERVAL,
|
||||
seenActive: true,
|
||||
status: { reindexing: true, indexedPages: 200, totalPages: 478 },
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('stops on an empty workspace (0 of 0) once the run is finished', () => {
|
||||
// The pre-seed publishes reindexing=true even for 0 pages, so a poll sees the
|
||||
// run active before the worker clears -> seenActive latches true.
|
||||
expect(
|
||||
nextReindexPollInterval({
|
||||
...base,
|
||||
@@ -156,26 +179,46 @@ describe('nextReindexPollInterval', () => {
|
||||
|
||||
describe('isReindexComplete', () => {
|
||||
it('false when no status yet', () => {
|
||||
expect(isReindexComplete(undefined)).toBe(false);
|
||||
expect(isReindexComplete(undefined, true)).toBe(false);
|
||||
});
|
||||
|
||||
it('false while a run is still active (even at indexed==total)', () => {
|
||||
expect(
|
||||
isReindexComplete({ reindexing: true, indexedPages: 478, totalPages: 478 }),
|
||||
isReindexComplete(
|
||||
{ reindexing: true, indexedPages: 478, totalPages: 478 },
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('false when finished but not yet fully indexed', () => {
|
||||
expect(
|
||||
isReindexComplete({ reindexing: false, indexedPages: 120, totalPages: 478 }),
|
||||
isReindexComplete(
|
||||
{ reindexing: false, indexedPages: 120, totalPages: 478 },
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('true once finished and fully indexed', () => {
|
||||
it('true once finished and fully indexed (after having been active)', () => {
|
||||
expect(
|
||||
isReindexComplete({ reindexing: false, indexedPages: 478, totalPages: 478 }),
|
||||
isReindexComplete(
|
||||
{ reindexing: false, indexedPages: 478, totalPages: 478 },
|
||||
true,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('false on the stale pre-reindex snapshot: finished+fully indexed but never seen active', () => {
|
||||
// The just-started edge: the gate keeps this from clearing the poll deadline
|
||||
// before the first post-reindex poll arrives.
|
||||
expect(
|
||||
isReindexComplete(
|
||||
{ reindexing: false, indexedPages: 478, totalPages: 478 },
|
||||
false,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReindexButtonLoading', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { z } from "zod/v4";
|
||||
import {
|
||||
ActionIcon,
|
||||
@@ -185,14 +185,23 @@ type ReindexStatus = Pick<
|
||||
* has finished AND everything is indexed (server cleared its progress record and
|
||||
* fell back to the DB coverage count), or the deadline cap is hit — the cap
|
||||
* always wins so a stuck/never-clearing progress record can't poll forever.
|
||||
*
|
||||
* `seenActive` guards the just-started window: right after "Reindex now" the
|
||||
* client still holds the PRE-reindex settings snapshot, which for an already
|
||||
* fully-indexed workspace reads as `reindexing=false, indexed>=total`. Treating
|
||||
* that stale snapshot as "done" would stop polling before the first post-reindex
|
||||
* poll ever lands (counter frozen at 0). So completion is only honored once a
|
||||
* poll has actually observed the active run (the enqueue-time pre-seed makes
|
||||
* `reindexing=true` visible from the first poll until the run truly clears).
|
||||
*/
|
||||
export function nextReindexPollInterval(args: {
|
||||
deadline: number | null;
|
||||
now: number;
|
||||
intervalMs: number;
|
||||
status?: ReindexStatus;
|
||||
seenActive: boolean;
|
||||
}): number | false {
|
||||
const { deadline, now, intervalMs, status } = args;
|
||||
const { deadline, now, intervalMs, status, seenActive } = args;
|
||||
if (deadline === null) return false;
|
||||
// Cap always wins.
|
||||
if (now > deadline) return false;
|
||||
@@ -200,20 +209,33 @@ export function nextReindexPollInterval(args: {
|
||||
if (status?.reindexing) return intervalMs;
|
||||
// Finished and fully indexed (incl. an empty workspace, 0 >= 0) → stop. Reuse
|
||||
// isReindexComplete so the completeness check lives in exactly one place.
|
||||
if (isReindexComplete(status)) return false;
|
||||
if (isReindexComplete(status, seenActive)) return false;
|
||||
// Within the deadline and not yet done → keep polling.
|
||||
return intervalMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the reindex poll deadline should be cleared: the server reports no
|
||||
* active run AND the count is complete. The single source of truth for the
|
||||
* "reindex finished" check — `nextReindexPollInterval` reuses it for its stop
|
||||
* condition (sans the cap, which the effect handles via time).
|
||||
* Whether the reindex poll deadline should be cleared: a poll has observed the
|
||||
* active run (`seenActive`) AND the server now reports no active run AND the
|
||||
* count is complete. The single source of truth for the "reindex finished"
|
||||
* check — `nextReindexPollInterval` reuses it for its stop condition (sans the
|
||||
* cap, which the effect handles via time).
|
||||
*
|
||||
* The `seenActive` requirement is what keeps the STALE pre-reindex snapshot
|
||||
* (already fully indexed → `reindexing=false, indexed>=total`) from being read
|
||||
* as "finished" in the window before the first post-reindex poll arrives. Once
|
||||
* a poll has seen `reindexing=true` (guaranteed by the server's enqueue-time
|
||||
* pre-seed for the whole run), this flips to a genuine completion check.
|
||||
*/
|
||||
export function isReindexComplete(status?: ReindexStatus): boolean {
|
||||
export function isReindexComplete(
|
||||
status: ReindexStatus | undefined,
|
||||
seenActive: boolean,
|
||||
): boolean {
|
||||
return (
|
||||
!!status && !status.reindexing && status.indexedPages >= status.totalPages
|
||||
seenActive &&
|
||||
!!status &&
|
||||
!status.reindexing &&
|
||||
status.indexedPages >= status.totalPages
|
||||
);
|
||||
}
|
||||
|
||||
@@ -290,6 +312,14 @@ export default function AiProviderSettings() {
|
||||
const REINDEX_POLL_INTERVAL = 5000; // ms between refetches while indexing
|
||||
const REINDEX_POLL_CAP_MS = 120000; // ~2 min hard cap
|
||||
const [reindexDeadline, setReindexDeadline] = useState<number | null>(null);
|
||||
// Whether any poll in the CURRENT window has actually observed the active run
|
||||
// (`reindexing === true`). Reset when a new reindex is kicked off. Gates the
|
||||
// completion check so the STALE pre-reindex snapshot (an already fully-indexed
|
||||
// workspace reads as `reindexing=false, indexed>=total`) can't be mistaken for
|
||||
// "finished" before the first post-reindex poll lands — which would freeze the
|
||||
// counter at 0 until a manual reload. A ref (not state) because it must not
|
||||
// trigger a render and is only ever read where `reindexing` is already false.
|
||||
const reindexSeenActiveRef = useRef(false);
|
||||
|
||||
// Only admins may read the (masked) AI settings; the server enforces this too.
|
||||
const { data: settings, isLoading } = useAiSettingsQuery(isAdmin, (query) =>
|
||||
@@ -298,6 +328,7 @@ export default function AiProviderSettings() {
|
||||
now: Date.now(),
|
||||
intervalMs: REINDEX_POLL_INTERVAL,
|
||||
status: query.state.data,
|
||||
seenActive: reindexSeenActiveRef.current,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -305,12 +336,17 @@ export default function AiProviderSettings() {
|
||||
// unmount because the deadline state goes away with the component.
|
||||
useEffect(() => {
|
||||
if (reindexDeadline === null) return;
|
||||
// "Done" matches the refetchInterval stop condition: the server reports no
|
||||
// active run AND the count is complete (indexed >= total, incl. an empty
|
||||
// workspace 0 >= 0), so the deadline clears promptly instead of waiting out
|
||||
// the cap. While `reindexing` is still true we keep the deadline so polling
|
||||
// continues for the whole run.
|
||||
if (isReindexComplete(settings)) {
|
||||
// Latch "we have seen the active run" the moment a poll reports it, so the
|
||||
// completion check below (and the refetchInterval's) only fires once the run
|
||||
// has genuinely started — never on the stale pre-reindex snapshot.
|
||||
if (settings?.reindexing) reindexSeenActiveRef.current = true;
|
||||
// "Done" matches the refetchInterval stop condition: a poll has observed the
|
||||
// active run AND the server now reports no active run AND the count is
|
||||
// complete (indexed >= total, incl. an empty workspace 0 >= 0), so the
|
||||
// deadline clears promptly instead of waiting out the cap. While `reindexing`
|
||||
// is still true (or no poll has seen it active yet) we keep the deadline so
|
||||
// polling continues for the whole run.
|
||||
if (isReindexComplete(settings, reindexSeenActiveRef.current)) {
|
||||
setReindexDeadline(null);
|
||||
return;
|
||||
}
|
||||
@@ -1117,8 +1153,13 @@ export default function AiProviderSettings() {
|
||||
reindexMutation.mutate(undefined, {
|
||||
// Begin bounded polling so the counter climbs as the async
|
||||
// background job indexes (it does not update on its own).
|
||||
onSuccess: () =>
|
||||
setReindexDeadline(Date.now() + REINDEX_POLL_CAP_MS),
|
||||
// Clear the "seen active" latch first so this fresh window
|
||||
// doesn't inherit a previous run's completion state and stop
|
||||
// immediately.
|
||||
onSuccess: () => {
|
||||
reindexSeenActiveRef.current = false;
|
||||
setReindexDeadline(Date.now() + REINDEX_POLL_CAP_MS);
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
135
docs/dev-stand.md
Normal file
135
docs/dev-stand.md
Normal file
@@ -0,0 +1,135 @@
|
||||
# Running a local dev stand
|
||||
|
||||
How to bring up a working local instance (API + client + realtime collaboration)
|
||||
and the non-obvious gotchas that will otherwise eat an hour. Written from real
|
||||
setup pain — read the **Gotchas** section before you start.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Node 20+ / pnpm 10+.**
|
||||
- **Postgres with pgvector.** Use the `pgvector/pgvector` image (e.g.
|
||||
`pgvector/pgvector:pg18`). The stock `postgres` image will FAIL the
|
||||
`CREATE EXTENSION vector` migration — the RAG feature stores embeddings in
|
||||
`page_embeddings`.
|
||||
- **Redis** — backs caching, BullMQ queues, the Socket.IO adapter, and collab
|
||||
sync.
|
||||
|
||||
## 1. Environment (`.env`)
|
||||
|
||||
The client (`apps/client/vite.config.ts`) and both server processes read env via
|
||||
`envPath` → the **workspace root `.env`**. Keep a single source of truth. Minimum:
|
||||
|
||||
```dotenv
|
||||
APP_URL=http://localhost:3000
|
||||
PORT=3000
|
||||
APP_SECRET=<one long secret — SAME value everywhere, see gotcha #3>
|
||||
DATABASE_URL="postgresql://<user>:<pass>@localhost:5432/<db>?schema=public"
|
||||
REDIS_URL=redis://127.0.0.1:6379
|
||||
COLLAB_URL=http://localhost:3001 # where the CLIENT connects for realtime
|
||||
COLLAB_PORT=3001 # where the COLLAB server listens
|
||||
STORAGE_DRIVER=local
|
||||
DISABLE_TELEMETRY=true
|
||||
```
|
||||
|
||||
> If you also keep an `apps/server/.env`, its `APP_SECRET` **must match** the
|
||||
> root one (see gotcha #3).
|
||||
|
||||
## 2. Migrations
|
||||
|
||||
Migrations do **not** auto-run in local dev. After a fresh checkout or switching
|
||||
branches, apply them yourself or endpoints touching a new column/table will 500:
|
||||
|
||||
```bash
|
||||
pnpm --filter server migration:latest
|
||||
```
|
||||
|
||||
## 3. Bring it up — THREE processes, not two
|
||||
|
||||
`pnpm dev` starts only the **API server** (Nest, `:3000`) and the **client**
|
||||
(Vite). Realtime collaboration is a **separate process** and `pnpm dev` does NOT
|
||||
start it. You need all three:
|
||||
|
||||
```bash
|
||||
# 1) API + client (from the repo root)
|
||||
pnpm dev
|
||||
# → API http://localhost:3000
|
||||
# → client http://localhost:5173 (Vite; localhost-only by default)
|
||||
|
||||
# 2) Collaboration server — SEPARATE process. Build first (see gotcha #2), then:
|
||||
pnpm --filter server build # produces dist/collaboration/server/collab-main.js
|
||||
pnpm collab:dev # node dist/.../collab-main → listens on :3001 (0.0.0.0)
|
||||
```
|
||||
|
||||
Without step 2 the editor shows **"Real-time editor connection lost. Retrying…"**,
|
||||
stays in read-only *static* mode, and anything that only mounts in the *live*
|
||||
editor won't appear.
|
||||
|
||||
## Seeding a login
|
||||
|
||||
Register through the UI, or reset an existing user's password directly in the DB
|
||||
(the server hashes with `bcrypt`):
|
||||
|
||||
```js
|
||||
// node -e '...' with pg + bcrypt from the repo's node_modules
|
||||
const bcrypt = require("bcrypt");
|
||||
const { Client } = require("pg");
|
||||
(async () => {
|
||||
const hash = await bcrypt.hash("demopass", 10);
|
||||
const c = new Client({ /* DATABASE_URL parts */ });
|
||||
await c.connect();
|
||||
await c.query("update users set password=$1 where email=$2", [hash, "admin@example.com"]);
|
||||
await c.end();
|
||||
})();
|
||||
```
|
||||
|
||||
> **Use a simple one-word password with no special characters** (e.g. `demopass`,
|
||||
> not `Str0ng!Pass@2026`). Demo/test credentials get passed through shells, JSON
|
||||
> payloads, and URLs by scripts and automation, where `!` `@` `$` `&` etc. get
|
||||
> mangled or need escaping — a plain alphanumeric word avoids a whole class of
|
||||
> "wrong password" confusion.
|
||||
|
||||
## Gotchas (the грабли)
|
||||
|
||||
1. **Collaboration is a third process.** `pnpm dev` runs API + client only.
|
||||
Start `pnpm collab:dev` (on `:3001`) separately or the live editor never
|
||||
connects. The client connects to `COLLAB_URL` directly (default
|
||||
`http://localhost:3001`), NOT through the Vite `/collab` proxy — the API
|
||||
server on `:3000` does **not** serve the collab websocket.
|
||||
|
||||
2. **The collab server must be built — you can't run it from source.**
|
||||
`collab:dev` runs `node dist/collaboration/server/collab-main.js`, so run
|
||||
`pnpm --filter server build` first. Running the entry via `tsx`/`ts-node`
|
||||
fails with a NestJS DI error ("dependency … appears to be undefined at
|
||||
runtime") because direct TS execution doesn't emit the decorator metadata the
|
||||
built output has.
|
||||
|
||||
3. **`APP_SECRET` must be identical for the API server and the collab server.**
|
||||
The API issues a collab-token (JWT signed with `APP_SECRET`); the collab
|
||||
server validates it with `APP_SECRET`. If they load different values (e.g. a
|
||||
root `.env` and an `apps/server/.env` with different secrets), every realtime
|
||||
connection is rejected with **`[onAuthenticate] Invalid collab token`** and
|
||||
the editor shows "connection lost". Keep one secret everywhere.
|
||||
|
||||
4. **Vite binds localhost only.** To reach the stand from another machine on the
|
||||
LAN, start the client with `--host` (`pnpm --filter client exec vite --host`)
|
||||
and use the box's LAN IP. The `/api`, `/socket.io`, and `/collab` Vite proxies
|
||||
forward to `APP_URL`, so the API just works over the LAN; realtime needs
|
||||
`COLLAB_URL` reachable from the browser (point it at the LAN IP:3001, and run
|
||||
collab on `0.0.0.0` — it does by default).
|
||||
|
||||
5. **A stale `@docmost/editor-ext` white-screens the client.** The client imports
|
||||
from `@docmost/editor-ext` (a workspace package). If that package's source is
|
||||
behind (missing a newer export, e.g. `Spoiler`), the client dies at load with
|
||||
*"The requested module … does not provide an export named 'Spoiler'"* → blank
|
||||
page. Make sure the workspace `packages/editor-ext` is current for the branch
|
||||
you're running (a stale sibling checkout resolved through a shared
|
||||
`node_modules` symlink is the usual cause).
|
||||
|
||||
6. **pgvector, not stock postgres** (see Prerequisites) — the `vector` extension
|
||||
migration fails otherwise.
|
||||
|
||||
7. **Migrations don't auto-run in dev** — run `migration:latest` after every pull
|
||||
or branch switch.
|
||||
|
||||
See also the **Commands** and **Architecture → Two server processes** sections in
|
||||
[`AGENTS.md`](../AGENTS.md).
|
||||
Reference in New Issue
Block a user