feat(web): rank chat mentions by recency (#3099)
This commit is contained in:
@@ -46,6 +46,7 @@ import { useEntityReferenceComposer } from "./use-entity-reference-composer";
|
||||
import { EntityReferenceSuggestionPluginKey } from "./tiptap-entity-reference-suggestion";
|
||||
import type { ImagePasteIssue } from "./clipboard-attachments";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { rankMentionItems, recordChatMentionSelection } from "@/lib/chat-mention-recency";
|
||||
|
||||
const RAW_DRAIN = { rawPagination: true } as const;
|
||||
|
||||
@@ -76,24 +77,6 @@ type TipTapInputProps = {
|
||||
onPlanModeChange?: (enabled: boolean) => void;
|
||||
};
|
||||
|
||||
// ── Filter items ────────────────────────────────────────────────────
|
||||
function filterItems(items: MentionItem[], query: string): MentionItem[] {
|
||||
if (!query) return items;
|
||||
const lq = query.toLowerCase();
|
||||
return items
|
||||
.map((item) => {
|
||||
const label = item.label.toLowerCase();
|
||||
let score = 0;
|
||||
if (label.startsWith(lq)) score = 100;
|
||||
else if (label.split(/[\s\-_/]/).some((w) => w.startsWith(lq))) score = 50;
|
||||
else if (label.includes(lq)) score = 25;
|
||||
return { item, score };
|
||||
})
|
||||
.filter(({ score }) => score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.map(({ item }) => item);
|
||||
}
|
||||
|
||||
// ── Menu keyboard navigation helper ──────────────────────────────
|
||||
|
||||
function handleMenuKeyDown<T>(
|
||||
@@ -139,13 +122,18 @@ async function fetchFileResults(
|
||||
return results;
|
||||
}
|
||||
|
||||
function useMentionItems(sessionId: string | null, taskId: string | null) {
|
||||
function useMentionItems(
|
||||
sessionId: string | null,
|
||||
taskId: string | null,
|
||||
workspaceId: string | null,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const { prompts } = useCustomPrompts();
|
||||
const storeApi = useAppStoreApi();
|
||||
const promptsRef = useRef(prompts);
|
||||
const sessionIdRef = useRef(sessionId);
|
||||
const taskIdRef = useRef(taskId);
|
||||
const workspaceIdRef = useRef(workspaceId);
|
||||
const lastFileSearchRef = useRef<{ query: string; results: string[] }>({
|
||||
query: "",
|
||||
results: [],
|
||||
@@ -154,6 +142,7 @@ function useMentionItems(sessionId: string | null, taskId: string | null) {
|
||||
promptsRef.current = prompts;
|
||||
sessionIdRef.current = sessionId;
|
||||
taskIdRef.current = taskId;
|
||||
workspaceIdRef.current = workspaceId;
|
||||
});
|
||||
|
||||
return useCallback(
|
||||
@@ -193,7 +182,7 @@ function useMentionItems(sessionId: string | null, taskId: string | null) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
return filterItems(allItems, query);
|
||||
return rankMentionItems(allItems, query, workspaceIdRef.current);
|
||||
},
|
||||
[storeApi],
|
||||
);
|
||||
@@ -204,6 +193,7 @@ function useMentionItems(sessionId: string | null, taskId: string | null) {
|
||||
type SuggestionConfigsInput = {
|
||||
sessionId: string | null;
|
||||
taskId: string | null;
|
||||
workspaceId: string | null;
|
||||
onMentionKeyDown: (event: KeyboardEvent) => boolean;
|
||||
onSlashKeyDown: (event: KeyboardEvent) => boolean;
|
||||
setMentionMenu: React.Dispatch<React.SetStateAction<MenuState<MentionItem>>>;
|
||||
@@ -213,6 +203,7 @@ type SuggestionConfigsInput = {
|
||||
function useSuggestionConfigs({
|
||||
sessionId,
|
||||
taskId,
|
||||
workspaceId,
|
||||
onMentionKeyDown,
|
||||
onSlashKeyDown,
|
||||
setMentionMenu,
|
||||
@@ -235,9 +226,17 @@ function useSuggestionConfigs({
|
||||
}));
|
||||
}, [agentCommands]);
|
||||
|
||||
const getMentionItems = useMentionItems(sessionId, taskId);
|
||||
const workspaceIdRef = useRef(workspaceId);
|
||||
useLayoutEffect(() => {
|
||||
workspaceIdRef.current = workspaceId;
|
||||
});
|
||||
|
||||
const getMentionItems = useMentionItems(sessionId, taskId, workspaceId);
|
||||
const mentionCallbacks = useMemo(
|
||||
(): MentionSuggestionCallbacks => ({ getItems: getMentionItems }),
|
||||
(): MentionSuggestionCallbacks => ({
|
||||
getItems: getMentionItems,
|
||||
onSelect: (item) => recordChatMentionSelection(item, workspaceIdRef.current),
|
||||
}),
|
||||
[getMentionItems],
|
||||
);
|
||||
|
||||
@@ -424,6 +423,7 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
|
||||
const { mentionSuggestion, slashSuggestion, slashCommands } = useSuggestionConfigs({
|
||||
sessionId,
|
||||
taskId: taskId ?? null,
|
||||
workspaceId,
|
||||
onMentionKeyDown: menu.onMentionKeyDown,
|
||||
onSlashKeyDown: menu.onSlashKeyDown,
|
||||
setMentionMenu: menu.setMentionMenu,
|
||||
@@ -471,10 +471,9 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
|
||||
ref,
|
||||
});
|
||||
useEditorRefSync(editorRef, editor);
|
||||
const { closeReverseSearch } = overlay;
|
||||
const handleReverseSearchSelect = useReverseSearchSelectHandler(
|
||||
applyHistoryEntry,
|
||||
closeReverseSearch,
|
||||
overlay.closeReverseSearch,
|
||||
editor,
|
||||
);
|
||||
return (
|
||||
|
||||
@@ -311,7 +311,7 @@ describe("createMentionSuggestion", () => {
|
||||
onSelect: vi.fn(),
|
||||
};
|
||||
const suggestion = createMentionSuggestion(
|
||||
{ getItems: vi.fn().mockResolvedValue([task, file]) },
|
||||
{ getItems: vi.fn().mockResolvedValue([task, file]), onSelect: vi.fn() },
|
||||
vi.fn(),
|
||||
vi.fn(),
|
||||
);
|
||||
@@ -322,4 +322,46 @@ describe("createMentionSuggestion", () => {
|
||||
|
||||
expect(items).toEqual([task, file]);
|
||||
});
|
||||
|
||||
it("records selection through the shared command path", () => {
|
||||
const task: MentionItem = {
|
||||
id: "task:task-1",
|
||||
kind: "task",
|
||||
label: "Selected task",
|
||||
task: {
|
||||
taskId: "task-1",
|
||||
title: "Selected task",
|
||||
workflowId: "workflow-1",
|
||||
workflowStepId: "step-1",
|
||||
state: null,
|
||||
},
|
||||
onSelect: vi.fn(),
|
||||
};
|
||||
const setMenuState = vi.fn();
|
||||
const onSelect = vi.fn();
|
||||
const suggestion = createMentionSuggestion(
|
||||
{ getItems: vi.fn().mockResolvedValue([task]), onSelect },
|
||||
setMenuState,
|
||||
vi.fn(),
|
||||
);
|
||||
const lifecycle = suggestion.render?.();
|
||||
const command = vi.fn();
|
||||
|
||||
lifecycle?.onStart?.({
|
||||
editor: {} as never,
|
||||
range: { from: 1, to: 2 },
|
||||
query: "",
|
||||
text: "@",
|
||||
items: [task],
|
||||
command,
|
||||
decorationNode: null,
|
||||
clientRect: null,
|
||||
});
|
||||
|
||||
const menu = setMenuState.mock.calls[0]?.[0];
|
||||
menu?.command?.(task);
|
||||
|
||||
expect(command).toHaveBeenCalledOnce();
|
||||
expect(onSelect).toHaveBeenCalledWith(task);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,6 +43,7 @@ const EMPTY_SLASH_STATE: MenuState<SlashCommand> = {
|
||||
|
||||
export type MentionSuggestionCallbacks = {
|
||||
getItems: (query: string) => Promise<MentionItem[]>;
|
||||
onSelect: (item: MentionItem) => void;
|
||||
};
|
||||
|
||||
export const MentionSuggestionPluginKey = new PluginKey("mentionSuggestion");
|
||||
@@ -95,6 +96,7 @@ export function createMentionSuggestion(
|
||||
clientRect: props.clientRect ?? null,
|
||||
command: (item: MentionItem) => {
|
||||
props.command(mentionItemToAttrs(item));
|
||||
callbacks.onSelect(item);
|
||||
},
|
||||
});
|
||||
},
|
||||
@@ -107,6 +109,7 @@ export function createMentionSuggestion(
|
||||
clientRect: props.clientRect ?? null,
|
||||
command: (item: MentionItem) => {
|
||||
props.command(mentionItemToAttrs(item));
|
||||
callbacks.onSelect(item);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { type Locator, type Page } from "@playwright/test";
|
||||
import { test, expect, type SeedData } from "../../fixtures/test-base";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import { CHAT_MENTION_RECENCY_STORAGE_KEY } from "../../../lib/chat-mention-recency";
|
||||
|
||||
const RECENT_TITLE = "Project-Mention-Recency-Target";
|
||||
const STRONGER_TITLE = "Mention-Recency-Stronger-Match";
|
||||
|
||||
async function createReadyTask(
|
||||
apiClient: ApiClient,
|
||||
seedData: SeedData,
|
||||
title: string,
|
||||
): Promise<{ id: string }> {
|
||||
return apiClient.createTaskWithAgent(seedData.workspaceId, title, seedData.agentProfileId, {
|
||||
description: "/e2e:simple-message",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
});
|
||||
}
|
||||
|
||||
async function openTaskChat(page: Page, taskId: string): Promise<SessionPage> {
|
||||
await page.goto(`/t/${taskId}`);
|
||||
const session = new SessionPage(page);
|
||||
await session.waitForLoad();
|
||||
await session.waitForChatIdle({ timeout: 30_000 });
|
||||
return session;
|
||||
}
|
||||
|
||||
function visibleEditor(scope: Locator): Locator {
|
||||
return scope.locator(".tiptap.ProseMirror:visible").first();
|
||||
}
|
||||
|
||||
async function typeMention(editor: Locator, query: string): Promise<Locator> {
|
||||
await editor.fill("");
|
||||
await editor.pressSequentially(`@${query}`);
|
||||
const menu = editor.page().getByRole("listbox", { name: /Mention tasks, files, prompts/i });
|
||||
await expect(menu).toBeVisible({ timeout: 10_000 });
|
||||
return menu;
|
||||
}
|
||||
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.1
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.2
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.4
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.6
|
||||
test("ranks a selected task first and keeps the order after reload", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
prCapture,
|
||||
}) => {
|
||||
await apiClient.seedTask(seedData.workspaceId, RECENT_TITLE, {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
await apiClient.seedTask(seedData.workspaceId, STRONGER_TITLE, {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
const active = await createReadyTask(apiClient, seedData, "Mention Recency Active Task");
|
||||
|
||||
await testPage.goto("/");
|
||||
await testPage.evaluate(
|
||||
(key) => window.localStorage.removeItem(key),
|
||||
CHAT_MENTION_RECENCY_STORAGE_KEY,
|
||||
);
|
||||
const session = await openTaskChat(testPage, active.id);
|
||||
const editor = visibleEditor(session.activeChat());
|
||||
|
||||
const baselineMenu = await typeMention(editor, "mention");
|
||||
await expect(baselineMenu.getByRole("option").first()).toContainText(STRONGER_TITLE);
|
||||
await editor.press("Escape");
|
||||
|
||||
const uniqueMenu = await typeMention(editor, "Project-Mention");
|
||||
await uniqueMenu.getByRole("option").filter({ hasText: RECENT_TITLE }).click();
|
||||
await expect(uniqueMenu).toHaveCount(0);
|
||||
|
||||
const rankedMenu = await typeMention(editor, "mention");
|
||||
await expect(rankedMenu.getByRole("option").first()).toContainText(RECENT_TITLE);
|
||||
await prCapture.screenshot("desktop-mention-recency-menu", {
|
||||
caption: "A previously selected task leads the desktop mention menu",
|
||||
});
|
||||
|
||||
await testPage.reload();
|
||||
const reloadedSession = new SessionPage(testPage);
|
||||
await reloadedSession.waitForLoad();
|
||||
const reloadedEditor = visibleEditor(reloadedSession.activeChat());
|
||||
await expect(reloadedEditor).toBeEditable({ timeout: 30_000 });
|
||||
const persistedMenu = await typeMention(reloadedEditor, "mention");
|
||||
await expect(persistedMenu.getByRole("option").first()).toContainText(RECENT_TITLE);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { type Page } from "@playwright/test";
|
||||
import { test, expect, type SeedData } from "../../fixtures/test-base";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import { waitForPromptInStore } from "../../helpers/settings-prompt-editor";
|
||||
import { CHAT_MENTION_RECENCY_STORAGE_KEY } from "../../../lib/chat-mention-recency";
|
||||
|
||||
const RECENT_PROMPT_NAME = "Project-Mention-Recency-Prompt";
|
||||
const STRONGER_PROMPT_NAME = "Mention-Recency-Strong-Prompt";
|
||||
|
||||
async function openReadyTask(page: Page, apiClient: ApiClient, seedData: SeedData) {
|
||||
const task = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
"Mobile Mention Recency Active Task",
|
||||
seedData.agentProfileId,
|
||||
{
|
||||
description: "/e2e:simple-message",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
await page.goto(`/t/${task.id}`);
|
||||
const session = new SessionPage(page);
|
||||
await session.waitForLoad();
|
||||
await session.waitForChatIdle({ timeout: 30_000 });
|
||||
return session;
|
||||
}
|
||||
|
||||
test.describe("Mobile chat mention recency", () => {
|
||||
test.describe.configure({ timeout: 90_000 });
|
||||
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.1
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.4
|
||||
// @covers AC-UI-COMPOSER-MENTION-RECENCY-001.8
|
||||
test("touch selection uses the shared recency order in the mobile popup", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
prCapture,
|
||||
}) => {
|
||||
const recentPrompt = await apiClient.createPrompt(
|
||||
RECENT_PROMPT_NAME,
|
||||
"Mobile recent mention prompt",
|
||||
);
|
||||
const strongerPrompt = await apiClient.createPrompt(
|
||||
STRONGER_PROMPT_NAME,
|
||||
"Mobile stronger mention prompt",
|
||||
);
|
||||
|
||||
try {
|
||||
await testPage.goto("/");
|
||||
await testPage.evaluate(
|
||||
(key) => window.localStorage.removeItem(key),
|
||||
CHAT_MENTION_RECENCY_STORAGE_KEY,
|
||||
);
|
||||
const session = await openReadyTask(testPage, apiClient, seedData);
|
||||
await waitForPromptInStore(testPage, RECENT_PROMPT_NAME);
|
||||
await waitForPromptInStore(testPage, STRONGER_PROMPT_NAME);
|
||||
const editor = await session.composerReady();
|
||||
|
||||
await editor.tap();
|
||||
await editor.fill("");
|
||||
await editor.pressSequentially("@mention");
|
||||
const baselineMenu = testPage.getByRole("listbox", {
|
||||
name: /Mention tasks, files, prompts/i,
|
||||
});
|
||||
await expect(baselineMenu).toBeVisible({ timeout: 10_000 });
|
||||
await expect(baselineMenu.getByRole("option").first()).toContainText(STRONGER_PROMPT_NAME);
|
||||
await editor.press("Escape");
|
||||
|
||||
await editor.fill("");
|
||||
await editor.pressSequentially("@Project-Mention");
|
||||
const uniqueMenu = testPage.getByRole("listbox", {
|
||||
name: /Mention tasks, files, prompts/i,
|
||||
});
|
||||
await expect(uniqueMenu).toBeVisible({ timeout: 10_000 });
|
||||
await uniqueMenu.getByRole("option").filter({ hasText: RECENT_PROMPT_NAME }).tap();
|
||||
await expect(uniqueMenu).toHaveCount(0);
|
||||
|
||||
await editor.fill("");
|
||||
await editor.pressSequentially("@mention");
|
||||
const rankedMenu = testPage.getByRole("listbox", {
|
||||
name: /Mention tasks, files, prompts/i,
|
||||
});
|
||||
await expect(rankedMenu).toBeVisible({ timeout: 10_000 });
|
||||
await expect(rankedMenu.getByRole("option").first()).toContainText(RECENT_PROMPT_NAME);
|
||||
await prCapture.screenshot("mobile-mention-recency-menu", {
|
||||
caption: "A touch-selected prompt leads the mobile mention popup",
|
||||
});
|
||||
} finally {
|
||||
await apiClient.deletePrompt(recentPrompt.id).catch(() => undefined);
|
||||
await apiClient.deletePrompt(strongerPrompt.id).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { MentionItem } from "@/hooks/use-inline-mention";
|
||||
import {
|
||||
CHAT_MENTION_RECENCY_STORAGE_KEY,
|
||||
MAX_CHAT_MENTION_RECENT_ENTRIES,
|
||||
getChatMentionRecentEntries,
|
||||
mentionItemToRecentEntry,
|
||||
normalizeChatMentionRecentEntries,
|
||||
rankMentionItems,
|
||||
recordChatMentionSelection,
|
||||
} from "./chat-mention-recency";
|
||||
|
||||
function makeItem(
|
||||
kind: MentionItem["kind"],
|
||||
id: string,
|
||||
label: string,
|
||||
taskId?: string,
|
||||
): MentionItem {
|
||||
return {
|
||||
id,
|
||||
kind,
|
||||
label,
|
||||
task:
|
||||
kind === "task"
|
||||
? {
|
||||
taskId: taskId ?? id,
|
||||
title: label,
|
||||
workflowId: "workflow-1",
|
||||
workflowStepId: "step-1",
|
||||
state: null,
|
||||
}
|
||||
: undefined,
|
||||
onSelect: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
const WORKSPACE_ID = "workspace-1";
|
||||
const OTHER_WORKSPACE_ID = "workspace-2";
|
||||
const FILE_PATH = "src/app.ts";
|
||||
|
||||
describe("chat mention recency", () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("preserves baseline filtering and stable source order without history", () => {
|
||||
const items = [
|
||||
makeItem("prompt", "contains", "Acontainsneedle"),
|
||||
makeItem("prompt", "word", "A needle word"),
|
||||
makeItem("prompt", "prefix", "Needle first"),
|
||||
makeItem("prompt", "same-1", "Same needle"),
|
||||
makeItem("prompt", "same-2", "Another needle"),
|
||||
];
|
||||
|
||||
expect(rankMentionItems(items, "needle", WORKSPACE_ID, [])).toEqual([
|
||||
items[2],
|
||||
items[1],
|
||||
items[3],
|
||||
items[4],
|
||||
items[0],
|
||||
]);
|
||||
});
|
||||
|
||||
it("ranks a recent weaker text match before an unselected stronger match", () => {
|
||||
const recent = makeItem("task", "task:recent", "Project task", "recent");
|
||||
const stronger = makeItem("task", "task:stronger", "Task owner", "stronger");
|
||||
|
||||
expect(
|
||||
rankMentionItems([stronger, recent], "task", WORKSPACE_ID, [
|
||||
{
|
||||
kind: "task",
|
||||
id: "recent",
|
||||
},
|
||||
]),
|
||||
).toEqual([recent, stronger]);
|
||||
});
|
||||
|
||||
it("orders multiple recent candidates by newest selection before text score", () => {
|
||||
const older = makeItem("task", "task:older", "Older task", "older");
|
||||
const newer = makeItem("prompt", "prompt:newer", "Newer prompt");
|
||||
const unselected = makeItem("task", "task:unselected", "Unselected task", "unselected");
|
||||
|
||||
expect(
|
||||
rankMentionItems([older, newer, unselected], "", WORKSPACE_ID, [
|
||||
{ kind: "prompt", id: newer.id },
|
||||
{ kind: "task", id: "older" },
|
||||
]),
|
||||
).toEqual([newer, older, unselected]);
|
||||
});
|
||||
|
||||
it("keeps the Plan action at its baseline index while reordering candidates", () => {
|
||||
const first = makeItem("task", "task:first", "First task", "first");
|
||||
const plan = makeItem("plan", "__plan__", "Plan");
|
||||
const recent = makeItem("prompt", "prompt-recent", "Recent prompt");
|
||||
|
||||
expect(
|
||||
rankMentionItems([first, plan, recent], "", WORKSPACE_ID, [
|
||||
{ kind: "prompt", id: recent.id },
|
||||
]),
|
||||
).toEqual([recent, plan, first]);
|
||||
});
|
||||
|
||||
it("uses Plan's filtered baseline position for non-empty queries", () => {
|
||||
const filtered = makeItem("task", "task:filtered", "Unrelated task", "filtered");
|
||||
const plan = makeItem("plan", "__plan__", "Plan");
|
||||
const recent = makeItem("prompt", "prompt-recent", "Plan prompt");
|
||||
|
||||
expect(
|
||||
rankMentionItems([filtered, plan, recent], "plan", WORKSPACE_ID, [
|
||||
{ kind: "prompt", id: recent.id },
|
||||
]),
|
||||
).toEqual([plan, recent]);
|
||||
});
|
||||
|
||||
it("scopes file identities to the active workspace", () => {
|
||||
const sharedPath = makeItem("file", FILE_PATH, FILE_PATH);
|
||||
const otherPath = makeItem("file", "src/other.ts", "src/other.ts");
|
||||
|
||||
expect(
|
||||
rankMentionItems([otherPath, sharedPath], "", OTHER_WORKSPACE_ID, [
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: WORKSPACE_ID },
|
||||
]),
|
||||
).toEqual([otherPath, sharedPath]);
|
||||
expect(
|
||||
rankMentionItems([otherPath, sharedPath], "", WORKSPACE_ID, [
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: WORKSPACE_ID },
|
||||
]),
|
||||
).toEqual([sharedPath, otherPath]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("chat mention recency storage", () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("normalizes malformed history, removes duplicate identities, and bounds the list", () => {
|
||||
const entries = normalizeChatMentionRecentEntries([
|
||||
{ kind: "prompt", id: "prompt-1" },
|
||||
{ kind: "prompt", id: "prompt-1" },
|
||||
{ kind: "file", id: FILE_PATH },
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: WORKSPACE_ID },
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: OTHER_WORKSPACE_ID },
|
||||
{ kind: "unknown", id: "bad" },
|
||||
{ kind: "task", id: "" },
|
||||
null,
|
||||
]);
|
||||
|
||||
expect(entries).toEqual([
|
||||
{ kind: "prompt", id: "prompt-1" },
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: WORKSPACE_ID },
|
||||
{ kind: "file", id: FILE_PATH, workspaceId: OTHER_WORKSPACE_ID },
|
||||
]);
|
||||
|
||||
const bounded = normalizeChatMentionRecentEntries(
|
||||
Array.from({ length: MAX_CHAT_MENTION_RECENT_ENTRIES + 3 }, (_, index) => ({
|
||||
kind: "task",
|
||||
id: `task-${index}`,
|
||||
})),
|
||||
);
|
||||
expect(bounded).toHaveLength(MAX_CHAT_MENTION_RECENT_ENTRIES);
|
||||
expect(bounded[0]).toEqual({ kind: "task", id: "task-0" });
|
||||
});
|
||||
|
||||
it("persists selections as a bounded newest-first MRU list", () => {
|
||||
const first = makeItem("task", "task:first", "First", "first");
|
||||
const second = makeItem("prompt", "prompt:second", "Second");
|
||||
window.localStorage.setItem(
|
||||
CHAT_MENTION_RECENCY_STORAGE_KEY,
|
||||
JSON.stringify(
|
||||
Array.from({ length: MAX_CHAT_MENTION_RECENT_ENTRIES }, (_, index) => ({
|
||||
kind: "task",
|
||||
id: `task-${index}`,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
recordChatMentionSelection(first, WORKSPACE_ID);
|
||||
recordChatMentionSelection(second, WORKSPACE_ID);
|
||||
recordChatMentionSelection(first, WORKSPACE_ID);
|
||||
|
||||
const stored = getChatMentionRecentEntries();
|
||||
expect(stored[0]).toEqual({ kind: "task", id: "first" });
|
||||
expect(stored[1]).toEqual({ kind: "prompt", id: "prompt:second" });
|
||||
expect(stored).toHaveLength(MAX_CHAT_MENTION_RECENT_ENTRIES);
|
||||
expect(stored.filter((entry) => entry.kind === "task" && entry.id === "first")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not record Plan or an unscoped file", () => {
|
||||
const plan = makeItem("plan", "__plan__", "Plan");
|
||||
const file = makeItem("file", FILE_PATH, FILE_PATH);
|
||||
|
||||
expect(mentionItemToRecentEntry(plan, WORKSPACE_ID)).toBeNull();
|
||||
expect(mentionItemToRecentEntry(file, null)).toBeNull();
|
||||
recordChatMentionSelection(plan, WORKSPACE_ID);
|
||||
recordChatMentionSelection(file, null);
|
||||
expect(getChatMentionRecentEntries()).toEqual([]);
|
||||
});
|
||||
|
||||
it("continues without throwing when browser storage is unavailable", () => {
|
||||
const originalStorage = window.localStorage;
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
configurable: true,
|
||||
get: () => {
|
||||
throw new Error("storage unavailable");
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
expect(getChatMentionRecentEntries()).toEqual([]);
|
||||
expect(() =>
|
||||
recordChatMentionSelection(makeItem("prompt", "prompt-1", "Prompt"), "w-1"),
|
||||
).not.toThrow();
|
||||
} finally {
|
||||
Object.defineProperty(window, "localStorage", {
|
||||
configurable: true,
|
||||
value: originalStorage,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import type { MentionItem } from "@/hooks/use-inline-mention";
|
||||
|
||||
export const CHAT_MENTION_RECENCY_STORAGE_KEY = "kandev.chatMentionRecency.v1";
|
||||
export const MAX_CHAT_MENTION_RECENT_ENTRIES = 50;
|
||||
|
||||
type ChatMentionRecentKind = "task" | "prompt" | "file";
|
||||
|
||||
export type ChatMentionRecentEntry = {
|
||||
kind: ChatMentionRecentKind;
|
||||
id: string;
|
||||
workspaceId?: string;
|
||||
};
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
function isRecentKind(value: unknown): value is ChatMentionRecentKind {
|
||||
return value === "task" || value === "prompt" || value === "file";
|
||||
}
|
||||
|
||||
function recentEntryKey(entry: ChatMentionRecentEntry): string {
|
||||
return `${entry.kind}:${entry.workspaceId ?? ""}:${entry.id}`;
|
||||
}
|
||||
|
||||
function normalizeRecentEntry(value: unknown): ChatMentionRecentEntry | null {
|
||||
if (!isRecord(value) || !isRecentKind(value.kind)) return null;
|
||||
const id = nonEmptyString(value.id);
|
||||
if (!id) return null;
|
||||
|
||||
if (value.kind === "file") {
|
||||
const workspaceId = nonEmptyString(value.workspaceId);
|
||||
if (!workspaceId) return null;
|
||||
return { kind: value.kind, id, workspaceId };
|
||||
}
|
||||
|
||||
return { kind: value.kind, id };
|
||||
}
|
||||
|
||||
export function normalizeChatMentionRecentEntries(value: unknown): ChatMentionRecentEntry[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const normalized: ChatMentionRecentEntry[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const candidate of value) {
|
||||
const entry = normalizeRecentEntry(candidate);
|
||||
if (!entry) continue;
|
||||
const key = recentEntryKey(entry);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
normalized.push(entry);
|
||||
if (normalized.length === MAX_CHAT_MENTION_RECENT_ENTRIES) break;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function getLocalStorage(): Storage | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
return window.localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getChatMentionRecentEntries(): ChatMentionRecentEntry[] {
|
||||
const storage = getLocalStorage();
|
||||
if (!storage) return [];
|
||||
|
||||
try {
|
||||
const raw = storage.getItem(CHAT_MENTION_RECENCY_STORAGE_KEY);
|
||||
return raw ? normalizeChatMentionRecentEntries(JSON.parse(raw)) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function mentionItemToRecentEntry(
|
||||
item: MentionItem,
|
||||
workspaceId: string | null | undefined,
|
||||
): ChatMentionRecentEntry | null {
|
||||
if (item.kind === "plan") return null;
|
||||
|
||||
if (item.kind === "file") {
|
||||
const scopedWorkspaceId = nonEmptyString(workspaceId);
|
||||
const id = nonEmptyString(item.id);
|
||||
if (!scopedWorkspaceId || !id) return null;
|
||||
return { kind: item.kind, id, workspaceId: scopedWorkspaceId };
|
||||
}
|
||||
|
||||
const id = nonEmptyString(item.kind === "task" ? (item.task?.taskId ?? item.id) : item.id);
|
||||
return id ? { kind: item.kind, id } : null;
|
||||
}
|
||||
|
||||
function writeRecentEntries(entries: ChatMentionRecentEntry[]): void {
|
||||
const storage = getLocalStorage();
|
||||
if (!storage) return;
|
||||
try {
|
||||
storage.setItem(CHAT_MENTION_RECENCY_STORAGE_KEY, JSON.stringify(entries));
|
||||
} catch {
|
||||
// Ignore private browsing, blocked storage, and quota failures.
|
||||
}
|
||||
}
|
||||
|
||||
export function recordChatMentionSelection(
|
||||
item: MentionItem,
|
||||
workspaceId: string | null | undefined,
|
||||
): ChatMentionRecentEntry[] {
|
||||
const entry = mentionItemToRecentEntry(item, workspaceId);
|
||||
if (!entry) return getChatMentionRecentEntries();
|
||||
|
||||
const current = getChatMentionRecentEntries().filter(
|
||||
(candidate) => recentEntryKey(candidate) !== recentEntryKey(entry),
|
||||
);
|
||||
const updated = [entry, ...current].slice(0, MAX_CHAT_MENTION_RECENT_ENTRIES);
|
||||
writeRecentEntries(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
type ScoredMentionItem = {
|
||||
item: MentionItem;
|
||||
score: number;
|
||||
baselineIndex: number;
|
||||
};
|
||||
|
||||
function textMatchScore(label: string, query: string): number {
|
||||
if (!query) return 0;
|
||||
const lowerLabel = label.toLowerCase();
|
||||
if (lowerLabel.startsWith(query)) return 100;
|
||||
if (lowerLabel.split(/[\s\-_/]/).some((word) => word.startsWith(query))) return 50;
|
||||
if (lowerLabel.includes(query)) return 25;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function buildBaseline(items: MentionItem[], query: string): ScoredMentionItem[] {
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return items
|
||||
.map((item, baselineIndex) => ({
|
||||
item,
|
||||
score: textMatchScore(item.label, lowerQuery),
|
||||
baselineIndex,
|
||||
}))
|
||||
.filter(({ score }) => !query || score > 0)
|
||||
.sort((a, b) => b.score - a.score || a.baselineIndex - b.baselineIndex);
|
||||
}
|
||||
|
||||
export function rankMentionItems(
|
||||
items: MentionItem[],
|
||||
query: string,
|
||||
workspaceId: string | null | undefined,
|
||||
recentEntries: readonly ChatMentionRecentEntry[] = getChatMentionRecentEntries(),
|
||||
): MentionItem[] {
|
||||
const baseline = buildBaseline(items, query);
|
||||
const normalizedRecentEntries = normalizeChatMentionRecentEntries(recentEntries);
|
||||
if (normalizedRecentEntries.length === 0) return baseline.map(({ item }) => item);
|
||||
|
||||
const recentPositions = new Map(
|
||||
normalizedRecentEntries.map((entry, index) => [recentEntryKey(entry), index]),
|
||||
);
|
||||
const planIndex = baseline.findIndex(({ item }) => item.kind === "plan");
|
||||
const plan = planIndex >= 0 ? baseline[planIndex] : undefined;
|
||||
const candidates = baseline.filter(({ item }) => item.kind !== "plan");
|
||||
|
||||
candidates.sort((a, b) => {
|
||||
const aEntry = mentionItemToRecentEntry(a.item, workspaceId);
|
||||
const bEntry = mentionItemToRecentEntry(b.item, workspaceId);
|
||||
const aRecent = aEntry ? recentPositions.get(recentEntryKey(aEntry)) : undefined;
|
||||
const bRecent = bEntry ? recentPositions.get(recentEntryKey(bEntry)) : undefined;
|
||||
const aKnown = aRecent !== undefined;
|
||||
const bKnown = bRecent !== undefined;
|
||||
|
||||
if (aKnown !== bKnown) return aKnown ? -1 : 1;
|
||||
if (aKnown && bKnown && aRecent !== bRecent) return aRecent! - bRecent!;
|
||||
return b.score - a.score || a.baselineIndex - b.baselineIndex;
|
||||
});
|
||||
|
||||
const ranked = candidates.map(({ item }) => item);
|
||||
if (!plan) return ranked;
|
||||
ranked.splice(Math.min(planIndex, ranked.length), 0, plan.item);
|
||||
return ranked;
|
||||
}
|
||||
Reference in New Issue
Block a user