Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -397,22 +397,24 @@ export const buildOnChangeListner = (onTrigeer: (newValue: string, cursor: Curso
return onChangeListner;
}

export const buildCompletionSource = (getCompletions: () => CompletionItem[]) => {
return (context: CompletionContext): CompletionResult | null => {
export const buildCompletionSource = (getCompletions: () => Promise<CompletionItem[]>) => {
return async (context: CompletionContext): Promise<CompletionResult | null> => {
const textBeforeCursor = context.state.doc.toString().slice(0, context.pos);
const lastNonSpaceChar = textBeforeCursor.trimEnd().slice(-1);

const word = context.matchBefore(/\w*/);
if (!word || (word.from === word.to && !context.explicit)) {
if (lastNonSpaceChar !== '.' && (
!word || (word.from === word.to && !context.explicit)
)) {
return null;
}

const textBeforeCursor = context.state.doc.toString().slice(0, context.pos);
const lastNonSpaceChar = textBeforeCursor.trimEnd().slice(-1);

// Don't show completions for trigger characters
if (lastNonSpaceChar === '+' || lastNonSpaceChar === ':') {
if (lastNonSpaceChar === '+') {
return null;
}

const completions = getCompletions();
const completions = await getCompletions();
const prefix = word.text;
const filteredCompletions = filterCompletionsByPrefixAndType(completions, prefix);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import { EditorState } from "@codemirror/state";
import { EditorView, keymap, tooltips } from "@codemirror/view";
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useFormContext } from "../../../../../context";
import {
buildNeedTokenRefetchListner,
Expand Down Expand Up @@ -88,8 +88,9 @@ export const ChipExpressionEditorComponent = (props: ChipExpressionEditorCompone
const fieldContainerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const [isTokenUpdateScheduled, setIsTokenUpdateScheduled] = useState(true);
const completionsRef = useRef(props.completions);
const completionsRef = useRef<CompletionItem[]>(props.completions);
const helperPaneToggleButtonRef = useRef<HTMLButtonElement>(null);
const completionsFetchScheduledRef = useRef<boolean>(false);

Comment on lines +91 to 94
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid unbounded requestAnimationFrame polling when completions don’t arrive

The handshake between completionsFetchScheduledRef and waitForStateChange is generally good, but there’s a failure mode:

  • On every doc change, handleChangeListner sets completionsFetchScheduledRef.current = true.
  • waitForStateChange then recursively polls via requestAnimationFrame until completionsFetchScheduledRef.current becomes false.
  • It is set back to false only in the useEffect that mirrors props.completions into completionsRef (line 303–305).

If, for any reason, props.completions isn’t updated (backend error, RPC being disabled, or a parent component choosing not to update on certain edits), completionsFetchScheduledRef.current will stay true and:

  • waitForStateChange’s Promise will never resolve, leaving CodeMirror’s completion request hanging.
  • requestAnimationFrame(checkState) will run indefinitely every frame, which is a subtle performance leak.

Consider adding a timeout/fallback and ensuring the scheduled flag is always cleared, even on failure:

-    const waitForStateChange = (): Promise<CompletionItem[]> => {
-        return new Promise((resolve) => {
-            const checkState = () => {
-                if (!completionsFetchScheduledRef.current) {
-                    resolve(completionsRef.current);
-                } else {
-                    requestAnimationFrame(checkState);
-                }
-            };
-            checkState();
-        });
-    };
+    const waitForStateChange = (timeoutMs = 500): Promise<CompletionItem[]> => {
+        const start = performance.now();
+        return new Promise((resolve) => {
+            const checkState = () => {
+                const timedOut = performance.now() - start > timeoutMs;
+                if (!completionsFetchScheduledRef.current || timedOut) {
+                    // On timeout, fall back to whatever completions we currently have.
+                    completionsFetchScheduledRef.current = false;
+                    resolve(completionsRef.current);
+                    return;
+                }
+                requestAnimationFrame(checkState);
+            };
+            checkState();
+        });
+    };

Additionally, make sure any completion-fetching code that can fail still drives props.completions (or explicitly flips completionsFetchScheduledRef.current back to false in its error path) so the editor doesn’t get stuck waiting.

Also applies to: 102-115, 129-145, 300-305

🤖 Prompt for AI Agents
In
workspaces/ballerina/ballerina-side-panel/src/components/editors/MultiModeExpressionEditor/ChipExpressionEditor/components/ChipExpressionEditor.tsx
around lines 91-94 (and similarly 102-115, 129-145, 300-305), the
requestAnimationFrame polling driven by completionsFetchScheduledRef can spin
forever if props.completions never updates; add a bounded timeout/fallback
inside waitForStateChange so the Promise resolves after a configurable max wait
(e.g., 500-1000ms) and ensure completionsFetchScheduledRef.current is cleared on
timeout or any error path; also update any completion-fetching error handlers to
flip completionsFetchScheduledRef.current = false so the editor never remains
stuck waiting.

const { expressionEditor } = useFormContext();
const expressionEditorRpcManager = expressionEditor?.rpcManager;
Expand All @@ -99,6 +100,7 @@ export const ChipExpressionEditorComponent = (props: ChipExpressionEditorCompone
});

const handleChangeListner = buildOnChangeListner((newValue, cursor) => {
completionsFetchScheduledRef.current = true;
props.onChange(newValue, cursor.position.to);
const textBeforeCursor = newValue.slice(0, cursor.position.to);
const lastNonSpaceChar = textBeforeCursor.trimEnd().slice(-1);
Expand All @@ -124,7 +126,22 @@ export const ChipExpressionEditorComponent = (props: ChipExpressionEditorCompone
setIsTokenUpdateScheduled(true);
});

const completionSource = buildCompletionSource(() => completionsRef.current);
const waitForStateChange = (): Promise<CompletionItem[]> => {
return new Promise((resolve) => {
const checkState = () => {
if (!completionsFetchScheduledRef.current) {
resolve(completionsRef.current);
} else {
requestAnimationFrame(checkState);
}
};
checkState();
});
};

const completionSource = useMemo(() => {
return buildCompletionSource(waitForStateChange);
}, [props.completions]);

const helperPaneKeymap = buildHelperPaneKeymap(() => helperPaneState.isOpen, () => {
setHelperPaneState(prev => ({ ...prev, isOpen: false }));
Expand Down Expand Up @@ -284,6 +301,7 @@ export const ChipExpressionEditorComponent = (props: ChipExpressionEditorCompone
// just don't touch this.
useEffect(() => {
completionsRef.current = props.completions;
completionsFetchScheduledRef.current = false;
}, [props.completions]);

useEffect(() => {
Expand Down
Loading