Build a Mention Autocomplete Engine
HardYou're building the mention engine behind a team chat app's compose box. When the user types @, a suggestion list opens and filters as they keep typing. The arrow keys move the highlight, Enter or Tab inserts the highlighted user as a mention, and Escape closes the list. User lookups are asynchronous and debounced.
You build the engine only, in Python. There's no UI or DOM: the engine takes text changes and key presses and exposes its state, so every behavior can be tested directly.
What's in the codebase
mention_engine.py. Where you implementMentionEngine. Its docstring holds the full contract. This is the only file you change.user_service.py. An asynchronous directory of 12 users.search_users(query)returns at most 5 users whose names contain the query as a case-insensitive substring. An empty query returns the first 5.test_runner.py. Nine tests covering triggers, insertion, dismissal, navigation, and debouncing.demo.py. Plays through a typing session so you can watch the engine's state change.instructions.md. The run commands.
The tests fail until you implement the engine.
Your task
Implement MentionEngine(user_service, debounce_ms=150) with two methods, handle_text_change(text, cursor) and handle_key(key). The engine exposes text, cursor, active, query, suggestions, and selected_index. key is one of "ArrowUp", "ArrowDown", "Enter", "Tab", and "Escape".
The engine follows these rules:
- A session starts when
@is at the start of the text or right after whitespace, and the cursor is in the query that follows it. An@inside a word, as in an email address, doesn't start one. - The query is the run of letters, digits, and underscores between the
@and the cursor. It can be empty, in which case the list shows the first 5 users. - Enter or Tab replaces the
@and the query with@Namefollowed by one space, and moves the cursor to just after it. If the character after the cursor is already a space, it's consumed, so the text never gets two spaces in a row. - Typing a space or punctuation after the query ends the session, and so does Escape.
- Lookups run after a 150 ms debounce, so a burst of keystrokes produces one lookup, for the final query. A result is applied only if its query is still current and the session is still active.
- ArrowUp and ArrowDown move
selected_indexby one and wrap at both ends. They apply only when there are suggestions. handle_keyreturnsTrueonly when an active session consumed the key.
"Hello @al", cursor 9 -> active, suggestions include Alice Enter -> "Hello @Alice ", cursor 13, inactive "Hi @al bye", cursor 6 -> Enter -> "Hi @Alice bye", cursor 10 "@a", "@al", "@ali" -> typed with no pause: one lookup, for "ali" "email@al", cursor 8 -> inactive
handle_text_change schedules its lookup with asyncio.create_task, so call it from async code. You're done when all nine tests pass.
Follow-up
Once the engine works, the interviewer adds three requirements:
- A mention is an atomic rich-text chip, not plain text. One press of Backspace deletes the whole token.
- Screen reader users need the suggestion list announced as it changes, through an ARIA live region.
- The directory has 10,000 users, not 12. The lookup, the filtering, and the rendering must stay fast at that size.
Describe how the design changes for each: where the cursor can rest relative to a chip, which changes the live region announces, and what breaks first at 10,000 users.
Using AI on this problem
This problem is usually run at the limited-context level. Use AI to check a regex for capturing @ tokens against specific inputs, or to compare your debounce with standard asyncio patterns once you've designed it. Don't have it generate the engine. The state transitions and the cursor math are what the interviewer is grading, and they're easy to get subtly wrong in generated code.
Approach
- Keep the session in five fields:
active,query,suggestions,selected_index, and a request ID that increases with every new query. - On each text change, scan back from the cursor over letters, digits, and underscores. A trigger exists if the scan stops on an
@that sits at position 0 or follows whitespace. The query is the text between the@and the cursor. No trigger deactivates the session, and an unchanged query starts no new lookup. - For each new query, schedule a task that sleeps for the debounce window and then checks its request ID. If a newer query has arrived, the task returns without calling the service. After the service call, check the request ID, the
activeflag, and the query again before applying the results. Applying results resetsselected_indexto 0. - On Enter or Tab, find the
@again by scanning back from the current cursor. Don't reuse a position stored earlier. Replace the text from the@to the cursor with the token, consume one following space if there is one, move the cursor to the end of the token, and deactivate the session.
The request ID is what makes both debouncing and stale-result handling work. A task that wakes up behind a newer query never calls the service, and a response that lands after the query has moved on never reaches suggestions.
What to focus on
- Model it as an explicit state machine. The states are idle, tracking a query, and closed by insertion or dismissal. Most mention bugs are state bugs: a list that doesn't close, or a highlight that carries into a new query.
- Treat the cursor as the source of truth. Positions move as text changes, so recompute the position of the
@at key time, from the current text and cursor. - Debounce, and drop stale responses. Debouncing waits for a pause and fires once per burst, for the final query. Throttling fires on a fixed interval during the burst, which isn't what this problem asks for. A slower response to an earlier query must not overwrite the suggestions for the current one.
- Cover the edge cases. An empty query right after the
@. An@inside an email address. A mention completed at the start of the text, at the end, and in the middle with text on both sides.
The production follow-up
Atomic chips change the text model. A plain string can't tell a mention from typed text, so store the compose box as a list of segments, plain text and mention tokens. The cursor can rest before or after a chip but never inside it, and Backspace with the cursor directly after a chip removes the whole segment.
The live region should announce the number of results when the list opens or its contents change, and the highlighted user when the selection moves. Announcing on every keystroke floods a screen reader, so announce after results apply, not while the user types.
At 10,000 users, filtering on the client and rendering every match break first. Move search to a server-side prefix index, cap the number of results, cancel in-flight requests so only the latest query's response is used, and render only the visible rows of the list.
Leveling signals
Related questions
Design autocomplete.Related courses

