Skip to content

fix: stabilize tray item key to prevent position jumps on property changes - #3386

Merged
bbedward merged 6 commits into
duxlabs-dev:masterfrom
Lemon-mon-254:fix/tray-item-key-stability
Sep 25, 2026
Merged

bbedward merged 6 commits into
duxlabs-dev:masterfrom
Lemon-mon-254:fix/tray-item-key-stability

Conversation

@Lemon-mon-254

Copy link
Copy Markdown
Contributor

Problem

Tray icons (especially Fcitx) jump positions when switching windows because getTrayItemKey() uses id::tooltipTitle as the key. Fcitx5 updates tooltipTitle on input method changes, causing the key to change and fall back to end of list.

Solution

Use only id for tray item key generation. The StatusNotifierItem specification guarantees id is unique per application, making tooltipTitle redundant for key purposes.

Testing

  • Verified with Fcitx5: no position jumps when switching input methods
  • Verified with other tray apps: stable positions maintained

const itemId = item?.id || "";
return !hiddenTrayIds.includes(itemId.toLowerCase());
});
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Lets remove this function entirely and replace all of the call sites

@bbedward

Copy link
Copy Markdown
Member

/claude review and identify all of the call sites of the getTrayItemKey function

return id;
}
return `${id}::${tooltipTitle}`;
return item?.id || "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Keying on id alone reverts the fix from 67d3aa9 (system tray: use id+title as identifier, fixes #1542). SNI Id is per-application, not per-instance, so two instances of the same app (or two apps registering the same id) now collide on one key, which breaks the code below:

  • manualHiddenBarItems / visibleSortedTrayItems (L164, L187): hiding one item hides every item sharing that id, and the context-menu toggle (L1509) un/hides them all at once.
  • hiddenBarItems (L189) matches by key membership, so if one duplicate lands in autoOverflowBarItems the other one renders both in the bar and in the overflow popup.
  • moveTrayItemKeyInFullOrder (L260) uses indexOf, so dragging the second duplicate moves the first (or no-ops).

The Fcitx problem is that tooltipTitle is mutable, not that a disambiguator is wrong — dropping it trades one bug for another. Better to keep the key unique with something stable for the item's lifetime (e.g. the item's occurrence index within SystemTray.items when ids collide) instead of a property the app rewrites at runtime.

return id;
}
return `${id}::${tooltipTitle}`;
return item?.id || "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This changes the persisted key format with no migration. SessionData.hiddenTrayIds and SessionData.trayItemOrder (quickshell/Common/SessionData.qml:191-192) store these keys verbatim in session.json, and existing users have entries in the id::tooltipTitle form. After this change isHiddenTrayId("myapp::Title") never matches "myapp", so on upgrade every hidden tray item reappears in the bar and the custom tray order resets, with the stale :: entries left in session.json forever.

Worth a one-time migration (strip everything from :: on load, dedupe) when the format changes.

@claude

claude Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Claude review

Fixes a real Fcitx bug, but by dropping the disambiguator entirely it regresses duplicate-id handling and silently resets persisted tray settings.

  • Key collision for tray items sharing an id reverts 67d3aa9 / tray icons grouped together and hide all at once #1542 - hide, overflow and drag-reorder all mis-target, quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:43
  • Persisted key format changed with no migration: existing id::tooltipTitle entries in hiddenTrayIds / trayItemOrder stop matching, quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:43

Call sites of getTrayItemKey (all in quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml)

Line Context
42 definition
154, 155 sortByPreferredOrder - saved-order lookup for both sort operands
163 allSortedTrayItemKeys
164 visibleSortedTrayItems - hidden filter
183 mainBarItems model key
187 manualHiddenBarItems
188 hiddenBarItemKeys
189 hiddenBarItems
247 displayedInlineExpandedItems model key
276 promoteTrayItemToBar
295 isManualHiddenTrayItem
299, 300 isAutoOverflowTrayItem
358 finishPopupDrag
1206 overflow popup delegate itemKey
1509 context-menu visibility toggle

Two more places build the same key inline and would need to stay in sync if the helper is inlined per @bbedward's request: quickshell/Common/TrayMenuManager.qml:38-42 (findTrayItem, still accepts both forms so IPC keeps working) and quickshell/DMSShellIPC.qml:2088-2090 (tray list still prints id::title).

Checked: full diff, every call site above, key persistence in SessionData/SessionSpec, and the IPC/TrayMenuManager key builders. Model: claude-opus-5.

@Lemon-mon-254
Lemon-mon-254 force-pushed the fix/tray-item-key-stability branch from eb042a2 to 8dd2a4c Compare September 11, 2026 07:32
@Lemon-mon-254

Copy link
Copy Markdown
Contributor Author

The previous approach (using plain id as the key) had clear downsides: it regressed duplicate-id disambiguation (#1542) and invalidated persisted id::tooltipTitle entries. This revision keeps getTrayItemKey() unchanged and only makes persisted-key lookups tolerant of dynamic tooltipTitle:

  • Added resolveOrderIndex() to sortByPreferredOrder(): exact key match first; prefix matching against id::* entries only when the id is a single instance (keeps Fcitx's position stable while its tooltipTitle changes — old Fcitx::… data still resolves).
  • Added findSavedTrayKey() / isTrayIdHidden() to replace all direct SessionData.isHiddenTrayId() calls (visibleSortedTrayItems, manualHiddenBarItems, promoteTrayItemToBar, isManualHiddenTrayItem, context-menu visibility toggle), and showTrayId() is now called with the actual saved key.
  • Prefix fallback is gated by trayItemCountForId() to single-instance ids only; multiple instances sharing an id always use exact matching, so hiding/ordering one never affects the others.

Existing persisted data keeps matching on read — no migration needed.

Verified locally against the live session.json: Fcitx position stays stable across input-method switches, and hiding one of three duplicate-id items leaves the other two untouched.

@Lemon-mon-254

Copy link
Copy Markdown
Contributor Author

@bbedward Updated. getTrayItemKey() is back to untouched — no duplicate-id/key-format regressions. Lookups now exact-match first, prefix-match id::* only for single-instance ids, so Fcitx stays put when tooltipTitle changes. Would appreciate a fresh look.

@bbedward

Copy link
Copy Markdown
Member

/claude review

const id = key.includes("::") ? key.split("::")[0] : key;
if (root.trayItemCountForId(id) > 1)
return null;
return list.filter(saved => saved === id || saved.startsWith(id + "::"))[0] || null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The ambiguity guard here only counts live items, not saved entries, so it misses the case where several stored keys share one id. resolveOrderIndex bails on that (L66-67) but this just takes [0].

Two instances of one app (the #1542 case), both hidden → hiddenTrayIds = ["foo::A", "foo::B"]. One instance exits, so trayItemCountForId("foo") === 1 and the fallback turns on for the survivor foo::B: the first unhide removes foo::B, then isTrayIdHidden prefix-matches the leftover foo::A and the item stays hidden — the user has to click unhide twice. Same leftover also makes a never-hidden survivor vanish from the bar.

Mirroring the order-lookup guard fixes it:

Suggested change
return list.filter(saved => saved === id || saved.startsWith(id + "::"))[0] || null;
const matches = list.filter(saved => saved === id || saved.startsWith(id + "::"));
return matches.length === 1 ? matches[0] : null;

@claude

claude Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Claude review

Much better than the previous revision — getTrayItemKey() is untouched, so the duplicate-id and persisted-format regressions from the last round are gone. One hole left in the new fallback.

  • findSavedTrayKey ambiguity guard counts live items but not saved entries, so a leftover id::* entry keeps a tray item hidden after unhide (and can hide an item the user never hid), quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:82

Checked: all 4 new helpers, every getTrayItemKey/hidden/order call site, the write path (hideTrayId/showTrayId/setTrayItemOrder in SessionData), persisted-key compatibility, and Map destructuring support in the QML engine (already used in CompositorService.qml:490). Order lookup via resolveOrderIndex looks correct — exact match first, prefix fallback only for single-instance ids, ambiguity bails to end-of-list which matches the old not-found behaviour. Model: claude-opus-5.

@bbedward

Copy link
Copy Markdown
Member

/claude review

function isTrayIdHidden(key) {
if (SessionData.isHiddenTrayId(key))
return true;
return !!findSavedTrayKey(key, SessionData.hiddenTrayIds);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The matches.length !== 1 guard added in 4377d30 closes the two-stale-entries case, but a single leftover id::* entry still leaks onto a different instance, because nothing ever removes stale entries.

Two instances of one app (the #1542 case), both hidden → hiddenTrayIds = ["foo::A", "foo::B"]:

  1. Instance A exits. trayItemCountForId("foo") === 1, so the fallback is live for survivor foo::B.
  2. User unhides B → exact match, showTrayId("foo::B") → list is now ["foo::A"].
  3. isTrayIdHidden("foo::B") → exact miss, matches === ["foo::A"], length 1 → hidden again. The user has to click unhide a second time.

Same leftover also hides an instance the user never hid: hiddenTrayIds = ["foo::A"], A exits, surviving foo::B prefix-matches and vanishes from the bar.

Fixing the guard alone can't cover this — the stale entry has to go away. Self-heal on resolve: when findSavedTrayKey returns a key that isn't the exact one, rewrite that entry to the current key (showTrayId(savedKey) + hideTrayId(key), or a single hiddenTrayIds splice) so at most one entry per id survives and the unhide in step 2 is final.

@claude

claude Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

Claude review

Ordering fallback looks right now; the stale-entry hole in the hidden-state fallback is narrower than last round but not closed.

  • A single leftover id::* entry still leaks onto a different instance — unhide has to be clicked twice, and a never-hidden survivor can vanish from the bar, quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:91

Checked: resolveOrderIndex ambiguity bail (correct — exact match first, prefix only for single-instance ids, ambiguous falls back to end-of-list like the old not-found path), all 4 helpers, every isHiddenTrayId/showTrayId/hideTrayId call site in the file (all converted, none left raw), SessionData.hideTrayId/showTrayId/setTrayItemOrder write paths, persisted-key compatibility with existing session.json, and no other QML consumer of hiddenTrayIds/trayItemOrder. getTrayItemKey() is untouched, so no key-format or duplicate-id regression. Model: claude-opus-5.

@Lemon-mon-254

Copy link
Copy Markdown
Contributor Author

getTrayItemKey now returns the plain id for single-instance items, and id::<occurrenceIndex> when ids collide.

Verified locally with simulated SNI instances: single-instance key stays stable under changing tooltips; duplicate ids get independent ::0/::1; leftover duptest no longer hides a survivor; migration normalizes Fcitx::… → Fcitx.

Revert the earlier simplistic key approach: keep getTrayItemKey()
unchanged (id::tooltipTitle) so duplicate-id disambiguation (duxlabs-dev#1542)
is preserved and persisted id::tooltipTitle entries keep matching.

Instead make persisted-key lookups tolerant of dynamic tooltipTitle:
resolveOrderIndex() in sortByPreferredOrder() does exact match first,
falling back to prefix matching an id::* entry only when the id has a
single instance. findSavedTrayKey()/isTrayIdHidden() replace direct
SessionData.isHiddenTrayId() calls and showTrayId() now receives the
actual saved key.

Prefix fallback is gated by trayItemCountForId() to single-instance
ids only, so multiple items sharing an id always match exactly and
hiding/ordering one never affects the others.
@bbedward

Copy link
Copy Markdown
Member

/claude review

const tooltipTitle = item?.tooltipTitle || "";
if (!tooltipTitle || tooltipTitle === id) {
if (!id)
return "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The key form depends on how many instances are live right now, so an item's key changes when a sibling appears or exits — the item itself didn't change, but its persisted order/hidden state stops matching.

  1. One instance of foo; user drags it to position 1 → trayItemOrder contains "foo", hide state "foo".
  2. A second instance of foo starts. Both items now key as foo::0 / foo::1, neither matches the saved "foo" → resolveOrderIndex misses for both, so the original item jumps to the end of the bar (10000 + index), and if it was hidden it pops back into the bar.
  3. The second instance exits → keys collapse back to "foo" and the old state resurrects, while any foo::N entries written in between are stale forever.

The occurrence index also shifts on exit: with foo::0/foo::1 hidden as foo::1, when instance 0 quits the survivor becomes "foo" (or with 3 instances, foo::2 becomes foo::1), so hidden/order state lands on the wrong item.

This is the same class of bug the PR is fixing — the disambiguator is derived from mutable global state instead of being stable for the item's lifetime. Assign the key once when an item first appears (keep a Map from item → key, pick the lowest free id::N among live keys, drop the entry when the item goes away) so an existing item's key never changes because of a sibling.

@claude

claude Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Claude review

The Fcitx case is fixed and the migration covers the format change; the remaining hole is that the duplicate-id disambiguator is still derived from live state.

  • Tray key flips between id and id::N when a sibling instance appears/exits, so saved order and hidden state stop matching an item that never changed, quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:45

Checked: getTrayItemKey/trayItemCountForId/resolveOrderIndex/isTrayIdHidden against every call site in the file, the sort fallback (equivalent to the old orderMap.has path), the v5 migration in SessionStore.js (strip + dedupe, runs on both load paths, version bump forces a rewrite), SessionData.hideTrayId/showTrayId/setTrayItemOrder, and the unrelated id::tooltipTitle builders in TrayMenuManager.qml/DMSShellIPC.qml (unchanged, pre-existing). Model: claude-opus-5.

@Lemon-mon-254
Lemon-mon-254 force-pushed the fix/tray-item-key-stability branch 2 times, most recently from ac49f19 to 00c9b02 Compare September 22, 2026 10:35
@bbedward

Copy link
Copy Markdown
Member

/claude review

@claude

claude Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

Claude review

No new issues found. The head (00c9b02) hasn't changed since the last review, so the open inline comment at SystemTrayBar.qml:43 still applies: the id / id::N key changes when a sibling instance appears or exits.

Checked: getTrayItemKey/trayItemCountForId/resolveOrderIndex/isTrayIdHidden and their call sites, the v7 strip+dedupe migration in SessionStore.js and the sessionConfigVersion bump, SessionData hide/show/order writers, and the IPC tray paths (TrayMenuManager.findTrayItem, DMSShellIPC list/menu). Those look items up by id/tooltip directly, not through the bar key, so the format change doesn't affect them. Model: claude-opus-5-5.

@hthienloc

Copy link
Copy Markdown
Member

/claude review

count++;
}
return `${id}::${tooltipTitle}`;
const key = count === 0 ? id : `${id}::${count}`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The suffix is the number of keyed siblings, not the lowest free suffix, so an item can get a key another live item already holds once an earlier instance exits.

  1. Instance A gets foo, instance B gets foo::1.
  2. A exits and its map entry is dropped. B keeps foo::1.
  3. A new instance C starts. It has one keyed sibling (B), so count === 1 and C also gets foo::1.

Now B and C share a key, which brings back the #1542 problems: hiding one hides both, hiddenBarItems shows one of them in both the bar and the overflow, and dragging uses indexOf on the key so it moves the wrong item.

Fix: collect the keys of live siblings and pick the first free one:

const taken = new Set();
for (const live of root.allTrayItems) {
    if (live !== item && (live?.id || "") === id && root._trayKeyByItem.has(live))
        taken.add(root._trayKeyByItem.get(live));
}
let key = id;
for (let n = 1; taken.has(key); n++)
    key = `${id}::${n}`;

@claude

claude Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Claude review

Pinning the key per item fixes the flip when a sibling comes or goes, but choosing the suffix by counting siblings can still give two live items the same key.

  • Suffix is the keyed-sibling count, not the first free one, so after an earlier instance exits a new instance can reuse a key that is still taken (for example two foo::1), quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:54

Checked: getTrayItemKey/_trayKeyByItem assignment and cleanup, resolveOrderIndex/isTrayIdHidden call sites, sort fallback, hidden/overflow key filters, and the v7 strip+dedupe migration in SessionStore.js with the sessionConfigVersion bump. Model: claude-opus-5-5.

@bbedward

Copy link
Copy Markdown
Member

/claude review

if (root._trayKeyByItem.has(item))
return root._trayKeyByItem.get(item);
const last = root._trayLastIndexById.get(id) || 0;
const key = last === 0 ? id : `${id}::${last}`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

_trayLastIndexById only goes up and nothing ever resets it, so a single-instance app that restarts during the session gets a new key and loses its saved state:

  1. nm-applet runs alone → key nm-applet, which the user has hidden or moved to position 1.
  2. It exits and restarts (a crash, an update, or an app like Fcitx restarting). The new item isn't in _trayKeyByItem, last === 1, so the key is nm-applet::1.
  3. resolveOrderIndex misses, so it jumps to the end. isTrayIdHidden misses, so a hidden icon shows up again. If the user hides it again, nm-applet::1 is saved, and after a shell restart the item keys as nm-applet again, so the entry is stale.

This is the same "state lost when the item re-registers" bug this PR is fixing. The key should be the lowest suffix not used by a live sibling (see the earlier suggestion on this function). Then drop _trayLastIndexById.

@claude

claude Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Claude review

The per-id counter fixes duplicate keys between live siblings, but it never goes down, so a single app that restarts gets a new key and loses its saved order and hidden state.

  • The counter only increases: after a restart foo becomes foo::1, the icon jumps to the end, hidden icons reappear, and the new entries are stale after a shell restart, quickshell/Modules/DankBar/Widgets/SystemTrayBar.qml:49

Checked: getTrayItemKey assignment and _trayKeyByItem cleanup, resolveOrderIndex/isTrayIdHidden call sites, the sort fallback, the hidden/overflow key filters, and the v7 strip+dedupe migration with the sessionConfigVersion bump. Model: claude-opus-5-5.

@bbedward

Copy link
Copy Markdown
Member

/claude review

@claude

claude Bot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

Claude review

No issues found. Picking the lowest free id::N among live siblings fixes both earlier issues: two live items sharing one key, and a restarted single-instance app getting a new key.

Checked: getTrayItemKey free-slot assignment and _trayKeyByItem pinning/cleanup, resolveOrderIndex/isTrayIdHidden call sites, the sort fallback, the hidden/overflow key filters, and the v7 strip+dedupe migration with the sessionConfigVersion bump. Model: claude-opus-5-5.

@bbedward
bbedward merged commit 60342b7 into duxlabs-dev:master Sep 25, 2026
2 checks passed
bbedward pushed a commit that referenced this pull request Oct 7, 2026
…anges (#3386)

* fix: keep tray order stable when tooltipTitle changes dynamically

Revert the earlier simplistic key approach: keep getTrayItemKey()
unchanged (id::tooltipTitle) so duplicate-id disambiguation (#1542)
is preserved and persisted id::tooltipTitle entries keep matching.

Instead make persisted-key lookups tolerant of dynamic tooltipTitle:
resolveOrderIndex() in sortByPreferredOrder() does exact match first,
falling back to prefix matching an id::* entry only when the id has a
single instance. findSavedTrayKey()/isTrayIdHidden() replace direct
SessionData.isHiddenTrayId() calls and showTrayId() now receives the
actual saved key.

Prefix fallback is gated by trayItemCountForId() to single-instance
ids only, so multiple items sharing an id always match exactly and
hiding/ordering one never affects the others.

* fix: bail on ambiguous saved tray keys in fallback

* tray: use occurrence index as stable key, add one-time session migration

* tray: pin stable key per item instance so it never flips when siblings come and go

* tray: assign unique per-id sequential keys to avoid collision after sibling exit

* tray: reuse free key slots so a restarted singleton keeps its plain id

(cherry picked from commit 60342b7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants