Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): refresh open slash menus when quick actions load (#9517)
Frezc23f6bb907b3f
diff --git a/packages/views/editor/content-editor-quick-actions.test.tsx b/packages/views/editor/content-editor-quick-actions.test.tsxnew file mode 100644index 0000000000..678ea497ff--- /dev/null+++ b/packages/views/editor/content-editor-quick-actions.test.tsx@@ -0,0 +1,200 @@+import type { Editor } from "@tiptap/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { ListQuickActionsResponse, QuickAction } from "@multica/core/types";+import { quickActionKeys } from "@multica/core/quick-actions";+import { renderWithI18n } from "../test/i18n";+import { NavigationProvider } from "../navigation/context";+import { useQuickActionMenu } from "../issues/hooks/use-quick-action-menu";+import { ContentEditor } from "./content-editor";++const listQuickActions = vi.hoisted(() => vi.fn());+const renderQuickAction = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@multica/core/api")>();+ return { ...actual, api: { ...actual.api, listQuickActions, renderQuickAction } };+});+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useCurrentWorkspace: () => ({ id: "ws", slug: "test" }),+ useWorkspaceSlug: () => "test",+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/test/issues/${id}` }),+}));++beforeAll(() => {+ // jsdom has no layout; ProseMirror measures the caret while opening a picker.+ const rects = () => ({+ length: 0,+ item: () => null,+ [Symbol.iterator]: function* () {},+ }) as DOMRectList;+ Range.prototype.getBoundingClientRect = () => new DOMRect();+ Range.prototype.getClientRects = rects;+ HTMLElement.prototype.getClientRects = rects;+ Object.defineProperty(Text.prototype, "getClientRects", { configurable: true, value: rects });+});++beforeEach(() => {+ listQuickActions.mockReset();+ renderQuickAction.mockReset().mockResolvedValue("Rendered feedback");+});++const clients: QueryClient[] = [];+afterEach(() => {+ cleanup();+ clients.splice(0).forEach((client) => client.clear());+});++const action: QuickAction = {+ id: "action",+ workspace_id: "ws",+ name: "delayed-feedback",+ description: "",+ assignee_type: "",+ assignee_id: "",+ prompt: "Rendered feedback",+ visibility: "public",+ status: "active",+ last_used_at: null,+ use_count: 0,+ created_by_id: "member",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ target_public: false,+ target_missing: false,+};++function pendingCatalog() {+ let resolve!: (data: ListQuickActionsResponse) => void;+ const promise = new Promise<ListQuickActionsResponse>((done) => { resolve = done; });+ listQuickActions.mockReturnValue(promise);+ return { resolve };+}++function Composer() {+ return (+ <ContentEditor+ quickActionMenu={useQuickActionMenu("issue")}+ enableSlashCommands+ slashCommandMode="command"+ showBubbleMenu={false}+ />+ );+}++async function mount(initialActions?: QuickAction[]) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ if (initialActions) {+ client.setQueryData(quickActionKeys.list("ws"), { quick_actions: initialActions });+ }+ clients.push(client);+ const result = renderWithI18n(+ <NavigationProvider value={{+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/test",+ searchParams: new URLSearchParams(),+ hash: "",+ getShareableUrl: (path) => path,+ }}>+ <QueryClientProvider client={client}><Composer /></QueryClientProvider>+ </NavigationProvider>,+ );+ const dom = await waitFor(() => {+ const el = result.container.querySelector<HTMLElement & { editor: Editor }>(".ProseMirror");+ expect(el?.editor).toBeDefined();+ return el!;+ });+ return { ...result, client, editor: dom.editor, dom };+}++async function type(editor: Editor, text: string) {+ await act(async () => {+ editor.commands.focus("end");+ // Exercise the typed-trigger guard as well as the real suggestion plugin.+ for (const ch of text) {+ const { from, to } = editor.state.selection;+ const handled = editor.view.someProp("handleTextInput", (fn) =>+ fn(editor.view, from, to, ch, () => editor.state.tr.insertText(ch, from, to)),+ );+ if (!handled) editor.view.dispatch(editor.state.tr.insertText(ch, from, to));+ }+ });+}++const menuItem = () => screen.queryByRole("button", { name: "/delayed-feedback" });++describe("comment quick-action catalog updates in the real editor", () => {+ it.each(["/", "/delayed"])(+ "refreshes %s after a delayed catalog arrives without another keystroke or editor reset",+ async (query) => {+ const pending = pendingCatalog();+ const { editor, dom } = await mount();+ await type(editor, query);+ expect(menuItem()).not.toBeInTheDocument();+ if (query === "/") expect(screen.getByRole("button", { name: /\/note/ })).toBeVisible();+ const selection = editor.state.selection.toJSON();++ await act(async () => pending.resolve({ quick_actions: [action] }));+ await waitFor(() => expect(menuItem()).toBeVisible());+ expect(dom.editor).toBe(editor);+ expect(editor.getText()).toBe(query);+ expect(editor.state.selection.toJSON()).toEqual(selection);++ fireEvent.click(menuItem()!);+ await waitFor(() => expect(editor.getText()).toBe("Rendered feedback"));+ expect(renderQuickAction).toHaveBeenCalledExactlyOnceWith("issue", "action");+ },+ );++ it("refreshes an open menu when cached actions are renamed, archived or removed", async () => {+ listQuickActions.mockResolvedValue({ quick_actions: [action] });+ const { editor, client } = await mount([action]);+ await type(editor, "/delayed");+ await waitFor(() => expect(menuItem()).toBeVisible());++ const renamed = { ...action, name: "delayed-updated" };+ await act(async () => client.setQueryData(quickActionKeys.list("ws"), { quick_actions: [renamed] }));+ await waitFor(() => expect(screen.getByRole("button", { name: "/delayed-updated" })).toBeVisible());+ expect(menuItem()).not.toBeInTheDocument();++ await act(async () => client.setQueryData(quickActionKeys.list("ws"), { quick_actions: [{ ...action, status: "archived" }] }));+ await waitFor(() => expect(screen.queryByRole("button", { name: /\/delayed/ })).not.toBeInTheDocument());+ await act(async () => client.setQueryData(quickActionKeys.list("ws"), { quick_actions: [action] }));+ await waitFor(() => expect(menuItem()).toBeVisible());+ await act(async () => client.setQueryData(quickActionKeys.list("ws"), { quick_actions: [] }));+ await waitFor(() => expect(menuItem()).not.toBeInTheDocument());+ expect(editor.getText()).toBe("/delayed");+ expect(renderQuickAction).not.toHaveBeenCalled();+ });++ it("does not reopen an escaped menu when the pending catalog arrives", async () => {+ const pending = pendingCatalog();+ const { editor, dom, client } = await mount();+ await type(editor, "/");+ expect(screen.getByRole("button", { name: /\/note/ })).toBeVisible();+ fireEvent.keyDown(dom, { key: "Escape" });+ expect(screen.queryByRole("button", { name: /\/note/ })).not.toBeInTheDocument();++ await act(async () => pending.resolve({ quick_actions: [action] }));+ await waitFor(() => expect(client.getQueryState(quickActionKeys.list("ws"))?.status).toBe("success"));+ expect(menuItem()).not.toBeInTheDocument();+ expect(editor.getText()).toBe("/");+ });++ it("cleans up an active menu when unmounted before the catalog arrives", async () => {+ const pending = pendingCatalog();+ const { editor, unmount } = await mount();+ await type(editor, "/");+ expect(screen.getByRole("button", { name: /\/note/ })).toBeVisible();+ unmount();+ await waitFor(() => expect(editor.isDestroyed).toBe(true));++ await act(async () => pending.resolve({ quick_actions: [action] }));+ expect(menuItem()).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /\/note/ })).not.toBeInTheDocument();+ });+});diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex cdafbd7534..5f3ab3815a 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -412,6 +412,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(// set is built once at mount, so a directly-captured options object would// freeze whatever closures existed then and stop seeing new quick actions.const quickActionMenuRef = useRef<BuiltinCommandSuggestionOptions | undefined>(quickActionMenu);+ const quickActionMenuListeners = useRef(new Set<() => void>());const lastEmittedRef = useRef<string | null>(null);// `content` already consumes the initial synchronized value when Tiptap// mounts. Track later changes separately so the sync effect does not parse@@ -617,6 +618,10 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(slashCommandMode,quickActionMenu: {getQuickActions: () => quickActionMenuRef.current?.getQuickActions?.() ?? [],+ subscribeQuickActions: (refresh) => {+ quickActionMenuListeners.current.add(refresh);+ return () => { quickActionMenuListeners.current.delete(refresh); };+ },renderQuickAction: (id: string) =>quickActionMenuRef.current?.renderQuickAction?.(id) ?? Promise.resolve(""),onRenderError: (error: unknown) =>@@ -690,6 +695,12 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(},});+ // Catalog queries can settle after the last keystroke. Refresh the active+ // popup without changing the document, selection or editor instance.+ useEffect(() => {+ quickActionMenuListeners.current.forEach((refresh) => refresh());+ }, [quickActionMenu]);+// Signal hosts that the deferred editor instance now exists. Fired from a// passive effect (not `onCreate`) so it runs after the commit in which// <EditorContent> attached the editor DOM — callers can measure/focus it.diff --git a/packages/views/editor/extensions/slash-command-suggestion.tsx b/packages/views/editor/extensions/slash-command-suggestion.tsxindex 02093458a5..0b5e0424f6 100644--- a/packages/views/editor/extensions/slash-command-suggestion.tsx+++ b/packages/views/editor/extensions/slash-command-suggestion.tsx@@ -319,10 +319,10 @@ export function buildBuiltinCommandItems(export interface BuiltinCommandSuggestionOptions {/*** Configured quick actions offered alongside the built-ins. Read lazily on- * every keystroke so a newly created action shows up without remounting the- * editor.+ * every keystroke and catalog notification without remounting the editor.*/getQuickActions?: () => { id: string; name: string; description?: string }[];+ subscribeQuickActions?: (refresh: () => void) => () => void;/*** Resolves a quick action to the text it would post. Server-rendered, so the* inserted body is byte-identical to what clicking the sidebar button sends.@@ -417,8 +417,11 @@ export function createBuiltinCommandSuggestion(render: createSuggestionPopupRender<SlashCommandItem, SlashCommandItem, SlashCommandListRef, SlashCommandListProps>({pluginKey,component: SlashCommandList,+ subscribe: options.subscribeQuickActions,getProps: (props) => ({- items: props.items,+ // Read the current catalog even when Tiptap finishes an older items+ // request after a catalog notification.+ items: buildBuiltinCommandItems(props.query, options.getQuickActions?.() ?? []),query: props.query,command: props.command,hideOnEmpty: true,diff --git a/packages/views/editor/extensions/suggestion-popup.tsx b/packages/views/editor/extensions/suggestion-popup.tsxindex 2afd425a57..2bf7115fba 100644--- a/packages/views/editor/extensions/suggestion-popup.tsx+++ b/packages/views/editor/extensions/suggestion-popup.tsx@@ -15,6 +15,8 @@ interface SuggestionPopupRenderOptions<pluginKey: PluginKey;component: ComponentType<TComponentProps>;getProps: (props: SuggestionProps<TItem, TSelected>) => TComponentProps;+ /** Refresh an active popup when its externally supplied catalog changes. */+ subscribe?: (refresh: () => void) => () => void;onKeyDown?: (ref: TRef | null | undefined,props: SuggestionKeyDownProps,@@ -30,6 +32,7 @@ export function createSuggestionPopupRender<pluginKey,component,getProps,+ subscribe,onKeyDown,}: SuggestionPopupRenderOptions<TItem, TSelected, TRef, TComponentProps>) {return () => {@@ -37,8 +40,13 @@ export function createSuggestionPopupRender<let popup: HTMLDivElement | null = null;let removeOutsideListeners: (() => void) | null = null;let removeAutoUpdate: (() => void) | null = null;+ let unsubscribe: (() => void) | undefined;+ let currentProps: SuggestionProps<TItem, TSelected> | null = null;const cleanup = () => {+ unsubscribe?.();+ unsubscribe = undefined;+ currentProps = null;removeOutsideListeners?.();removeOutsideListeners = null;removeAutoUpdate?.();@@ -164,6 +172,7 @@ export function createSuggestionPopupRender<return {onStart: (props: SuggestionProps<TItem, TSelected>) => {+ currentProps = props;renderer = new ReactRenderer(component, {props: getProps(props),editor: props.editor,@@ -179,9 +188,15 @@ export function createSuggestionPopupRender<installOutsideListeners(props);trackPosition(popup, props.clientRect);updatePosition(popup, props.clientRect);+ unsubscribe = subscribe?.(() => {+ if (!currentProps || !renderer) return;+ renderer.updateProps(getProps(currentProps));+ if (popup) updatePosition(popup, currentProps.clientRect);+ });},onUpdate: (props: SuggestionProps<TItem, TSelected>) => {+ currentProps = props;renderer?.updateProps(getProps(props));if (popup) {trackPosition(popup, props.clientRect);diff --git a/packages/views/issues/hooks/use-quick-action-menu.ts b/packages/views/issues/hooks/use-quick-action-menu.tsindex dd815070e7..203c611637 100644--- a/packages/views/issues/hooks/use-quick-action-menu.ts+++ b/packages/views/issues/hooks/use-quick-action-menu.ts@@ -1,6 +1,6 @@"use client";-import { useCallback, useMemo, useRef } from "react";+import { useCallback, useMemo } from "react";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";import { api } from "@multica/core/api";@@ -28,23 +28,20 @@ import { quickActionListOptions } from "@multica/core/quick-actions";export function useQuickActionMenu(issueId: string) {const workspace = useCurrentWorkspace();const wsId = workspace?.id ?? "";- const { data = [] } = useQuery({+ const { data } = useQuery({...quickActionListOptions(wsId),enabled: wsId !== "",});- // The extension reads through a getter on every keystroke; a ref keeps that- // read cheap and current without re-creating the editor.- const actionsRef = useRef<{ id: string; name: string; description?: string }[]>([]);- actionsRef.current = useMemo(+ const actions = useMemo(() =>- data+ (data ?? []).filter((a) => a.status === "active").map((a) => ({ id: a.id, name: a.name, description: a.description || undefined })),[data],);- const getQuickActions = useCallback(() => actionsRef.current, []);+ const getQuickActions = useCallback(() => actions, [actions]);const renderQuickAction = useCallback((quickActionId: string) => api.renderQuickAction(issueId, quickActionId),[issueId],