perf: Faster mention suggestions (#14583)

* perf: Faster mention suggestions

Limit each section of suggestions.mention to 1s so a slow query does not
delay the others, debounce mention and link editor requests, ignore stale
responses, and use title search in the link editor.

* fix: Include presentation in the mention suggestion time limits

* test: Use a fixed name in the collection member name filter test
This commit is contained in:
Tom Moor authored and GitHub committed 2026-11-13 22:37:49 -05:00
1 parent 4fd9b60400
commit 6a6987ec2d
8 files changed
+248 -41

No files matched your search

+22 -7
View File
@@ -19,9 +19,9 @@ import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import Flex from "~/components/Flex";
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
import Scrollable from "~/components/Scrollable";
import useDebouncedValue from "~/hooks/useDebouncedValue";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import { client } from "~/utils/ApiClient";
import Input from "./Input";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
import ToolbarButton from "./ToolbarButton";
@@ -29,6 +29,9 @@ import Tooltip from "./Tooltip";
import useOnClickOutside from "~/hooks/useOnClickOutside";
import { useEditor } from "./EditorContext";
/** The time in milliseconds the query must stay the same before it is sent. */
const RequestDelay = 100;
type Props = {
mark?: Mark;
view: EditorView;
@@ -67,18 +70,30 @@ const LinkEditor: React.FC<Props> = ({
? documents.findByQuery(trimmedQuery, { maxResults: 25 })
: [];
// Results from the store show at once, the server is only asked for more
// when the user stops typing.
const requestQuery = useDebouncedValue(trimmedQuery, RequestDelay);
const { request } = useRequest(
React.useCallback(async () => {
const res = await client.post("/suggestions.mention", { query });
res.data.documents.map(documents.add);
}, [documents, query])
React.useCallback(
() =>
documents.searchTitles({
query: requestQuery,
limit: 25,
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
}),
[documents, requestQuery]
)
);
useEffect(() => {
if (trimmedQuery) {
if (requestQuery) {
void request();
}
}, [trimmedQuery, request]);
}, [requestQuery, request]);
// Focus imperatively rather than with the autoFocus attribute, which only
// applies on mount – the editor can already be open when focus is requested.
+19 -4
View File
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import { v4 as uuidv4 } from "uuid";
import { runInAction } from "mobx";
import { useState, useCallback, useEffect } from "react";
import { useState, useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { MentionType } from "@shared/types";
@@ -25,6 +25,7 @@ import {
groupMentionItem,
userMentionItem,
} from "~/editor/menus/mention";
import useDebouncedValue from "~/hooks/useDebouncedValue";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
@@ -36,6 +37,9 @@ import type { Props as SuggestionsMenuProps } from "./SuggestionsMenu";
import SuggestionsMenu from "./SuggestionsMenu";
import SuggestionsMenuItem from "./SuggestionsMenuItem";
/** The time in milliseconds the search must stay the same before it is sent. */
const RequestDelay = 100;
type Props = Omit<
SuggestionsMenuProps<MentionMenuItem>,
"renderMenuItem" | "items" | "embeds"
@@ -122,13 +126,24 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
];
}
// Results from the store show at once, the server is only asked for more
// when the user stops typing.
const requestSearch = useDebouncedValue(search, RequestDelay);
const latestRequestId = useRef(0);
const { loading, request } = useRequest(
useCallback(async () => {
const requestId = ++latestRequestId.current;
const res = await client.post("/suggestions.mention", {
query: search,
limit: maxResultsInSection,
query: requestSearch,
limit: requestSearch ? 25 : 5,
});
// A newer request was sent while this one was in progress.
if (requestId !== latestRequestId.current) {
return;
}
runInAction(() => {
res.data.documents.map(documents.add);
res.data.users.map(users.add);
@@ -143,7 +158,7 @@ function MentionMenu({ search = "", isActive, ...rest }: Props) {
...Object.entries<number>(res.data.familiarity ?? {}),
])
);
}, [search, documents, users, collections, groups, maxResultsInSection])
}, [requestSearch, documents, users, collections, groups])
);
// Suggestions that the current user is familiar with, for example a member of
+20
View File
@@ -0,0 +1,20 @@
import { useEffect, useState } from "react";
/**
* Returns a value that only changes after the given value has stayed the same
* for the wait time. The first value is returned at once.
*
* @param value the value to debounce.
* @param wait the time in milliseconds the value must stay the same.
* @returns the last value that stayed the same for the wait time.
*/
export default function useDebouncedValue<T>(value: T, wait: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebounced(value), wait);
return () => clearTimeout(timeout);
}, [value, wait]);
return debounced;
}
@@ -1443,7 +1443,7 @@ describe("#collections.memberships", () => {
it("should allow filtering members in collection by name", async () => {
const team = await buildTeam();
const user = await buildUser({ teamId: team.id });
const user = await buildUser({ teamId: team.id, name: "Alice Smith" });
const collection = await buildCollection({
userId: user.id,
teamId: team.id,
@@ -7,6 +7,7 @@ import {
buildUser,
} from "@server/test/factories";
import { getTestServer } from "@server/test/support";
import SearchProviderManager from "@server/utils/SearchProviderManager";
const server = getTestServer();
@@ -116,6 +117,27 @@ describe("#suggestions.mention", () => {
expect(body.data.users).toEqual([]);
});
it("should return the other sections when a section is too slow", async () => {
const user = await buildUser();
const other = await buildUser({ teamId: user.teamId, name: "Elizabeth" });
const spy = vi
.spyOn(SearchProviderManager.getProvider(), "searchTitlesForUser")
.mockReturnValue(new Promise(() => undefined));
try {
const res = await server.post("/api/suggestions.mention", user);
const body = await res.json();
expect(res.status).toEqual(200);
expect(body.data.documents).toEqual([]);
expect(body.data.users.map((u: { id: string }) => u.id)).toContain(
other.id
);
} finally {
spy.mockRestore();
}
});
it("should require authentication", async () => {
const res = await server.post("/api/suggestions.mention");
expect(res.status).toEqual(401);
+78 -29
View File
@@ -1,6 +1,9 @@
import Router from "@koa/router";
import { Op } from "sequelize";
import { Sequelize } from "sequelize-typescript";
import { Second } from "@shared/utils/time";
import { withinTimeLimit } from "@shared/utils/timers";
import { addTags, getRootSpanFromRequestContext } from "@server/logging/tracer";
import auth from "@server/middlewares/authentication";
import validate from "@server/middlewares/validate";
import { Group, User } from "@server/models";
@@ -22,6 +25,9 @@ import * as T from "./schema";
const router = new Router();
/** The time each section of the suggestions may take before it is left out. */
const sectionTimeLimit = Second.ms;
router.post(
"suggestions.mention",
auth(),
@@ -80,23 +86,51 @@ router.post(
};
};
const timedOut: string[] = [];
const withinLimit = <T>(
section: string,
run: () => Promise<T>,
fallback: T
) =>
withinTimeLimit(run, sectionTimeLimit, fallback, () => {
timedOut.push(section);
});
// Presentation is part of each section, as presenters can also query.
const [documents, { users, familiarity }, groups, collections] =
await Promise.all([
SearchProviderManager.getProvider().searchTitlesForUser(actor, {
query,
offset,
limit,
filter: {
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
},
}),
suggestUsers(),
can(actor, "listGroups", actor.team)
? Group.findAll({
withinLimit(
"documents",
async () =>
presentDocuments(
ctx,
await SearchProviderManager.getProvider().searchTitlesForUser(
actor,
{
query,
offset,
limit,
filter: {
operator: "AND",
filters: [
{ field: "archivedAt", operator: "isNull" },
{ field: "publishedAt", operator: "isNotNull" },
],
},
}
)
),
[]
),
withinLimit("users", suggestUsers, { users: [], familiarity: {} }),
withinLimit(
"groups",
async () => {
if (!can(actor, "listGroups", actor.team)) {
return [];
}
const found = await Group.findAll({
where: {
teamId: actor.teamId,
disableMentions: false,
@@ -107,34 +141,49 @@ router.post(
: {},
},
order: [["name", "ASC"]],
replacements: { query: QueryHelper.likeContains(query ?? "") },
replacements: {
query: QueryHelper.likeContains(query ?? ""),
},
offset,
limit,
})
: [],
SearchProviderManager.getProvider().searchCollectionsForUser(actor, {
query,
offset,
limit,
}),
});
return Promise.all(found.map((group) => presentGroup(group)));
},
[]
),
withinLimit(
"collections",
() =>
SearchProviderManager.getProvider().searchCollectionsForUser(
actor,
{
query,
offset,
limit,
}
),
[]
),
]);
const [presentedDocuments, presentedGroups] = await Promise.all([
presentDocuments(ctx, documents),
Promise.all(groups.map((group) => presentGroup(group))),
]);
if (timedOut.length) {
addTags(
{ "suggestions.timedOut": timedOut.join(",") },
getRootSpanFromRequestContext(ctx)
);
}
ctx.body = {
pagination: ctx.state.pagination,
data: {
documents: presentedDocuments,
documents,
users: users.map((user) =>
presentUser(user, {
includeEmail: !!can(actor, "readEmail", user),
includeDetails: !!can(actor, "readDetails", user),
})
),
groups: presentedGroups,
groups,
collections,
familiarity,
},
+50
View File
@@ -0,0 +1,50 @@
import { withinTimeLimit } from "./timers";
describe("withinTimeLimit", () => {
it("should return the result when the function finishes in time", async () => {
const onTimeout = vi.fn();
const result = await withinTimeLimit(
async () => "done",
100,
"fallback",
onTimeout
);
expect(result).toEqual("done");
expect(onTimeout).not.toHaveBeenCalled();
});
it("should return the fallback when the function is too slow", async () => {
vi.useFakeTimers();
try {
const onTimeout = vi.fn();
const promise = withinTimeLimit(
() => new Promise<string>(() => undefined),
100,
"fallback",
onTimeout
);
await vi.advanceTimersByTimeAsync(100);
await expect(promise).resolves.toEqual("fallback");
expect(onTimeout).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});
it("should throw the error of a function that fails in time", async () => {
await expect(
withinTimeLimit(
async () => {
throw new Error("failed");
},
100,
"fallback"
)
).rejects.toThrow("failed");
});
});
+36
View File
@@ -1,3 +1,5 @@
import { TimeoutError, withTimeout } from "es-toolkit";
/**
* Returns a promise that resolves after a specified number of milliseconds.
*
@@ -6,3 +8,37 @@
export function sleep(ms = 1) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Runs an async function with a time limit, and returns a fallback value when
* the function takes too long. The function is not canceled, its result is
* ignored when it settles after the time limit.
*
* @param run the function to run.
* @param ms the time limit in milliseconds.
* @param fallback the value to return when the time limit is reached.
* @param onTimeout called when the time limit is reached.
* @returns the result of the function, or the fallback.
* @throws the error of the function, when it fails within the time limit.
*/
export async function withinTimeLimit<T>(
run: () => Promise<T>,
ms: number,
fallback: T,
onTimeout?: () => void
): Promise<T> {
const controller = new AbortController();
try {
return await withTimeout(run, ms, { signal: controller.signal });
} catch (err) {
if (err instanceof TimeoutError) {
onTimeout?.();
return fallback;
}
throw err;
} finally {
// Clears the timer when the function finished within the time limit.
controller.abort();
}
}