The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): surface native OS notification on Kanban task completion
nductiena30636f8174a
diff --git a/apps/desktop/src/plugins/kanban/api.ts b/apps/desktop/src/plugins/kanban/api.tsindex 16403bbc4ee..1b21ec51c50 100644--- a/apps/desktop/src/plugins/kanban/api.ts+++ b/apps/desktop/src/plugins/kanban/api.ts@@ -11,6 +11,8 @@import { atom, type PluginRestOptions, type PluginStorage, queryClient } from '@hermes/plugin-sdk'+// P6B1 N2 — native completion notification (LOCAL_PATCH_UNTIL_UPSTREAM).+import { bindCompletionNotify, type CompletionEvent, onKanbanEventsFrame } from './completion-notify'import type {BoardMeta,BoardsResponse,@@ -52,7 +54,7 @@ const COLLAPSED_KEY = 'collapsedLanes'* each touched task's detail. The polls (8s board / 4s drawer) stay as the* fallback — the socket just makes the board feel instant. */function onEventsFrame(slug: string, data: unknown): void {- const events = (data as { events?: Array<{ task_id?: string }> })?.events+ const events = (data as { events?: CompletionEvent[] })?.eventsif (!events?.length) {return@@ -65,6 +67,10 @@ function onEventsFrame(slug: string, data: unknown): void {for (const taskId of new Set(events.map(event => event.task_id).filter(Boolean))) {void queryClient.invalidateQueries({ queryKey: taskKey(slug, taskId!) })}++ // P6B1 N2 — completion notification (after invalidation so notify failure+ // never interferes with cache invalidation).+ void onKanbanEventsFrame(slug, events).catch(() => undefined)}// A persisted, subscribable atom (the structural slice we need — avoids@@ -81,6 +87,7 @@ interface Persisted<T> {* handshake, so a board switch closes + reopens it. */export function bindApi(r: Rest, storage: PluginStorage, socket: Socket): () => void {rest = r+ bindCompletionNotify(r)const unsubs: Array<() => void> = []// Hydrate an atom from storage and keep storage in sync with it.diff --git a/apps/desktop/src/plugins/kanban/completion-notify.test.ts b/apps/desktop/src/plugins/kanban/completion-notify.test.tsnew file mode 100644index 00000000000..ff8ddc0632a--- /dev/null+++ b/apps/desktop/src/plugins/kanban/completion-notify.test.ts@@ -0,0 +1,378 @@+/**+ * P6B1 N2 — focused tests for the completion-notify POC.+ *+ * Each test starts from a FRESH module instance (vi.resetModules + dynamic+ * import) so the in-memory per-board cursor and rest binding match a fresh+ * renderer process. The @hermes/plugin-sdk host is mocked: notify/navigate+ * calls are asserted, never really executed.+ */++import type { PluginRestOptions } from '@hermes/plugin-sdk'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type { CompletionEvent } from './completion-notify'++/** Mirrors the module's public surface (no `typeof import()` — repo eslint+ * bans import() in type annotations). */+type Rest = <T>(path: string, opts?: PluginRestOptions) => Promise<T>+interface Mod {+ bindCompletionNotify: (r: Rest) => void+ onKanbanEventsFrame: (slug: string, events?: CompletionEvent[]) => Promise<boolean>+}++const { hostMock } = vi.hoisted(() => ({+ hostMock: { notify: vi.fn(), navigate: vi.fn() },+}))++vi.mock('@hermes/plugin-sdk', () => ({ host: hostMock }))++type NotifyInput = { message: string; title?: string; kind?: string; detail?: string; action?: { label: string; onClick: () => void } }+const lastNotify = (): NotifyInput => hostMock.notify.mock.calls[hostMock.notify.mock.calls.length - 1][0] as NotifyInput++/** Rest stub: GET /board resolves to the current latest_event_id. */+function makeRest(latest: () => number) {+ return vi.fn(async (path: string) => {+ if (path.startsWith('/board')) {+ return { latest_event_id: latest() }+ }++ throw new Error(`unexpected rest call: ${path}`)+ })+}++async function loadModule(): Promise<Mod> {+ vi.resetModules()++ return import('./completion-notify')+}++const ev = (id: number, kind = 'created', payload: Record<string, unknown> | null = null, taskId = `t${id}`): CompletionEvent => ({+ id,+ kind,+ task_id: taskId,+ payload,+})++beforeEach(() => {+ vi.clearAllMocks()+})++describe('authoritative baseline', () => {+ it('baselines from GET /board latest_event_id and suppresses replay history', async () => {+ const rest = makeRest(() => 100)+ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ // Replay/historical: ids <= baseline must never notify.+ const fired = await m.onKanbanEventsFrame('smoke', [ev(50, 'completed'), ev(100, 'completed')])++ expect(fired).toBe(false)+ expect(hostMock.notify).not.toHaveBeenCalled()+ expect(rest).toHaveBeenCalledWith('/board?board=smoke')+ })++ it('post-baseline completion notifies exactly once', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ const fired = await m.onKanbanEventsFrame('smoke', [+ ev(101, 'completed', { summary: 'Done', artifacts: ['/tmp/x/report.md'] }),+ ])++ expect(fired).toBe(true)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)++ // Same event delivered again (duplicate frame) must not re-notify.+ const again = await m.onKanbanEventsFrame('smoke', [ev(101, 'completed', { summary: 'Done' })])++ expect(again).toBe(false)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('duplicate ids inside one frame notify once', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [ev(101, 'completed'), ev(101, 'completed'), ev(101, 'completed')])++ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('reconnect replay dedupe: replayed history up to the cursor is suppressed', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [ev(101, 'completed'), ev(102, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(2)++ // Reconnect replays from 0: ids <= cursor are history, only 103 is new.+ await m.onKanbanEventsFrame('smoke', [ev(99, 'completed'), ev(101, 'completed'), ev(102, 'completed'), ev(103, 'completed')])++ expect(hostMock.notify).toHaveBeenCalledTimes(3)+ expect(hostMock.notify.mock.calls[2][0]).toMatchObject({ message: 't103' })+ })++ it('missed unseen event: frame arriving before the baseline resolves is classified after it', async () => {+ let resolveBoard!: (value: { latest_event_id: number }) => void++ const rest = vi.fn(async (path: string) => {+ if (path.startsWith('/board')) {+ return new Promise<{ latest_event_id: number }>(resolve => {+ resolveBoard = resolve+ })+ }++ throw new Error(`unexpected rest call: ${path}`)+ })++ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ // Fire the frame before the baseline resolves.+ const pending = m.onKanbanEventsFrame('smoke', [ev(100, 'created'), ev(105, 'completed')])+ resolveBoard({ latest_event_id: 100 })+ const fired = await pending++ expect(fired).toBe(true)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ expect(lastNotify().message).toBe('t105')+ })++ it('fresh process baseline: a new module instance re-baselines and suppresses older events', async () => {+ // First instance: baseline 100, sees 101 -> notify.+ const m1 = await loadModule()+ m1.bindCompletionNotify(makeRest(() => 100) as never)+ await m1.onKanbanEventsFrame('smoke', [ev(101, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(1)++ // "Restart": fresh module, board's MAX has advanced to 200 -> 150 is history.+ const m2 = await loadModule()+ m2.bindCompletionNotify(makeRest(() => 200) as never)+ const fired = await m2.onKanbanEventsFrame('smoke', [ev(150, 'completed')])+ expect(fired).toBe(false)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('baseline failure is fail-closed: unknown baseline suppresses, later success binds', async () => {+ let failBoard = true++ const rest = vi.fn(async (path: string) => {+ if (path.startsWith('/board')) {+ if (failBoard) {throw new Error('board unavailable')}++ return { latest_event_id: 200 }+ }++ throw new Error(`unexpected rest call: ${path}`)+ })++ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ const fired1 = await m.onKanbanEventsFrame('smoke', [ev(150, 'completed')])+ expect(fired1).toBe(false)+ expect(hostMock.notify).not.toHaveBeenCalled()++ // Baseline now succeeds: 150 <= 200 stays suppressed, 201 notifies.+ failBoard = false+ const fired2 = await m.onKanbanEventsFrame('smoke', [ev(150, 'completed')])+ expect(fired2).toBe(false)++ const fired3 = await m.onKanbanEventsFrame('smoke', [ev(201, 'completed')])+ expect(fired3).toBe(true)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('unbound module (no rest door) is fail-closed', async () => {+ const m = await loadModule()+ const fired = await m.onKanbanEventsFrame('smoke', [ev(101, 'completed')])+ expect(fired).toBe(false)+ expect(hostMock.notify).not.toHaveBeenCalled()+ })+})++describe('cursor advancement', () => {+ it('advances for every event kind; only completed emits', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [ev(101, 'created'), ev(102, 'assigned'), ev(103, 'status_changed')])+ expect(hostMock.notify).not.toHaveBeenCalled()++ // Cursor is at 103; a completed at 104 must still notify (cursor moved).+ const fired = await m.onKanbanEventsFrame('smoke', [ev(104, 'completed')])+ expect(fired).toBe(true)+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('malformed ids are skipped without advancing the cursor', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ const bad = { id: 'not-a-number', kind: 'completed', task_id: 'tx' } as unknown as CompletionEvent+ await m.onKanbanEventsFrame('smoke', [bad, ev(102, 'completed')])++ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ expect(lastNotify().message).toBe('t102')+ })+})++describe('board isolation', () => {+ it('never mixes cursors between boards', async () => {+ const latest = new Map<string, number>([['a', 100], ['b', 200]])++ const rest = vi.fn(async (path: string) => {+ if (path.startsWith('/board')) {+ const slug = new URLSearchParams(path.split('?')[1]).get('board') ?? ''++ return { latest_event_id: latest.get(slug) ?? 0 }+ }++ throw new Error(`unexpected rest call: ${path}`)+ })++ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ await m.onKanbanEventsFrame('a', [ev(150, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(1)++ // Same id on board b is below b's baseline -> suppressed.+ await m.onKanbanEventsFrame('b', [ev(150, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(1)+ })++ it('switch away and back reuses the prior cursor, never reset to current MAX', async () => {+ const latest = new Map<string, number>([['a', 100], ['b', 50]])++ const rest = vi.fn(async (path: string) => {+ if (path.startsWith('/board')) {+ const slug = new URLSearchParams(path.split('?')[1]).get('board') ?? ''++ return { latest_event_id: latest.get(slug) ?? 0 }+ }++ throw new Error(`unexpected rest call: ${path}`)+ })++ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ await m.onKanbanEventsFrame('a', [ev(150, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(1)++ // Away to b.+ await m.onKanbanEventsFrame('b', [ev(60, 'completed')])+ expect(hostMock.notify).toHaveBeenCalledTimes(2)++ // Back to a: replay [100..150] must be silent — cursor kept at 150,+ // and the baseline must NOT be re-fetched (no reset to current MAX).+ const fired = await m.onKanbanEventsFrame('a', [ev(100, 'completed'), ev(150, 'completed')])+ expect(fired).toBe(false)+ expect(hostMock.notify).toHaveBeenCalledTimes(2)+ const boardCalls = rest.mock.calls.filter(call => String(call[0]).startsWith('/board?board=a'))+ expect(boardCalls).toHaveLength(1)+ })+})++describe('ambiguous alias', () => {+ it("empty slug ('' = server current board) is suppressed and never queried", async () => {+ const rest = makeRest(() => 100)+ const m = await loadModule()+ m.bindCompletionNotify(rest as never)++ const fired = await m.onKanbanEventsFrame('', [ev(101, 'completed')])++ expect(fired).toBe(false)+ expect(hostMock.notify).not.toHaveBeenCalled()+ expect(rest).not.toHaveBeenCalled()+ })+})++describe('notification content', () => {+ it('zero artifacts: task identity only', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [ev(101, 'completed', { summary: 'Done', artifacts: [] })])++ expect(lastNotify()).toEqual({+ kind: 'success',+ title: 'Task completed',+ message: 'Done',+ detail: 't101',+ action: { label: 'Open Kanban', onClick: expect.any(Function) },+ })+ })++ it('one artifact: shows its basename', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [+ ev(101, 'completed', { summary: 'Done', artifacts: ['/work/x/out/report.md'] }),+ ])++ expect(lastNotify().detail).toBe('t101 · report.md')+ })++ it('multiple artifacts: "<N> artifacts"', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [+ ev(101, 'completed', { summary: 'Done', artifacts: ['/a/1.md', '/b/2.md', '/c/3.md'] }),+ ])++ expect(lastNotify().detail).toBe('t101 · 3 artifacts')+ })++ it('malformed payload does not crash: null payload, non-array artifacts, non-string summary', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [+ ev(101, 'completed', null),+ ev(102, 'completed', { summary: 42, artifacts: 'nope' }),+ ev(103, 'completed', { summary: 'ok', artifacts: [7, ' /tmp/x/ok.md ', null] }),+ ])++ // All three are unseen completions; none may throw.+ expect(hostMock.notify).toHaveBeenCalledTimes(3)+ expect(lastNotify().message).toBe('ok')+ expect(lastNotify().detail).toBe('t103 · ok.md')+ })++ it('Open Kanban action navigates to the native /kanban page', async () => {+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ await m.onKanbanEventsFrame('smoke', [ev(101, 'completed', { summary: 'Done' })])++ const input = lastNotify()+ expect(input.action?.label).toBe('Open Kanban')+ input.action?.onClick()+ expect(hostMock.navigate).toHaveBeenCalledWith('/kanban')+ })+})++describe('notification failure isolation', () => {+ it('notify throwing never rejects the frame and does not stall cursor advancement', async () => {+ hostMock.notify.mockImplementationOnce(() => {+ throw new Error('toast backend down')+ })+ const m = await loadModule()+ m.bindCompletionNotify(makeRest(() => 100) as never)++ // First completed notify throws; the frame must still resolve, and the+ // following created event must still advance the cursor.+ await expect(m.onKanbanEventsFrame('smoke', [ev(101, 'completed'), ev(102, 'created')])).resolves.toBe(false)++ // Cursor is at 102 -> a completed at 103 fires normally. The earlier+ // thrown call is still recorded, so total calls = 2.+ const fired = await m.onKanbanEventsFrame('smoke', [ev(103, 'completed')])+ expect(fired).toBe(true)+ expect(hostMock.notify).toHaveBeenCalledTimes(2)+ expect(lastNotify().message).toBe('t103')+ })+})diff --git a/apps/desktop/src/plugins/kanban/completion-notify.ts b/apps/desktop/src/plugins/kanban/completion-notify.tsnew file mode 100644index 00000000000..f03caee716d--- /dev/null+++ b/apps/desktop/src/plugins/kanban/completion-notify.ts@@ -0,0 +1,89 @@+/**+ * P6B1 N2 — native kanban task-completion notification (TEMPORARY POC).+ *+ * LOCAL_PATCH_UNTIL_UPSTREAM: no maintained exact-fit OSS exists and the SDK+ * has no kanban event door, so this module rides the kanban plugin's EXISTING+ * /events socket (api.ts onEventsFrame). No new WebSocket, no new process,+ * no DB, no auth, no persistence — cursor is an in-memory per-board high-water+ * mark. Reuses native completion finality: kind == 'completed' events written+ * by kanban_db.complete_task (payload: summary + artifacts).+ *+ * Cursor contract (P6B1 §6): first observation of a board baselines+ * seen[board] = GET /board latest_event_id (MAX task_events.id for that+ * board). Events id <= seen are historical/replay — never notified, no+ * cursor change. id > seen advances cursor for EVERY kind; only 'completed'+ * emits. Reconnect replays from 0; cursor filters. Board switch never mixes+ * cursors; returning reuses prior cursor (never reset to current MAX).+ * Fail-closed: while a board's baseline is unknown, no event can be+ * classified so none is notified. Empty slug ('') suppressed (§7).+ */++import { host, type PluginRestOptions } from '@hermes/plugin-sdk'++type Rest = <T>(path: string, opts?: PluginRestOptions) => Promise<T>++export interface CompletionEvent {+ id?: unknown+ task_id?: string+ kind?: string+ payload?: Record<string, unknown> | null+}++const seenEventIdByBoard = new Map<string, number>()+const baselinePending = new Set<string>()++let rest: Rest | null = null++export function bindCompletionNotify(r: Rest): void {+ rest = r+}++async function ensureBaseline(slug: string): Promise<void> {+ if (seenEventIdByBoard.has(slug) || baselinePending.has(slug)) { return }+ baselinePending.add(slug)++ try {+ const board = (await rest!<{ latest_event_id?: unknown }>(`/board?board=${encodeURIComponent(slug)}`)) as { latest_event_id?: unknown }+ seenEventIdByBoard.set(slug, typeof board.latest_event_id === 'number' ? board.latest_event_id : 0)+ } catch {+ // Fail-closed: unknown baseline → notifications stay suppressed.+ } finally {+ baselinePending.delete(slug)+ }+}++function notifyOne(ev: CompletionEvent): void {+ const taskId = (ev.task_id ?? '').trim()+ const summary = typeof ev.payload?.summary === 'string' ? ev.payload.summary.trim() : ''++ const artifacts = Array.isArray(ev.payload?.artifacts)+ ? (ev.payload!.artifacts as unknown[]).filter((a): a is string => typeof a === 'string' && a.trim().length > 0).map(a => a.trim())+ : []++ const artifactText = artifacts.length === 1 ? (artifacts[0].split(/[\\/]/).pop() || artifacts[0]) : artifacts.length > 1 ? `${artifacts.length} artifacts` : ''+ const detail = [taskId, artifactText].filter(Boolean).join(' · ')+ host.notify({ kind: 'success', title: 'Task completed', message: summary || taskId || 'Task completed', ...(detail ? { detail } : {}), action: { label: 'Open Kanban', onClick: () => host.navigate('/kanban') } })+}++/** Consume one /events frame for a board. Returns true when a completion+ * notification was fired. Never throws: notification failure cannot+ * interfere with api.ts cache invalidation. */+export async function onKanbanEventsFrame(slug: string, events?: CompletionEvent[]): Promise<boolean> {+ if (!events?.length || slug === '' || !rest) { return false }+ await ensureBaseline(slug)+ const seen = seenEventIdByBoard.get(slug)++ if (seen === undefined) { return false } // fail-closed+ let fired = false+ let cursor = seen++ for (const ev of events) {+ if (typeof ev.id !== 'number' || ev.id <= cursor) { continue }+ cursor = ev.id+ seenEventIdByBoard.set(slug, cursor)++ if (ev.kind === 'completed') { try { notifyOne(ev); fired = true } catch { /* swallowed */ } }+ }++ return fired+}