Repository navigation
feat(menu): implement context menu on right-click (#155) - #170
Conversation
Add native context menu that appears on right-click over the sprite. The menu provides access to character switching, Do Not Disturb toggle, hide, and quit. Built as a reusable component for future tray integration. - Add muda dependency for cross-platform native menus - Emit Menu verb on right-click (secondary button) over sprite - Build menu as pure function from installed characters and engine state - Show menu at cursor with blocking wait (pauses sprite while open) - Handle menu actions: switch character (stubbed for #18), toggle DND, hide (same path as hotkey), and quit Menu behaves like Poke: wakes sleeping sprite, doesn't stop walk, keeps grab during drag. Tested at Engine seam to pin this contract. - Engine: Menu verb during walk/drag behaves like Poke - Shell: Menu construction from character list (pure function) - Input: Right-click on/off sprite emits Menu/passes through Chat menu item is present but disabled until #17. Consent item (#148) is absent (not disabled) until implemented. Character switching builds and recognizes action but persistence deferred to #18. Co-authored-by: Oded Messer <odedmesser@gmail.com>
Add test to verify Menu verb aborts chase Primitive like it does for walk, maintaining the contract that Menu interrupts but doesn't stop sprite motion. Chase sets velocity each tick, so when it's aborted the last velocity persists. Co-authored-by: Oded Messer <odedmesser@gmail.com>
2e68ad6 to
c395d4a
Compare
- Add missing 'use muda::ContextMenu' import for macOS build - Fix engine access to use roster.get/get_mut instead of direct field - Apply cargo fmt formatting fixes Co-authored-by: Oded Messer <odedmesser@gmail.com>
Fix E0716 borrow checker errors in menu tests by consuming the Vec from .items() with into_iter() instead of borrowing with iter(). Co-authored-by: Oded Messer <odedmesser@gmail.com>
Store items() result in a binding to ensure the Vec lives long enough for iterator borrows. This fixes E0515 errors while avoiding the E0716 errors from the previous attempt with into_iter(). Co-authored-by: Oded Messer <odedmesser@gmail.com>
f37e15b to
00490fb
Compare
- Add set_do_not_disturb method to Instance for DND toggle - Wrap show_context_menu calls in unsafe blocks (required by muda) - Cfg-gate show_context_menu per OS (nsview/gtk_window/hwnd) - Cfg-gate ContextMenu import to macOS only - Rewrite menu tests to avoid E0515 lifetime errors by checking properties inline instead of extracting borrowed references Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Combine Menu and Poke verb handlers (both return Happened::Poke) - Add #[allow(dead_code)] to MenuAction enum (Quit used but not constructed) Co-authored-by: Oded Messer <odedmesser@gmail.com>
muda::Menu requires main thread on macOS and display on Linux. Mark all menu construction tests as ignored since they create native menus. These are verified manually instead. Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Import ContextMenu trait on Linux (not just macOS) for show_context_menu_for_gtk_window - All 6 menu tests now properly marked as #[ignore] (previous commit only had 2) Co-authored-by: Oded Messer <odedmesser@gmail.com>
Linux ContextMenu API requires >k::Window reference, not a raw pointer. Without window handle in show_and_wait, skip Linux popup. #155 targets macOS first; Linux support can follow once window threading is resolved. Co-authored-by: Oded Messer <odedmesser@gmail.com>
e507da3 to
010d164
Compare
Move muda from common dependencies to target.'cfg(target_os = "macos")' so Linux does not link libxdo-sys → -lxdo. #155 targets macOS first; Linux stub returns None. Remove unused Duration import from platform.rs. Co-authored-by: Oded Messer <odedmesser@gmail.com>
6b6821f to
da9b787
Compare
- BuiltMenu.actions HashMap now present on all platforms - Non-macOS build() creates the action map without native Menu - every_actionable_item_is_mapped no longer ignored (tests HashMap only) - Cfg-gate Duration import in platform.rs to fix unused warning Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Tests accessing built.menu are macOS-only (field doesn't exist on Linux) - every_actionable_item_is_mapped ignored on macOS (needs main thread) but runs on Linux (stub build() doesn't create native Menu) - All other menu tests are macOS-only + ignored (require main thread) Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Extract actions_for() with no muda calls, testable on all platforms - Both macOS and Linux build() use actions_for() for the HashMap - every_actionable_item_is_mapped calls actions_for() directly (no Menu) - show_and_wait() takes &BuiltMenu on both platforms - main.rs fixed to pass &built instead of &built.menu - Cfg-gate Instant import in platform.rs with Duration Co-authored-by: Oded Messer <odedmesser@gmail.com>
- show_and_wait() now returns Option<MenuAction> on both platforms - macOS: lookup action from MenuEvent.id inside show_and_wait() - Use with_id() to set muda menu item IDs matching HashMap keys - main.rs simplified: match directly on returned MenuAction - Fixes unused item_id clippy warning and Linux compile error Co-authored-by: Oded Messer <odedmesser@gmail.com>
Required for .cloned() in show_and_wait() on macOS. Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Review of the menu implementation. The structure is right in two places worth keeping: secondary_button_down uses the platform.rs seam exactly as primary_button_down does, and actions_for is a genuinely pure function that can be tested without a window. The Engine tests pinning Menu's non-interruption contract are the right instinct, and leaving the consent item absent rather than disabled is the honest call.
The rest needs work before this can ship. Grouped by severity.
Blocking: no menu item can ever fire
show_and_wait is documented as "Block until the user dismisses the menu", but it calls MenuEvent::receiver().try_recv() — non-blocking — immediately after popping the menu. It polls once, before the user could physically click, and returns None.
So Do Not Disturb, Hide, Quit, and character switching are all unreachable. The blocking behaviour the whole design rests on — "the sprite pauses because the menu blocks" — is not implemented, which also means the three Engine tests describing what happens "while the menu is open" are describing a state the code never enters.
Blocking: AppKit is called from the frame-loop thread
run_frame_loop runs inside thread::spawn, and show_and_wait is called from within that loop. macOS requires menu tracking on the main thread.
This codebase already documents the rule it is breaking. build_overlay carries "Main thread only: it builds a window and calls AppKit", and place_overlays is posted through run_on_main_thread for exactly this reason. Whatever shape the fix takes, the popup has to reach the main thread — and once it does, "block the frame loop until dismissed" stops being available as the pause mechanism, so the pause needs its own answer. That is the part worth designing before writing more code.
Also broken
- Null NSView.
show_context_menu_for_nsview(std::ptr::null_mut(), None)passes a null view into anunsafeObjC call. The doc says "shown at the given cursor position", butNoneis passed and there is no position parameter at all — so the doc describes behaviour the signature cannot deliver. - A menu per tick.
if secondary_held && over_sprite { return vec![Verb::Menu]; }ininput.rsfires on every tick the right button is held, so roughly 60 Menu verbs a second — each one runningpackage::installed, a filesystem scan, inside the 16 ms frame loop. Menu wants the press-edge treatment the other verbs get, and the character list wants reading once rather than per tick. - The drag test does not test the drag path. That early
returnskips the primary-button match, so a right-click during a drag stopsVerb::Grabbeing emitted.a_menu_during_a_drag_does_not_drop_the_spritefeeds the Engine a syntheticvec![Verb::Menu, Verb::Grab], so it asserts a contract the input layer no longer produces. Worth driving that one throughPointer::updateinstead. MenuAction::Quitis never mapped.PredefinedMenuItem::quithandles quit internally andactions_fornever inserts aquitkey, so theQuitarm inmain.rsis dead code — which is what the#[allow(dead_code)]on the enum is hiding.actions_forignores_currentand_do_not_disturb. Both parameters are unused.
The macOS gating is not justified
This is the part I would most like reconsidered, because the goal is to keep as many modules multi-platform as possible.
The module doc gives the reason plainly: "muda pulls in platform-specific dependencies (libxdo on Linux) that are not available in CI. Cfg-gate the entire implementation to macOS only." That is a CI environment gap, not a platform limitation, and it should not be encoded in the source. .github/workflows/tests.yml already installs five system packages on Linux — libwebkit2gtk-4.1-dev, libgtk-3-dev, librsvg2-dev, patchelf, libayatana-appindicator3-dev. libxdo-dev would join them the same way.
There is a second, larger problem underneath it. muda is already in Cargo.lock at 0.19.3, pulled in by tauri itself and by tray-icon. This PR adds muda = "0.16" as a second, older copy — so the binary carries two versions of the same menu library, and the MenuEvent channel this code listens on is not the one Tauri uses. That defeats this PR's own goal that "the tray (#18) can reuse it later", since tray-icon is on 0.19.
Most of this file has no OS content. Which items exist, their labels, which one is check-marked, which action each maps to — that is data. Only popping the menu touches the OS. But the #[cfg] sits on BuiltMenu, on build, on show_and_wait, and on five of the tests, so the one genuinely portable piece of logic here is tested on macOS only.
It also cuts against platform.rs, whose own doc says it exists so that an OS difference is "one edit in one file" — the convention secondary_button_down in this same PR follows correctly.
A shape that would hold:
| Layer | Content | #[cfg] |
|---|---|---|
| Menu model — items, labels, enabled, checked, action ids | pure data, tested on every platform | none |
platform::show_menu(model, at) -> Option<ActionId> |
the popup alone | macOS impl + stub, like primary_button_down |
menu.rs |
builds the model | none |
Strongly worth considering tauri::menu rather than a direct muda dependency: it re-exports Menu, MenuItem, Submenu, CheckMenuItem and PredefinedMenuItem with a popup path, which is cross-platform without a second muda, integrates with Tauri's event loop and its main-thread handling, and hands #18's tray the same objects.
Summary
Two blocking defects — no action can fire, and AppKit is called off the main thread — plus a platform gate that is at the wrong seam and brings a duplicate dependency with it. The threading model is the piece to settle first; the rest follows from it.
Happy to leave inline comments on specific hunks if that is more useful than this summary.
- Track was_secondary_held in Pointer state - Emit Verb::Menu only on secondary button down transition - Add tests: hold no-retrigger, off-sprite ignored, Menu during drag Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Collect verbs in a vec instead of early-return for Menu - Extend with gesture verbs (Grab, Poke, etc.) so both can emit - Update test to expect vec![Menu, Grab] in one tick Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Remove MenuAction::Quit (PredefinedMenuItem::quit needs no mapping) - Remove unused _current and _do_not_disturb params from actions_for - Actions are stateless; current state is only for menu item checkmarks Co-authored-by: Oded Messer <odedmesser@gmail.com>
- Add menu_pending field to InstanceState to track outstanding menus - Create channel when Menu verb first detected - Post menu popup to main thread via run_on_main_thread - Poll channel on subsequent ticks, inject Menu verb to hold instance - Extract apply_menu_action function for action handling - Frame loop never blocks waiting for menu result Co-authored-by: Oded Messer <odedmesser@gmail.com>
Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Round 2, at 4ae5484. Four things fixed, and they are fixed properly. One new problem: the branch does not compile. The two blockers from round 1 are untouched.
Fixed, and well
- Menu is the press edge.
was_secondary_heldis the right mechanism, and it mirrors howwas_heldalready works for the primary button — so the file gained a pattern rather than an exception.holding_right_button_does_not_retrigger_menupins it. This also settles the per-tick filesystem scan as a side effect:package::installednow runs once per right-click instead of sixty times a second. - Menu and Grab both survive a right-click during a drag. Dropping the early
returnand appending the gesture verbs is the correct shape, anda_right_click_during_a_drag_is_a_menunow drivesPointer::updaterather than handing the Engine a synthetic verb list. That was the specific thing I asked for, and it is what landed. MenuAction::Quitis gone, with a comment saying why Quit needs no mapping.actions_fortakes only what it uses.
New: the branch does not compile
MenuAction::Quit was removed from the enum, but main.rs still matches on it.
error[E0599]: no variant, associated function, or constant named `Quit`
found for enum `MenuAction` in the current scope
--> src-tauri/src/main.rs:652:47
cargo check -p ai-buddy at 4ae5484. The arm at main.rs:652 needs to go with the variant. Worth running cargo check locally before pushing — CI on this run had not reported yet when I looked, so this would have been caught a few minutes later either way.
Still open: the two blockers
Neither has been touched, so restating them rather than assuming they are queued.
1. No menu item can fire. menu.rs:145 is still MenuEvent::receiver().try_recv(), called immediately after the popup. It is non-blocking, so it polls once before the user could click and returns None. Do Not Disturb, Hide, and character switching remain unreachable, and the three Engine tests still describe a state the code never enters.
2. AppKit is called from the frame-loop thread. menu::show_and_wait is invoked at main.rs:630, inside the thread::spawn that starts at main.rs:467. macOS requires menu tracking on the main thread, and this repo already documents that rule at build_overlay and honours it by posting place_overlays through run_on_main_thread.
These two are one problem, which is why I would settle them together: the popup has to move to the main thread, and once it does, "block the frame loop until dismissed" is no longer available as the pause mechanism. A blocking wait on the main thread while the frame loop waits on the result is a deadlock, so the pause wants a different answer — a flag the loop reads, or the Engine gate the tests already assume — rather than a blocking call in a different place.
Also still open, and unchanged: the null NSView at menu.rs:141, the #[cfg] gating (13 of them in menu.rs, still covering the portable menu-shape logic and its tests), and muda = "0.16" duplicating Tauri's own 0.19.3.
One new nit from this round: the non-macOS build() still takes current and do_not_disturb and now uses neither, so it will warn once anything builds that path.
Where this stands
The input-layer work is done and I would keep it as is. The menu itself is not yet functional on any platform, and the threading model is still the piece to decide before more code goes in. Happy to look again on the next push.
- Remove explicit muda = "0.16" dependency - Use muda 0.19.3 that tauri already includes - Keep ContextMenu import for show_context_menu_for_nsview API - Still need: real NSView and cursor position for show_and_wait Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Round 3, at 2c64f40. The threading direction is right. The branch still does not compile, and the compiler is pointing at the design rather than at a typo.
Right call: the async shape
Moving the popup through run_on_main_thread and polling a channel instead of blocking is the correct answer, and holding the pause by re-injecting Verb::Menu while a result is outstanding is a good one — it keeps the Engine gate the tests already describe, without a blocking wait anywhere. apply_menu_action pulling the match out of the loop reads better too. Core tests pass: 351.
The branch still does not compile
error[E0277]: `Rc<muda::MenuId>` cannot be sent between threads safely
--> src-tauri/src/main.rs:688:44
error[E0277]: `Rc<RefCell<muda::platform_impl::platform::Menu>>`
cannot be sent between threads safely
--> src-tauri/src/main.rs:688:44
cargo check -p ai-buddy at 2c64f40. That is two consecutive pushes that do not build — worth a local cargo check before each one, since both were a single command away from being caught.
This one is worth reading as design feedback rather than as an error to silence. muda::Menu is Rc-based and therefore !Send. It cannot be built on the frame-loop thread and moved to the main thread, and no amount of Arc/Mutex around it will change that — the type is telling you the native menu belongs to the main thread for its whole life, construction included.
So the shape it wants is:
- The frame loop builds a plain description of the menu — labels, ids, enabled, checked. Owned
Strings andbools, soSendfor free. - That crosses to the main thread.
- The main thread constructs the native menu from it and pops it.
- Only the selected action id comes back through the channel.
Which is the model/popup split from round 1, arrived at from the other direction: the borrow checker is now making the same argument the portability concern was making. Doing it this way fixes the !Send error, un-gates the portable half, and gives #18's tray something to reuse — one change, three problems.
Still open: no menu item can fire
menu.rs was not touched this round, so show_and_wait is unchanged: it pops the menu and then calls MenuEvent::receiver().try_recv() immediately. It returns None, sends None down the new channel, and the frame loop clears menu_pending having applied nothing.
The channel refactor relocated this rather than fixing it. Note that muda's show_context_menu_for_nsview returns as soon as the menu is on screen — selections arrive on muda's global MenuEvent channel afterwards. So there is nothing to wait for at the call site, and show_and_wait is the wrong abstraction rather than a function with a bug in it.
Given the polling loop that now exists, the simplest fit: pop the menu on the main thread and have the frame loop poll MenuEvent::receiver().try_recv() each tick, mapping the event id through BuiltMenu::actions. The per-instance channel then carries nothing and can go. Using tauri::menu with on_menu_event is the other route, and would also retire the duplicate muda.
New: an instance can freeze permanently
if let Ok(action_opt) = receiver.try_recv() { ... } else { /* keep injecting Verb::Menu */ }try_recv fails two ways, and both are treated as "still waiting". If the sender is dropped without sending — run_on_main_thread returning Err (which .ok() discards), or the closure panicking before send — the receiver returns Err(Disconnected) forever. menu_pending never clears, Verb::Menu is injected on every tick from then on, and that instance is held for the rest of the session with no menu on screen.
TryRecvError::Disconnected needs to clear menu_pending the same way a result does.
Smaller
apply_menu_action(action, &mut roster, &live.id, &Arc::clone(&rules))clones theArconly to take a reference to it and drop it.&rulessays the same thing.- Unchanged from round 2: the null
NSViewatmenu.rs:141, the#[cfg]gating over the portable menu-shape logic and its tests,muda = "0.16"against Tauri's own 0.19.3, and the non-macOSbuild()taking two parameters it no longer uses.
Where this stands
The input layer is finished. The async threading shape is right and worth keeping. What remains is one structural change — build the native menu on the main thread from a plain description, and read selections from muda's global event channel — which resolves the compile error, the dead try_recv, and the portability gating together. I would do that before anything else on this branch.
- Take position as Option<(f64, f64)> and view as *mut c_void - Convert position to muda::LogicalPosition on macOS - Update docs to describe parameters - Call site passes None and null_mut() for now (ponytail: get real values) Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Round 4, at 87ae8df. Two findings addressed at the signature level. The head still does not compile, and this is the third consecutive one — that is now the thing most worth fixing, because it is hiding whether the real work landed.
Addressed
- The duplicate
mudais gone fromCargo.toml. Right call. show_and_waitnow takes a realpositionand a realviewinstead ofnull_mut()andNone. That is the null-NSView finding answered at the signature, and the doc now describes parameters that exist.
The head does not compile
error[E0432]: unresolved import `muda`
--> src-tauri/src/menu.rs:13:5
error[E0061]: this function takes 3 arguments but 1 argument was supplied
--> src-tauri/src/main.rs:689:38
error[E0433]: cannot find module or crate `muda`
--> src-tauri/src/menu.rs:145:47
cargo check -p ai-buddy at 87ae8df. Two half-finished edits: the muda dependency was removed while menu.rs:13 still imports from it, and show_and_wait grew two parameters while the only caller at main.rs:689 still passes one.
On the pattern rather than the errors. 4ae5484, 2c64f40, 1da53b01 and 87ae8df have all failed to build, each for a different reason, each catchable by the same single command:
cargo check -p ai-buddyRunning that before every push would have turned four review rounds into one. I cannot tell from a non-compiling branch whether the substantive fixes work, so the compile failures are costing more than the bugs at this point.
The central problem is unchanged after three rounds
menu.rs still ends show_and_wait with:
MenuEvent::receiver()
.try_recv()
.ok()
.and_then(|event| built.actions.get(&event.id.0).cloned())The doc above it now reads "This function blocks until the menu is dismissed". It does not block — try_recv returns immediately, before the user can click — so the comment and the code now disagree more sharply than before. No menu item can fire on any platform, which has been true since the first review.
This is worth stating plainly: there is nothing to wait for at this call site. muda's show_context_menu_for_nsview returns as soon as the menu is on screen, and selections arrive later on muda's global MenuEvent channel. A function called show_and_wait cannot be made correct by adjusting its parameters; the waiting has to move to whoever polls that channel, which is the frame loop you already gave a polling structure to.
Relatedly, the !Send error from round 3 has not been solved, only hidden by the unresolved import. BuiltMenu is still constructed on the frame-loop thread and moved into run_on_main_thread. The moment muda resolves again, E0277 comes back. The structural change is still the one to make:
- Frame loop builds a plain description — labels, ids, enabled, checked.
Stringandbool, soSend. - That crosses to the main thread.
- The main thread constructs the native menu and pops it.
- The frame loop polls for the selection and maps the id through the action table.
Switching the import to tauri::menu is what makes step 3 pleasant: Tauri's own menu types with popup_at, plus an event hook, and no muda in Cargo.toml at all — which is presumably where this round was heading when the import was left behind.
Also still open
- A dismissed channel freezes an instance.
try_recv'sErris still undifferentiated (Disconnectedappears nowhere inmain.rs), so a failedrun_on_main_threadpost leavesmenu_pendingset forever, injectingVerb::Menuevery tick for the rest of the session. - 13
#[cfg]gates inmenu.rs, still covering the portable menu-shape logic and its tests. The structural change above resolves this on its own. apply_menu_action(..., &Arc::clone(&rules))still clones anArcto borrow it.- The non-macOS
build()still takes two parameters it no longer uses.
Where this stands
The input layer is finished and good. Everything since has been moving around a single unresolved decision: where the native menu is built, and who waits for the selection. Answer that once — plain description across the thread boundary, native menu built and popped on the main thread, selection polled from the global event channel — and the compile error, the dead try_recv, the !Send problem and the platform gating all close together.
Please run cargo check -p ai-buddy before the next push.
Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Short note rather than a full round, at 88aeef9. The argument-count error is fixed — the caller now passes position and view. Two errors remain, and they are one misconception, so it is worth naming precisely:
error[E0432]: unresolved import `muda`
error[E0433]: cannot find module or crate `muda` in this scope
Tauri does not re-export the muda crate. The comment added in Cargo.toml — "tauri 2 includes muda 0.19 for menu support" — is true of Tauri's dependency tree but does not put muda in scope for this crate. Tauri depending on a crate does not make it nameable here; only a direct entry in Cargo.toml does. So use muda::… cannot resolve as things stand.
Two ways out, and they are not equal:
The one-line unblock. Add it back at Tauri's version, so Cargo unifies rather than duplicating:
muda = "0.19"That compiles, keeps one copy of muda in the binary, and leaves everything else where it is — including the !Send error from round 3, which returns the moment the import resolves.
The one that closes several findings at once. Use tauri::menu instead: tauri::menu::{Menu, MenuItem, Submenu, CheckMenuItem, PredefinedMenuItem}, built from an AppHandle, popped with popup_at, selections delivered through Tauri's own menu-event hook rather than muda's global channel. No muda in Cargo.toml at all, no raw NSView pointer, no #[cfg] needed around menu construction, and the event plumbing is the same one #18's tray will use.
The second is where I would go, and it is what the last two pushes seem to have been reaching for. It also removes the reason show_and_wait exists: with a Tauri event hook there is no channel to poll and nothing to wait for.
Everything else from round 4 stands unchanged — the dead try_recv, the !Send construction across the thread boundary, the undifferentiated Disconnected, and the 13 #[cfg] gates.
…an send A popup returns once the menu is on screen, not when it is dismissed, so a call that waited for the selection could not have one. show_and_wait is gone. menu.rs is now two halves. describe() returns a MenuDescription: owned Strings and bools for the rows, and a table saying what the clickable ones do. It is Send and it is portable, so its tests run on every platform with no cfg and nothing ignored. show() turns one into a native menu and pops it over the overlay at the cursor, and is only ever called inside run_on_main_thread - the native items are reference-counted without a lock and cannot be sent. Selections arrive on the app's menu event channel. A hook registered at startup forwards ids into a channel the frame loop drains every tick, mapping each through the holding Instance's table. The loop never blocks. The hold ends on Closed, sent after show() returns, because a menu dismissed without a choice reports nothing anywhere else. It also ends on a disconnected channel or a run_on_main_thread that failed: an Instance handed Verb::Menu every tick forever would never move again, and that outlives the failure. tauri::menu rather than muda, so the tree carries one copy of the menu library instead of two. Dropping the second copy is also what takes libxdo off the Linux link line: the binary links there without libxdo-dev. Co-authored-by: Oded Messer <odedmesser@gmail.com>
omesser
left a comment
There was a problem hiding this comment.
Round 6, at 7509823. This is the change. Every blocker is cleared, and the structure is better than what I asked for in one place.
Verified
cargo check -p ai-buddy clean
cargo clippy --all-targets -- -D warnings clean
cargo fmt --check clean
cargo test 48 shell + 351 core, 0 failed, 3 ignored
node --test tests/ 23 passed
First head on this branch that compiles, and it passes the whole gate.
What landed
The split is done properly. describe() returns a MenuDescription of plain MenuEntry rows — owned Strings and bools, Send for free, no #[cfg] anywhere in menu.rs. show() builds the native menu on the main thread from that description and pops it. The frame loop sends a description across; only ids come back. That closes the !Send error, the platform gating and the null handle in one move.
tauri::menu instead of muda. No direct muda in Cargo.toml, so one copy in the binary, and #18's tray gets the same objects. popup_menu_at on a window resolved by label — as the comment says, the runtime resolves the view it actually drew, so there is no null handle to get wrong.
Selection actually works now. on_menu_event forwards ids to the frame loop, which drains the channel each tick. The doc on show() states plainly that it returns as soon as the menu is on screen and the selection arrives later — the misunderstanding that survived five rounds is gone from the code and from the comments.
Two things better than I suggested:
MenuSignal::Closedcovers a menu dismissed without a choice. I had not thought about Escape, which fires nothing on the event channel and would otherwise have held the Instance until the timeout.MenuHold.actionskeeps the map the menu was drawn from rather than rebuilding it when the click lands, so a package installed while the menu is open cannot change what its rows do. That is a race I did not raise.
Everything else from earlier rounds: Disconnected now ends the hold with a comment naming the freeze it prevents; MENU_HOLD_TIMEOUT is a second net under the same failure; &rules no longer clones an Arc to borrow it; routing matches a click to the Instance whose hold carries the id rather than to whatever the cursor is over, which is right — the sprite is free to walk out from under its own menu.
Nine tests on describe(), all of them running on every platform now. a_character_named_like_a_row_does_not_collide_with_it is a good catch: a package named after a fixed row would otherwise steal its id.
One thing to check by hand before merging
The ordering of Chose and Closed depends on whether popup_menu_at is modal on macOS, and that decides whether a selection can be lost.
- If modal — the call returns after dismissal, so
Chosearrives first and both land in the same drain. Routing happens beforemenu_closedclears the holds, in that order, so the action applies. Correct. - If it returns immediately —
Closedlands on the next tick and clears every hold. A click arriving later findsmenu_holdempty,pickedcomes back empty, and the action is silently dropped.
The in-tick ordering is right either way, so this only bites across ticks. Worth confirming with the obvious manual test: right-click the sprite, choose Do Not Disturb, and check the buddy actually goes quiet. If it does, the popup is modal and this is settled. If the menu appears and the toggle does nothing, that is the non-modal path and Closed wants sending after the selection rather than after show() returns.
Everything else that needs a human is the list already in the PR body.
Verdict
The blockers are cleared and I have no further findings. The input layer, the description/popup split, the event plumbing and the hold all read correctly, and the tests cover the portable half on every platform. I cannot approve my own account's pull request, so treat this as the review passing rather than a green check: good to merge once the Do Not Disturb click is confirmed by hand.
Worth saying, given six rounds: the last push did in one pass what the previous four were circling, and it did it by taking the structural decision rather than adjusting around it.
The description exists so the frame loop can hand the main thread something to build a menu from. A native handle in a MenuEntry would take that away, and the symptom would be a compile error somewhere else entirely, so assert the bound where the reason for it lives. Co-authored-by: Oded Messer <odedmesser@gmail.com>
|
Round 5 answered finding by finding. I took the second option — The misconception, first, because it was mine
Correct, and that comment was the whole error. I read I also had this wrong in the PR body and have corrected it: declaring Findings
On
|
omesser
left a comment
There was a problem hiding this comment.
Round 7, at a3d2c32. One test added since the round 6 pass, and it is the right one. The pass stands.
a_description_can_be_sent_to_another_thread guards exactly the mistake that broke 2c64f40: a native handle finding its way into a MenuEntry would make the description unsendable, and there would be nothing for the main thread to build from. Asserting the Send bound makes that a build failure rather than a runtime one, and moving a real description across a thread means the bound is exercised rather than only declared. Good instinct to pin a property that has already been broken once.
Verified at this head:
cargo clippy --all-targets -- -D warnings clean
cargo fmt --check clean
cargo test 49 shell + 351 core, 0 failed, 3 ignored
node --test tests/ 23 passed
One nit, and it is only that. The test closes with:
// Chat, Character, Do Not Disturb, Hide, Quit.
assert_eq!(moved.join().expect("the thread panicked"), 5);That ties a thread-safety test to the number of rows, which the seven describe tests beside it already cover. Adding a row later fails a test named "can be sent to another thread", which sends the reader somewhere unrelated to the breakage. assert!(… > 0) would keep the point — that a real description crossed and arrived intact — without the coupling.
Nothing else has changed since round 6, so the verdict there still holds: good to merge once the Do Not Disturb click is confirmed by hand, which is the one thing that decides whether popup_menu_at is modal and therefore whether a selection can be dropped across ticks.
The test verifies MenuDescription is Send and genuinely crosses a thread boundary. Asserting the exact row count couples it to what the describe tests already own - add a row and a test named "a_description_can_be_sent_to_another_thread" breaks for an unrelated reason. Check that the moved description arrived intact (> 0) without depending on how many rows it has. Co-authored-by: Oded Messer <odedmesser@gmail.com>
The rebase onto #170 left Pointer::update with four arguments, so clippy could not compile the shell. Restore the menu drain and secondary_held from main; keep the overlay latch. Co-authored-by: Cursor <cursoragent@cursor.com>
What
Right-click on the sprite opens a native context menu at the cursor. Right-click anywhere else passes through to the desktop.
The menu is one component, built in two halves.
menu::describereturns aMenuDescription— owned Strings and bools for the rows, plus a table saying what the clickable ones do.menu::showturns one into a native menu and pops it over the overlay. The tray (#18) reuses the first half unchanged.Look
Context menu (Chat disabled, Character submenu, Do Not Disturb, Hide, Quit):
Character submenu with BMO current:
Right-click on BMO, menu, choose Do Not Disturb, menu closes (composed render of the flow, not a live capture):
v1 rows:
Engine::do_not_disturband callingset_do_not_disturb. Manual only; macOS Focus auto-detect stays Do Not Disturb: the buddy stays, and stops starting things #84.PredefinedMenuItem.Verb::Menuis the press edge of the right button over drawn pixels, and it interrupts like a Poke: a walk, a drag and a chase all continue.Why
Right-click is already a Verb (#6): the Engine emits and accepts
Menu, and nothing answered. Every recent spec needs a way in — chat (#17), Do Not Disturb (#84), character switching (#18), consent (#148) — and this is the front door.Why the menu is built on the main thread from a
Senddescription. The native menu objects are reference-counted without a lock, so a worker thread cannot hold one even for as long as it takes to hand it over. There is no version of this that builds the menu on the frame loop. So the frame loop builds a description instead — owned Strings and bools, which crosses a thread boundary — andrun_on_main_threadbuilds the real menu from it over there. The description also has no platform types in it, which is why its tests run everywhere with nocfgand nothing ignored.Why the frame loop polls the app's event channel instead of waiting for a return value. A popup returns once the menu is on screen, not when it is dismissed, so a call that waited for the selection could not have one to wait for. The click arrives later on the app's menu event channel. A hook registered at startup forwards ids into a channel the frame loop drains every tick and maps through the holding Instance's table.
Why nothing blocks. The frame loop drives every Instance. A thread parked on one buddy's menu stops all of them, and stops the hit-test that decides click-through with it.
Why the hold is released four ways. While a menu is open the frame loop re-injects
Verb::Menu, which closes the Engine's not-now gates and is what pauses the sprite. That hold ends when the menu closes; when the channel disconnects; whenrun_on_main_threadnever took the popup in the first place; and, as a backstop, on a timeout. A menu dismissed with Escape reports nothing on the event channel, and an Instance handedVerb::Menuevery tick forever would never move again — a failure that outlives whatever caused it, which is whyEmptyandDisconnectedare told apart rather than both meaning "keep waiting".Why
tauri::menurather than declaringmudadirectly. Declaringmuda = "0.19"would also have compiled, and Cargo would have unified it with Tauri's copy rather than duplicating it — the duplicate, and thelibxdoit put on the Linux link line, were specific to the old0.16pin. The reason to go throughtauri::menuinstead is that it answers several things at once: the menu is built from anAppHandle, popped withpopup_menu_atso there is no rawNSViewto get wrong, its selections arrive on the same event hook #18's tray will use, and nothing about menu construction needs a#[cfg]. Not namingmudaat all also avoids re-enabling its default features, which is wherelibxdocame from.Why Chat is listed but disabled. #17 has not shipped. The row moving later is worse than a row that cannot be clicked yet.
Why the consent row is absent rather than disabled. A disabled row promises a feature. There is nothing to promise.
How to test
Checked scenarios, all covered by tests in this branch:
hideordnddoes not collide with the row of that name.Manual, because it needs a window server and a real popup:
Notes
Rebased on main, so this carries #164's cursor awareness and chase Primitive, and pins Menu against chase as well as walk and drag.