Skip to content
Closed
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
8 changes: 8 additions & 0 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,3 +197,11 @@ timers and mutations make). `omarchy-reminder -i` summons the
`omarchy.reminders` overlay (`shell/plugins/reminders/ReminderFlow.qml`), a
two-step minutes/message prompt that shells back out to `omarchy-reminder` to
do the setting.

## Duplicate popups

Matching live notifications share a popup with a `(2)`, `(3)`, etc. count. By default they group until that popup is dismissed or expires. Configure `notifications.deduplicationWindowMs` in `~/.config/omarchy/shell.json`: `-1` (the default) groups for the popup's lifetime, `0` disables grouping, and a positive number sets a millisecond window measured from the first arrival. For example, `"notifications": { "deduplicationWindowMs": 2000 }` limits grouping to two seconds. Changes apply to subsequent arrivals; existing groups stay intact.

Grouping compares app name, desktop-entry hint, raw title and body, urgency, and the executable-action hint. Temporary icon/image paths are not compared. Matching text can represent separate real messages, so choose a timed window or disable grouping if this is undesirable. Restored/history popups do not accept fresh members.

All members remain tracked. An update is not a new arrival: unchanged updates preserve the count, while a member whose matching content changes leaves its group and receives its own popup. Clicking invokes the first remaining member's default action; dismissing or expiring the popup closes all its members. If a sender closes a member, the count decreases and the next member supplies the action. Counts are retained in persisted popups and history, but live actions cannot survive a shell restart.
33 changes: 32 additions & 1 deletion shell/plugins/notifications/NotificationLogic.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ function snapshotOf(notification, timestamp) {
return {
id: id,
originalId: id,
duplicateCount: 1,
desktopEntry: stringHint(n.hints, "desktop-entry"),
app: n.appName || "",
appIcon: n.appIcon || "",
summary: String(n.summary || ""),
Expand All @@ -203,7 +205,7 @@ function snapshotOf(notification, timestamp) {

// Everything the popup card draws, and therefore everything an in-place
// update has to write through to the row and its file.
var POPUP_ROLES = ["app", "appIcon", "summary", "body", "image", "glyph", "execArgv", "urgency", "expireTimeout"]
var POPUP_ROLES = ["desktopEntry", "app", "appIcon", "summary", "body", "image", "glyph", "execArgv", "urgency", "expireTimeout"]

function popupRoles() {
return POPUP_ROLES
Expand Down Expand Up @@ -239,6 +241,8 @@ function historyEntry(value, normalUrgency) {
return {
id: e.id || 0,
originalId: e.originalId || e.id || 0,
duplicateCount: Math.max(1, Number(e.duplicateCount) || 1),
desktopEntry: e.desktopEntry || "",
app: e.app || "",
appIcon: e.appIcon || "",
summary: e.summary || "",
Expand Down Expand Up @@ -446,6 +450,29 @@ function historyRows(raw, liveRows, normalUrgency, limit) {
return out.slice(0, max)
}

// -1 groups until the popup leaves the screen; 0 disables grouping.
function deduplicationWindow(value) {
if (typeof value !== "number" || !isFinite(value) || value < -1) return -1
return value
}

function sameContent(a, b) {
return !!a.app && a.app === b.app && a.desktopEntry === b.desktopEntry &&
a.summary === b.summary && a.body === b.body && a.urgency === b.urgency &&
a.execArgv === b.execArgv
}

function duplicateMatches(a, b, windowMs) {
windowMs = deduplicationWindow(windowMs)
var age = b.timestamp - a.timestamp
return a.originalId !== b.originalId && windowMs !== 0 &&
(windowMs === -1 || (age >= 0 && age <= windowMs)) && sameContent(a, b)
}

function countedSummary(summary, count) {
return summary + (count > 1 ? " (" + count + ")" : "")
}

if (typeof module !== "undefined") {
module.exports = {
isChromiumDerived: isChromiumDerived,
Expand All @@ -459,6 +486,10 @@ if (typeof module !== "undefined") {
execArgvFromHints: execArgvFromHints,
parseExecArgv: parseExecArgv,
shouldRenderCompactGlyph: shouldRenderCompactGlyph,
deduplicationWindow: deduplicationWindow,
sameContent: sameContent,
duplicateMatches: duplicateMatches,
countedSummary: countedSummary,
snapshotOf: snapshotOf,
popupRoles: popupRoles,
popupRowChanged: popupRowChanged,
Expand Down
132 changes: 109 additions & 23 deletions shell/plugins/notifications/Service.qml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,74 @@ Item {
// and the next read of that role segfaults in QQmlListModel::data. A JS
// map only holds a wrapper, which degrades to a catchable error instead.
property var liveRefs: ({})
// Snapshots only: live QObject wrappers remain in liveRefs.
property var popupGroups: ({})
readonly property real deduplicationWindowMs: NotificationLogic.deduplicationWindow(
shell && shell.shellConfig && shell.shellConfig.notifications
? shell.shellConfig.notifications.deduplicationWindowMs : undefined)

function groupIndex(originalId) {
for (var i = 0; i < popupModel.count; i++) {
var members = popupGroups[NotificationLogic.popupFileName(popupModel.get(i))] || []
for (var j = 0; j < members.length; j++) {
if (members[j].originalId === originalId) return i
}
}
return -1
}

function popupRef(entry) {
if (!entry || isRestoredRow(entry)) return null
var members = popupGroups[NotificationLogic.popupFileName(entry)]
return liveRefs[members && members.length ? members[0].originalId : entry.originalId]
}

function updateGroup(index, members) {
var row = popupModel.get(index)
var entry = NotificationLogic.popupEntry(members[0], NotificationUrgency.Normal)
// Keep the file identity stable when the original representative leaves.
entry.id = row.id
entry.originalId = row.originalId
entry.timestamp = row.timestamp
entry.duplicateCount = members.length
popupGroups[NotificationLogic.popupFileName(row)] = members
var roles = NotificationLogic.popupRoles().concat(["duplicateCount"])
for (var r = 0; r < roles.length; r++) popupModel.setProperty(index, roles[r], entry[roles[r]])
persistPopupFile(entry)
}

function detachMember(originalId) {
var index = groupIndex(originalId)
if (index < 0) return
var row = popupModel.get(index)
var key = NotificationLogic.popupFileName(row)
var members = popupGroups[key].filter(function(member) { return member.originalId !== originalId })
if (members.length) updateGroup(index, members)
else {
delete popupGroups[key]
archivePopupFileFor(row)
popupModel.remove(index)
}
}

function insertGrouped(snapshot) {
for (var i = 0; i < popupModel.count; i++) {
var row = popupModel.get(i)
var key = NotificationLogic.popupFileName(row)
var members = popupGroups[key]
if (!members || !members.length) continue
if (!NotificationLogic.duplicateMatches(row, snapshot, deduplicationWindowMs)) continue
updateGroup(i, members.concat([snapshot]))
return
}
insertSingleton(snapshot)
}

function insertSingleton(snapshot) {
popupGroups[NotificationLogic.popupFileName(snapshot)] = [snapshot]
persistPopupFile(snapshot)
popupModel.insert(0, snapshot)
}

// PersistentProperties handles in-process QML reloads. The on-disk
// notifications.json file is the cross-restart backstop — its `dnd` key
Expand Down Expand Up @@ -163,8 +231,11 @@ Item {
// Guard the delete: a newer notification may have reused this originalId
// (freedesktop replaces_id) and taken over the map slot.
notification.closed.connect(function() {
if (service.liveRefs[snapshot.originalId] === notification)
delete service.liveRefs[snapshot.originalId]
if (service.liveRefs[snapshot.originalId] !== notification) return
delete service.liveRefs[snapshot.originalId]
Qt.callLater(function() {
if (!service.liveRefs[snapshot.originalId]) service.detachMember(snapshot.originalId)
})
})

// DND bypass rules: chat apps abuse urgency=critical to force
Expand All @@ -183,17 +254,17 @@ Item {
return
}

persistPopupFile(snapshot)
watchForUpdates(notification, snapshot)
// Qt.callLater avoids "QV4::Object::insertMember" crashes when a
// Repeater is mid-incubation while we mutate its model.
Qt.callLater(function() {
removePopupsByOriginalId(snapshot.originalId, NotificationLogic.popupFileName(snapshot))
popupModel.insert(0, snapshot)
if (service.liveRefs[snapshot.originalId] !== notification) return
service.detachMember(snapshot.originalId)
service.insertGrouped(NotificationLogic.replacementSnapshot(notification, snapshot.originalId, snapshot.timestamp))
// An update that arrived while the insert was deferred found no row to
// write to, and a property that already changed will not change again.
// Reading the object once the row exists catches up on it.
service.refreshPopup(notification, snapshot.originalId, snapshot.timestamp)
Qt.callLater(function() { service.refreshPopup(notification, snapshot.originalId, snapshot.timestamp) })
})
}

Expand Down Expand Up @@ -244,7 +315,9 @@ Item {
// — so nothing reaches the screen until we copy it again.
function watchForUpdates(notification, snapshot) {
function refresh() {
service.refreshPopup(notification, snapshot.originalId, snapshot.timestamp)
// A replaces_id update emits one signal per changed property. Read its
// final content once those changes have settled before splitting a group.
Qt.callLater(function() { service.refreshPopup(notification, snapshot.originalId, snapshot.timestamp) })
}

for (var i = 0; i < updateSignals.length; i++) {
Expand All @@ -266,17 +339,22 @@ Item {
return
}

var roles = NotificationLogic.popupRoles()
for (var i = 0; i < popupModel.count; i++) {
var row = popupModel.get(i)
if (!row || row.originalId !== originalId || row.timestamp !== timestamp) continue
if (!NotificationLogic.popupRowChanged(row, updated)) return
for (var r = 0; r < roles.length; r++) popupModel.setProperty(i, roles[r], updated[roles[r]])
// The file name is the timestamp and id this popup was persisted under,
// so the rewrite lands on the same file: a restart restores the version
// last shown, and so does the copy that ends up in history.
persistPopupFile(updated)
return
var index = groupIndex(originalId)
if (index < 0) return
var row = popupModel.get(index)
var members = popupGroups[NotificationLogic.popupFileName(row)]
var memberIndex = members.findIndex(function(member) { return member.originalId === originalId })
if (!NotificationLogic.popupRowChanged(members[memberIndex], updated)) return
if (members.length > 1 && !NotificationLogic.sameContent(members[memberIndex], updated)) {
// A single client changing content leaves its old group. Give the new
// card a fresh lifetime and file identity, even if it was the first member.
var nextTimestamp = Math.max(Date.now(), row.timestamp + 1)
detachMember(originalId)
updated.timestamp = nextTimestamp
insertSingleton(updated)
} else {
members[memberIndex] = updated
updateGroup(index, members)
}
}

Expand Down Expand Up @@ -326,7 +404,9 @@ Item {
// may meanwhile belong to a fresh notification — resolving liveRefs by
// id would dismiss that unrelated notification at the server.
var restored = isRestoredRow(entry)
var ref = !restored && originalId >= 0 ? liveRefs[originalId] : null
var members = !restored ? popupGroups[NotificationLogic.popupFileName(entry)] : null
var refs = members ? members.map(function(member) { return liveRefs[member.originalId] }) : [popupRef(entry)]
delete popupGroups[NotificationLogic.popupFileName(entry)]
// The popup is leaving the screen — for any reason — so its file must not
// survive to the next shell restart. It becomes the newest history entry
// instead. Rows that never had a file (a history replay, the empty-history
Expand All @@ -336,9 +416,10 @@ Item {
if (restored) delete restoredPopups[NotificationLogic.popupFileName(entry)]
}
popupModel.remove(index)
if (ref) {
for (var member = 0; member < refs.length; member++) {
var ref = refs[member]
try {
if (ref.tracked) {
if (ref && ref.tracked) {
if (reason === "expire" && typeof ref.expire === "function") ref.expire()
else ref.dismiss()
}
Expand Down Expand Up @@ -371,7 +452,7 @@ Item {
}
// Restored rows have no live actions, and looking up liveRefs by their
// old-generation id could fire an unrelated fresh notification's action.
var ref = entry && !isRestoredRow(entry) ? liveRefs[entry.originalId] : null
var ref = popupRef(entry)
var invoked = false
try {
if (ref && ref.actions) {
Expand Down Expand Up @@ -660,6 +741,8 @@ Item {
rows.push(NotificationLogic.persistablePopup({
id: row.id,
originalId: row.originalId,
duplicateCount: row.duplicateCount,
desktopEntry: row.desktopEntry,
app: row.app,
appIcon: row.appIcon,
summary: row.summary,
Expand All @@ -684,6 +767,8 @@ Item {
popupModel.insert(0, {
id: -1,
originalId: -1,
duplicateCount: 1,
desktopEntry: "",
app: "omarchy-action",
appIcon: "",
summary: "No recent notifications",
Expand Down Expand Up @@ -996,6 +1081,7 @@ Item {
required property int index
required property string app
required property string appIcon
required property int duplicateCount
required property string summary
required property string body
required property string image
Expand Down Expand Up @@ -1043,7 +1129,7 @@ Item {
anchors.right: parent.right
app: cardSlot.app
appIcon: cardSlot.appIcon
summary: cardSlot.summary
summary: NotificationLogic.countedSummary(cardSlot.summary, cardSlot.duplicateCount)
body: cardSlot.body
image: cardSlot.image
urgency: cardSlot.urgency
Expand Down
95 changes: 95 additions & 0 deletions test/shell.d/notification-deduplication-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/bin/bash
source "$(dirname "$0")/base-test.sh"
run_node_test <<'JS'
const fs = require('fs'), vm = require('vm')
const logic = requireFromRoot('shell/plugins/notifications/NotificationLogic.js')
const qml = fs.readFileSync(path.join(root, 'shell/plugins/notifications/Service.qml'), 'utf8')
const model = {
rows: [], get count() { return this.rows.length },
get(i) { return this.rows[i] }, insert(i,v) { this.rows.splice(i,0,{...v}) },
remove(i) { this.rows.splice(i,1) }, setProperty(i,k,v) { this.rows[i][k]=v }
}
const persisted = [], archived = []
const ctx = {NotificationLogic:logic, NotificationUrgency:{Normal:1}, popupModel:model,
popupGroups:{}, liveRefs:{}, restoredPopups:{}, deduplicationWindowMs:-1,
persistPopupFile(v) { persisted.push({...v}) }, archivePopupFileFor(v) { archived.push({...v}) },
Date, console}
ctx.service=ctx
vm.createContext(ctx)
for (const name of ['groupIndex','popupRef','updateGroup','detachMember','insertGrouped','insertSingleton','refreshPopup','isRestoredRow','removePopup']) {
const start=qml.indexOf(' function '+name+'('), end=qml.indexOf('\n }',start)+4
vm.runInContext(qml.slice(start,end),ctx)
}
function member(id, body='Hello',time=1000) {
const n={id,appName:'Teams',summary:'Chat',body,urgency:1,tracked:true,
dismiss(){this.tracked=false},expire(){this.tracked=false}}
ctx.liveRefs[id]=n
return logic.snapshotOf(n,time)
}
ctx.insertGrouped(member(1))
ctx.insertGrouped(member(2,'Hello',100000))
assertEqual(model.count,1,'default groups matching arrivals beyond two seconds')
assertEqual(model.get(0).duplicateCount,2,'counts distinct arrivals')
const writes=persisted.length
ctx.refreshPopup(ctx.liveRefs[2],2,100000)
assertEqual(persisted.length,writes,'unchanged updates neither increment nor rewrite')
ctx.liveRefs[2].body='Updated'
ctx.refreshPopup(ctx.liveRefs[2],2,100000)
assertEqual(model.count,2,'an updated duplicate splits into its own popup')
assertEqual(model.get(1).duplicateCount,1,'old group count decreases after split')
assertEqual(model.get(0).body,'Updated','split popup shows updated content')
ctx.insertGrouped(member(3,'Hello',200000))
ctx.liveRefs[1].body='First changed'
ctx.refreshPopup(ctx.liveRefs[1],1,1000)
assertEqual(model.count,3,'updating the original member also splits correctly')
assertEqual(ctx.popupRef(model.get(ctx.groupIndex(3))),ctx.liveRefs[3],'remaining member supplies the original group action')
ctx.insertGrouped(member(4,'Hello',300000))
const group=ctx.groupIndex(3)
ctx.removePopup(group,'dismiss')
assert(!ctx.liveRefs[3].tracked && !ctx.liveRefs[4].tracked,'dismissing a group closes every member')
ctx.deduplicationWindowMs=2000
ctx.insertGrouped(member(5,'Timed',1000));ctx.insertGrouped(member(6,'Timed',4000))
assert(ctx.groupIndex(5)!==ctx.groupIndex(6),'configured window keeps later messages separate')
ctx.deduplicationWindowMs=0
ctx.insertGrouped(member(7,'Disabled'));ctx.insertGrouped(member(8,'Disabled'))
assert(ctx.groupIndex(7)!==ctx.groupIndex(8),'zero disables grouping')
ctx.deduplicationWindowMs=-1
ctx.insertGrouped(member(11,'Closing'));ctx.insertGrouped(member(12,'Closing'))
delete ctx.liveRefs[11];ctx.detachMember(11)
assertEqual(model.get(ctx.groupIndex(12)).duplicateCount,1,'sender closure decreases the count')
assertEqual(ctx.popupRef(model.get(ctx.groupIndex(12))),ctx.liveRefs[12],'sender closure promotes the remaining live action')
ctx.removePopup(ctx.groupIndex(12),'expire')
assert(!ctx.liveRefs[12].tracked,'expiry releases the remaining member')
const restored=logic.historyEntry(member(13,'History'),1)
ctx.restoredPopups[logic.popupFileName(restored)]=true
model.insert(0,restored)
assertEqual(ctx.popupRef(restored),null,'restored ID collision cannot invoke a fresh object')
ctx.insertGrouped(member(14,'History'))
assertEqual(model.rows.filter(r=>r.body==='History').length,2,'restored popups never absorb new arrivals')
// A changed member must not inherit an older matching popup's countdown.
const oldTime=Date.now()-8000
ctx.insertGrouped(member(20,'Older match',oldTime))
ctx.insertGrouped(member(21,'New group',oldTime+7000))
ctx.insertGrouped(member(22,'New group',oldTime+7001))
const updateTime=Date.now()
ctx.liveRefs[22].body='Older match'
ctx.refreshPopup(ctx.liveRefs[22],22,oldTime+7001)
assert(ctx.groupIndex(20)!==ctx.groupIndex(22),'changed member remains separate from older matching popup')
const split=model.get(ctx.groupIndex(22))
assert(split.timestamp>=updateTime,'split receives a fresh lifetime timestamp')
assertEqual(split.duplicateCount,1,'split starts as a singleton')
assertEqual(model.get(ctx.groupIndex(20)).timestamp,oldTime,'older popup keeps its existing countdown')
ctx.removePopup(ctx.groupIndex(20),'expire')
assert(!ctx.liveRefs[20].tracked,'older matching popup expires')
assert(ctx.liveRefs[22].tracked&&ctx.groupIndex(22)>=0,'split survives older matching popup expiry')
assert(ctx.liveRefs[21].tracked&&ctx.groupIndex(21)>=0,'original group survives independently')
ctx.removePopup(ctx.groupIndex(22),'expire')
assert(!ctx.liveRefs[22].tracked,'split expires independently')
const a=member(9),b=member(10)
for (const changed of [{app:'Other'},{desktopEntry:'other'},{summary:'Different'},{body:'Different'},{urgency:2},{execArgv:'["other"]'},{originalId:9}])
assert(!logic.duplicateMatches(a,{...b,...changed},-1),'different identity/content and replacement IDs do not group')
assertEqual(logic.countedSummary('Chat',3),'Chat (3)','title shows grouped count')
assertEqual(logic.historyEntry({...a,duplicateCount:3},1).duplicateCount,3,'count survives history serialization')
assertEqual(logic.deduplicationWindow(undefined),-1,'omitted setting defaults to until dismissed')
assertEqual(logic.deduplicationWindow('bad'),-1,'invalid setting falls back safely')
JS
Loading