diff --git a/README.md b/README.md index b03d8a8..8a3ac1e 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ It's for the everyday work. You can follow a standup or refinement someone's run ## Keys -Everywhere: `1` My work (with Mentions) · `2` Projects · `3`–`5` your most used projects · `/` search everything · `t` go to a ticket by its key (`TL-308` or `tl-308`) · `D` unsent drafts · `esc` or `q` back (on My work and Projects, `q` quits) · `Q` quit from anywhere · `?` your version, updates and these keys; `h` there opens the help answers. +Everywhere: `1` My work (with Mentions) · `2` Projects · `3`–`5` your most used projects · `/` search everything · `t` go to a ticket by its key (`TL-308` or `tl-308`) · `N` notifications · `D` unsent drafts · `esc` or `q` back (on My work and Projects, `q` quits) · `Q` quit from anywhere · `?` your version, updates and these keys; `h` there opens the help answers. | Screen | Keys | |---|---| @@ -59,6 +59,7 @@ Everywhere: `1` My work (with Mentions) · `2` Projects · `3`–`5` your most u | Ticket | `j`/`k` scroll · `e` edit · `m` move to a column · `c` comment · `a` assign to you (again: unassign) · `tab` pick a sub-ticket or file, `enter` open it · `o` open a picked file in your system's viewer (`xdg-open`; `open` on macOS) · `u` attach a file · `d` remove the picked file (asks first; yours, or any if you're an org admin) · `p` open the parent · `b` browse blocking tickets (project, title and open/done status; `enter` opens the selected blocker, `esc` returns) · `h` its history (everything that happened to it — columns, assignment, edits, labels, comments, files, pull requests — who did it and when; newest first. Edits to text say only that they happened) · `r` reload | | New / edit ticket | Typing is insert mode; `esc` leaves it. Then `tab` or `j`/`k` field · `i`/`enter` edit · `h`/`l` change type, priority, estimate, and spike timebox · on the due date: `h`/`l` a day, `H`/`L` a week, `x` clears · `q` cancel · `ctrl+s` save (any time) · `ctrl+o` create and attach a file (new tickets) | | Attach a file (`u`) | type or paste a path, or drop a file on the terminal · `tab` completes it (lists the choices when there are several) · `enter` uploads it with its progress · `esc` cancels the upload, or goes back. Up to 10 MB a file and 10 files a ticket; not on a done ticket. The file goes through the TrackLin.es API, so the TUI never needs the file store's key. | +| Notifications (`N`) | `j`/`k` · `enter` read it and open its ticket or board · `x` clear · `a` mark all read · `r` reload | | Drafts (`D`) | `j`/`k` · `r` send again · `x` discard · `enter` open its ticket (`c` or `e` there picks the draft up to change it first) | | Board / project | `f` follows its standup / refinement, when one's running (the banner says so) | | Following | it moves with the host: who's here, whose turn, the ticket they have open · `esc`/`q` leave | @@ -72,6 +73,7 @@ Everywhere: `1` My work (with Mentions) · `2` Projects · `3`–`5` your most u - Boards that use estimates ask for one when you create a ticket there. - **Due dates** count down by day, in your local day: "due in 3 days", "due tomorrow", "due today", then "2 days overdue" (red). They show in lists and on the ticket, and go once it's done. - Choose `spike` to set an optional timebox in days (0–60) and hours (0–23); `not set` is available for either. Changing to another type clears the timebox. +- **Notifications.** The header shows how many are unread, and `N` lists them, as the website's bell. The TUI looks for new ones every 30 seconds, even while its terminal isn't focused, and on Linux each new one also goes to the desktop through the D-Bus notification service (`notify-send`'s; nothing is sent without a session bus). An urgent one (the backend asks policy2 which are) opens the list once, on whichever client sees it first, never over something you're typing. - **Drafts.** A comment or an edit that can't be sent (the API down, the connection gone) isn't lost: it's kept in `~/.local/state/tracklines/drafts.json` (under `$XDG_STATE_HOME` if set) until it's sent or you discard it, through restarts too, and the TUI says how many are waiting when it starts. Nothing is resent on its own: `D` lists them and `r` sends one again. A comment that got through before the connection dropped isn't posted twice, and an edit to a ticket someone has changed since isn't sent over their changes: open it and `e` shows your edit with a warning, to compare and save if you still want it. - **Help answers** are the ones in the web app's help panel, written by the TrackLin.es team. They're built in, so help works offline, and the TUI checks for newer ones when it starts and every minute after, swapping them in without a restart. The latest copy is kept in `~/.local/state/tracklines/help..json` for the next start. - `m` on a backlog ticket picks a board, then a column, then an estimate if that board sizes tickets. When a move isn't allowed (a read-only key, a sprint on its last day), the TUI says why. diff --git a/go.mod b/go.mod index f99b430..d8ac428 100644 --- a/go.mod +++ b/go.mod @@ -23,6 +23,7 @@ require ( github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect github.com/go-logfmt/logfmt v0.6.1 // indirect + github.com/godbus/dbus/v5 v5.2.4 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-localereader v0.0.1 // indirect diff --git a/go.sum b/go.sum index b73faba..207873c 100644 --- a/go.sum +++ b/go.sum @@ -30,6 +30,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE= github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk= +github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U= +github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= diff --git a/internal/api/api.go b/internal/api/api.go index cef8795..94c46d1 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -124,6 +124,23 @@ type Mention struct { MentionedAt string `json:"mentioned_at"` } +// Notification is one in the bell (TL-886): read_at nil is unread; urgent ones open the notifications +// once, then shown_at is set. +type Notification struct { + ID string `json:"id"` + Kind string `json:"kind"` + Text string `json:"text"` + Actor string `json:"actor"` + TicketID *string `json:"ticket_id"` + TicketKey *string `json:"ticket_key"` + BoardID *string `json:"board_id"` + Link *string `json:"link"` + CreatedAt string `json:"created_at"` + ReadAt *string `json:"read_at"` + Urgent bool `json:"urgent"` + ShownAt *string `json:"shown_at"` +} + type Column struct { ID string `json:"id"` Name string `json:"name"` @@ -513,6 +530,38 @@ func (c *Client) Mentions(ctx context.Context) ([]Mention, error) { return out.Mentions, err } +// Notifications are yours, unread first, then newest (TL-886). +func (c *Client) Notifications(ctx context.Context) ([]Notification, error) { + var out []Notification + err := c.do(ctx, http.MethodGet, "/notifications?page=1&per_page=50", nil, &out) + return out, err +} + +func (c *Client) UnreadCount(ctx context.Context) (int, error) { + var out struct { + Count int `json:"count"` + } + err := c.do(ctx, http.MethodGet, "/notifications/unread-count", nil, &out) + return out.Count, err +} + +func (c *Client) ReadNotification(ctx context.Context, id string) error { + return c.do(ctx, http.MethodPost, "/notifications/"+url.PathEscape(id)+"/read", nil, nil) +} + +func (c *Client) ReadAllNotifications(ctx context.Context) error { + return c.do(ctx, http.MethodPost, "/notifications/read-all", nil, nil) +} + +func (c *Client) DismissNotification(ctx context.Context, id string) error { + return c.do(ctx, http.MethodDelete, "/notifications/"+url.PathEscape(id), nil, nil) +} + +// NotificationShown: an urgent one opened the notifications here, so no client does again (TL-886). +func (c *Client) NotificationShown(ctx context.Context, id string) error { + return c.do(ctx, http.MethodPost, "/notifications/"+url.PathEscape(id)+"/shown", nil, nil) +} + // Create makes a ticket at the bottom of a column (joining the board's sprint), or, with no column, // in the project's backlog. func (c *Client) Create(ctx context.Context, project, column string, in TicketInput) (Ticket, error) { diff --git a/internal/desktop/desktop.go b/internal/desktop/desktop.go new file mode 100644 index 0000000..274e8e9 --- /dev/null +++ b/internal/desktop/desktop.go @@ -0,0 +1,13 @@ +// Package desktop shows desktop notifications: on Linux through org.freedesktop.Notifications on the +// session bus (TL-886); elsewhere nothing, for now. +package desktop + +// Notifier shows one notification. Never fails the caller: no bus or no daemon is no notification. +type Notifier interface { + Notify(summary, body string, urgent bool) +} + +// None shows nothing (other systems, tests). +type None struct{} + +func (None) Notify(string, string, bool) {} diff --git a/internal/desktop/desktop_linux.go b/internal/desktop/desktop_linux.go new file mode 100644 index 0000000..5b279b1 --- /dev/null +++ b/internal/desktop/desktop_linux.go @@ -0,0 +1,42 @@ +package desktop + +import ( + "os" + "sync" + + "github.com/godbus/dbus/v5" +) + +// Session is the desktop's notification daemon, over the D-Bus session bus. +type Session struct { + once sync.Once + conn *dbus.Conn // nil: no session bus (a server, a container, SSH without one) +} + +// New is the system's notifier. +func New() Notifier { return &Session{} } + +// urgency is the freedesktop hint: 1 normal, 2 critical (stays until dismissed on most desktops). +func urgency(urgent bool) byte { + if urgent { + return 2 + } + return 1 +} + +// hints are the urgency and who sent it, as notify-send gives them. +func hints(urgent bool, pid int) map[string]dbus.Variant { + return map[string]dbus.Variant{"urgency": dbus.MakeVariant(urgency(urgent)), "sender-pid": dbus.MakeVariant(int64(pid))} +} + +func (s *Session) Notify(summary, body string, urgent bool) { + s.once.Do(func() { s.conn, _ = dbus.ConnectSessionBus() }) + if s.conn == nil { + return + } + // Notify(app_name, replaces_id, app_icon, summary, body, actions, hints, expire_timeout), sent as + // notify-send sends it: some daemons (quickshell here) didn't show one named "TrackLin.es" without sender-pid + s.conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").Call( + "org.freedesktop.Notifications.Notify", 0, "tracklines", uint32(0), "", summary, body, []string{}, + hints(urgent, os.Getpid()), int32(-1)) +} diff --git a/internal/desktop/desktop_linux_test.go b/internal/desktop/desktop_linux_test.go new file mode 100644 index 0000000..cac365e --- /dev/null +++ b/internal/desktop/desktop_linux_test.go @@ -0,0 +1,27 @@ +package desktop + +import ( + "testing" + + "github.com/godbus/dbus/v5" +) + +func TestUrgency(t *testing.T) { + if urgency(true) != 2 || urgency(false) != 1 { + t.Fatal("urgent is critical (2), the rest normal (1)") + } +} + +// As notify-send sends them: some daemons drop ones without sender-pid. +func TestHints(t *testing.T) { + h := hints(true, 42) + if h["urgency"] != dbus.MakeVariant(byte(2)) || h["sender-pid"] != dbus.MakeVariant(int64(42)) { + t.Fatalf("hints: %v", h) + } +} + +// No session bus (CI, SSH): nothing shown, nothing fails. +func TestNoBus(t *testing.T) { + t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/nonexistent") + (&Session{}).Notify("TrackLin.es", "Sam assigned you TL-1", false) +} diff --git a/internal/desktop/desktop_other.go b/internal/desktop/desktop_other.go new file mode 100644 index 0000000..a46e43a --- /dev/null +++ b/internal/desktop/desktop_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package desktop + +// New is the system's notifier: nothing yet off Linux. +// ponytail: macOS (osascript) and Windows (toast) when someone asks +func New() Notifier { return None{} } diff --git a/internal/i18n/de.go b/internal/i18n/de.go index 9b25f6c..33d0249 100644 --- a/internal/i18n/de.go +++ b/internal/i18n/de.go @@ -2,6 +2,20 @@ package i18n // de is German: English text → its translation. A missing entry shows the English (i18n_test finds it). var de = map[string]string{ + // notifications (TL-886) + "Notifications": "Benachrichtigungen", + "N %d unread": "N %d ungelesen", + "You’re all caught up.": "Du bist auf dem neuesten Stand.", + "Reminder: %s": "Erinnerung: %s", + "Someone": "Jemand", + "Cleared.": "Entfernt.", + "Couldn’t clear it": "Konnte nicht entfernt werden", + "All read.": "Alle gelesen.", + "Couldn’t mark them read": "Konnten nicht als gelesen markiert werden", + "Open it on the website: %s": "Auf der Website öffnen: %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k bewegen · enter öffnen · x entfernen · a alle gelesen · r neu laden · esc/q zurück", + "notifications (on Linux, new ones also go to the desktop)": "Benachrichtigungen (unter Linux kommen neue auch auf den Desktop)", + "open": "offen", "Blocked by": "Blockiert durch", diff --git a/internal/i18n/es.go b/internal/i18n/es.go index 0c8384b..48810d2 100644 --- a/internal/i18n/es.go +++ b/internal/i18n/es.go @@ -2,6 +2,20 @@ package i18n // es is Spanish: English text → its translation. A missing entry shows the English (i18n_test finds it). var es = map[string]string{ + // notifications (TL-886) + "Notifications": "Notificaciones", + "N %d unread": "N %d sin leer", + "You’re all caught up.": "Estás al día.", + "Reminder: %s": "Recordatorio: %s", + "Someone": "Alguien", + "Cleared.": "Quitada.", + "Couldn’t clear it": "No se pudo quitar", + "All read.": "Todas leídas.", + "Couldn’t mark them read": "No se pudieron marcar como leídas", + "Open it on the website: %s": "Ábrela en la web: %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k mover · enter abrir · x quitar · a marcar todo leído · r recargar · esc/q atrás", + "notifications (on Linux, new ones also go to the desktop)": "notificaciones (en Linux, las nuevas también van al escritorio)", + "open": "abierto", "Blocked by": "Bloqueado por", diff --git a/internal/i18n/fr.go b/internal/i18n/fr.go index a5beee2..396491a 100644 --- a/internal/i18n/fr.go +++ b/internal/i18n/fr.go @@ -2,6 +2,20 @@ package i18n // fr is French: English text → its translation. A missing entry shows the English (i18n_test finds it). var fr = map[string]string{ + // notifications (TL-886) + "Notifications": "Notifications", + "N %d unread": "N %d non lues", + "You’re all caught up.": "Vous êtes à jour.", + "Reminder: %s": "Rappel : %s", + "Someone": "Quelqu’un", + "Cleared.": "Effacée.", + "Couldn’t clear it": "Impossible de l’effacer", + "All read.": "Tout est lu.", + "Couldn’t mark them read": "Impossible de les marquer comme lues", + "Open it on the website: %s": "Ouvrez-la sur le site : %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k déplacer · entrée ouvrir · x effacer · a tout marquer lu · r recharger · échap/q retour", + "notifications (on Linux, new ones also go to the desktop)": "notifications (sous Linux, les nouvelles vont aussi sur le bureau)", + "open": "ouvert", "Blocked by": "Bloqué par", diff --git a/internal/i18n/nl.go b/internal/i18n/nl.go index 2866fad..977685e 100644 --- a/internal/i18n/nl.go +++ b/internal/i18n/nl.go @@ -2,6 +2,20 @@ package i18n // nl is Dutch: English text → Nederlands. A missing entry shows the English (i18n_test finds it). var nl = map[string]string{ + // notifications (TL-886) + "Notifications": "Meldingen", + "N %d unread": "N %d ongelezen", + "You’re all caught up.": "Je bent helemaal bij.", + "Reminder: %s": "Herinnering: %s", + "Someone": "Iemand", + "Cleared.": "Gewist.", + "Couldn’t clear it": "Kon niet wissen", + "All read.": "Alles gelezen.", + "Couldn’t mark them read": "Kon ze niet als gelezen markeren", + "Open it on the website: %s": "Open het op de website: %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k bewegen · enter openen · x wissen · a alles gelezen · r herladen · esc/q terug", + "notifications (on Linux, new ones also go to the desktop)": "meldingen (op Linux gaan nieuwe ook naar het bureaublad)", + "open": "open", "Blocked by": "Geblokkeerd door", diff --git a/internal/i18n/pt.go b/internal/i18n/pt.go index ca5df53..ef7bb81 100644 --- a/internal/i18n/pt.go +++ b/internal/i18n/pt.go @@ -2,6 +2,20 @@ package i18n // pt is Brazilian Portuguese: English text → its translation. A missing entry shows the English (i18n_test finds it). var pt = map[string]string{ + // notifications (TL-886) + "Notifications": "Notificações", + "N %d unread": "N %d não lidas", + "You’re all caught up.": "Você está em dia.", + "Reminder: %s": "Lembrete: %s", + "Someone": "Alguém", + "Cleared.": "Removida.", + "Couldn’t clear it": "Não foi possível remover", + "All read.": "Todas lidas.", + "Couldn’t mark them read": "Não foi possível marcá-las como lidas", + "Open it on the website: %s": "Abra no site: %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k mover · enter abrir · x remover · a marcar tudo lido · r recarregar · esc/q voltar", + "notifications (on Linux, new ones also go to the desktop)": "notificações (no Linux, as novas também vão para a área de trabalho)", + "open": "aberto", "Blocked by": "Bloqueado por", diff --git a/internal/i18n/tlh.go b/internal/i18n/tlh.go index 71f9700..6735ef9 100644 --- a/internal/i18n/tlh.go +++ b/internal/i18n/tlh.go @@ -2,6 +2,20 @@ package i18n // tlh is Klingon, for fun: English text → its translation. A missing entry shows the English (i18n_test finds it). var tlh = map[string]string{ + // notifications (TL-886) + "Notifications": "De’ chu’mey", + "N %d unread": "N %d De’ chu’ laDbe’lu’", + "You’re all caught up.": "Hoch DaSovta’.", + "Reminder: %s": "yIqaw: %s", + "Someone": "vay’", + "Cleared.": "teq.", + "Couldn’t clear it": "teqlaHbe’", + "All read.": "Hoch laDlu’ta’.", + "Couldn’t mark them read": "laDlu’ta’ net ghItlhlaHbe’", + "Open it on the website: %s": "Daq yIpoSmoH: %s", + "j/k move · enter open · x clear · a mark all read · r reload · esc/q back": "j/k vIH · enter poSmoH · x teq · a Hoch laD · r chu’qa’ · esc/q chegh", + "notifications (on Linux, new ones also go to the desktop)": "De’ chu’mey (Linux Daq, chu’ De’ ’oH raSDaq ghoS)", + "open": "ta’be’", "Blocked by": "botwI’", diff --git a/internal/ui/about.go b/internal/ui/about.go index 3d5c845..6f5d066 100644 --- a/internal/ui/about.go +++ b/internal/ui/about.go @@ -86,6 +86,7 @@ func (v *aboutView) render(a *app) string { {"V", T("saved views: open, save, rename or delete")}, {"ctrl+x", T("clear all filters on the current ticket list")}, {"t", T("go to a ticket by its key (TL-308)")}, + {"N", T("notifications (on Linux, new ones also go to the desktop)")}, {"D", T("unsent drafts: comments and edits that didn't reach the server")}, {"esc / q", T("back (q quits on My work and Projects)")}, {"Q", T("quit from anywhere")}, diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 56668de..c350caf 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -37,7 +37,8 @@ var ( // closed or the TUI gives up; removeForbidden: the file isn't yours to remove uploadFails, removeForbidden bool uploadHold chan struct{} - callsMu sync.Mutex // guards fakeAPI's calls while requests are in flight + fakeNotices []map[string]any // the bell's list (TL-886); unread ones have no read_at + callsMu sync.Mutex // guards fakeAPI's calls while requests are in flight ) // fakeAPI is TrackLin.es for Sam: project TL with a Web board (To do → In progress → Done, Fibonacci @@ -211,6 +212,16 @@ func fakeAPI(t *testing.T) (*Client, *[]string) { w.Header().Set("ETag", `"h2"`) out = []map[string]any{{"slug": "fresh", "question": "How do I add another board?", "answer": "From the API: Edit project → Boards.", "href": "/projects/[project]/edit", "fallback_href": "", "pages": []string{"project"}, "words": "board"}} + case p == "/api/notifications/unread-count": + n := 0 + for _, x := range fakeNotices { + if x["read_at"] == nil { + n++ + } + } + out = map[string]any{"count": n} + case p == "/api/notifications" && r.Method == http.MethodGet: + out = fakeNotices case p == "/api/assignees": out = []map[string]any{{"id": "user_1", "label": "You", "name": "Sam Doe"}, {"id": "user_2", "label": "Alex", "name": "Alex Roe"}, {"id": "Claude", "label": "Claude", "kind": "ai"}} case p == "/api/projects": diff --git a/internal/ui/notify.go b/internal/ui/notify.go new file mode 100644 index 0000000..5ce6f89 --- /dev/null +++ b/internal/ui/notify.go @@ -0,0 +1,235 @@ +package ui + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/tracklines/tui/internal/desktop" +) + +// Notifications (TL-886): the bell's list on its own screen (N), the unread count in the header, and +// each new one on the desktop too (D-Bus on Linux). An urgent one opens the screen, once on any client. + +// noticeEvery: how often the TUI asks for new ones; it keeps asking while the terminal isn't focused, +// so the desktop hears about them. +// ponytail: polled, like the website's bell; the live stream if half a minute is too slow +const noticeEvery = 30 * time.Second + +const brand = "TrackLin.es" + +type ( + noticeTick struct{} + // noticesMsg is a poll: the unread count, and the list when the count had changed + noticesMsg struct { + unread int + list []Notice + listed bool + err error + } + urgentShownMsg struct{ err error } +) + +func noticesLater() tea.Cmd { + return tea.Tick(noticeEvery, func(time.Time) tea.Msg { return noticeTick{} }) +} + +// pollNotices asks for the unread count, and for the list only when it changed since the last look. +func (a *app) pollNotices() tea.Cmd { + seen := a.unreadSeen + return func() tea.Msg { + ctx := context.Background() + n, err := a.api.UnreadCount(ctx) + if err != nil || n == seen { + return noticesMsg{unread: n, err: err} + } + list, err := a.api.Notifications(ctx) + return noticesMsg{unread: n, list: list, listed: err == nil, err: err} + } +} + +// fresh are the unread ones that arrived after since, oldest first; a burst gives its latest three. +func fresh(list []Notice, since string) []Notice { + var out []Notice + for _, n := range list { + if n.ReadAt == nil && n.CreatedAt > since { + out = append(out, n) + } + } + slices.SortFunc(out, func(x, y Notice) int { return strings.Compare(x.CreatedAt, y.CreatedAt) }) + return out[max(0, len(out)-3):] +} + +// urgentNotice is the one to open the screen for: urgent, unread, and no client has opened them for it. +func urgentNotice(list []Notice) *Notice { + for i, n := range list { + if n.Urgent && n.ReadAt == nil && n.ShownAt == nil { + return &list[i] + } + } + return nil +} + +// notices handles a poll's answer: the count, the desktop, and an urgent one. +func (a *app) notices(msg noticesMsg) tea.Cmd { + if msg.err != nil { + return nil // missing a look isn't worth showing; the next one comes soon + } + a.unread = msg.unread + if !msg.listed { + return nil + } + a.unreadSeen = msg.unread + for _, n := range fresh(msg.list, a.noticesSince) { + a.desktop.Notify(brand, a.noticeLine(n), n.Urgent) + a.noticesSince = max(a.noticesSince, n.CreatedAt) + } + u := urgentNotice(msg.list) + if u == nil { + return nil + } + if a.top().typing() { + a.unreadSeen = -1 // not over what you're writing: look again next time + return nil + } + id := u.ID + return func() tea.Msg { return urgentShownMsg{a.api.NotificationShown(context.Background(), id)} } +} + +// noticeLine is how one reads, as on the website: "Sam assigned you TL-12: Fix login". +func (a *app) noticeLine(n Notice) string { + switch { + case n.Kind == "legal" || n.Kind == "billing": // from TrackLin.es itself + return n.Text + case n.Kind == "due": + return F("Reminder: %s", n.Text) + case n.Kind == "downtime_credit": + return brand + " " + n.Text + case n.Actor == "": + return T("Someone") + " " + n.Text + } + return a.name(n.Actor) + " " + n.Text +} + +// notificationsView is the list: unread first, then newest. +type notificationsView struct { + items []Notice + loaded bool + cursor int +} + +func (v *notificationsView) load(a *app) tea.Cmd { + return fetch("notifications", func(ctx context.Context) (any, error) { return a.api.Notifications(ctx) }) +} + +func (v *notificationsView) unread() int { + n := 0 + for _, x := range v.items { + if x.ReadAt == nil { + n++ + } + } + return n +} + +func (v *notificationsView) update(a *app, msg tea.Msg) (view, tea.Cmd) { + switch msg := msg.(type) { + case loadedMsg: + if msg.tag == "notifications" { + v.items, _ = msg.data.([]Notice) + v.loaded = true + v.cursor = min(v.cursor, max(len(v.items)-1, 0)) + // ponytail: the first 50; more unread than that and the header's count is the server's again on the next poll + a.unread = v.unread() + } + case tea.KeyMsg: + k := msg.String() + if cursorKeys(k, &v.cursor, len(v.items)) { + return v, nil + } + if k == "r" { + a.loading = true + return v, v.load(a) + } + if len(v.items) == 0 { + return v, nil + } + n := v.items[v.cursor] + switch k { + case "enter": + return v, v.open(a, n) + case "x": + return v, act(T("Cleared."), T("Couldn’t clear it"), func(ctx context.Context) error { return a.api.DismissNotification(ctx, n.ID) }) + case "a": + return v, act(T("All read."), T("Couldn’t mark them read"), func(ctx context.Context) error { return a.api.ReadAllNotifications(ctx) }) + } + } + return v, nil +} + +// open marks it read and goes to its ticket or board; one about neither (the launch offer, new Terms) +// says where it is on the website. +func (v *notificationsView) open(a *app, n Notice) tea.Cmd { + var next view + switch { + case n.TicketID != nil: + next = &ticketView{id: *n.TicketID} + case n.BoardID != nil: + next = &boardView{id: *n.BoardID} + } + if n.ReadAt == nil { + now := time.Now().UTC().Format(time.RFC3339) + v.items[v.cursor].ReadAt = &now + a.unread = max(0, a.unread-1) + } + read := func() tea.Msg { + if n.ReadAt == nil { + _ = a.api.ReadNotification(context.Background(), n.ID) // ponytail: a failed read stays unread; nothing to do about it here + } + return nil + } + if next != nil { + return tea.Batch(read, msgOf(pushMsg{next})) + } + if n.Link != nil { + a.status = F("Open it on the website: %s", siteURL(a.api.Base)+*n.Link) + } + return read +} + +func (v *notificationsView) render(a *app) string { + var b strings.Builder + b.WriteString(accent.Render(T("Notifications")) + muted.Render(fmt.Sprintf(" %d", v.unread())) + "\n\n") + if !v.loaded { + return b.String() + } + if len(v.items) == 0 { + return b.String() + muted.Render(T("You’re all caught up.")) + "\n" + } + var rows []string + for _, n := range v.items { + mark, line := " ", cut(a.noticeLine(n), max(10, a.width-22)) + if n.ReadAt == nil { + mark = "● " + if n.Urgent { + line = warn.Render(line) + } + } else { + line = muted.Render(line) + } + rows = append(rows, mark+line+" "+muted.Render(when(n.CreatedAt))) + } + b.WriteString(lines(rows, v.cursor, max(1, a.rows()-2))) + return b.String() +} + +func (v *notificationsView) help() string { + return T("j/k move · enter open · x clear · a mark all read · r reload · esc/q back") +} +func (v *notificationsView) typing() bool { return false } + +// newDesktop is the desktop's notifier; tests swap it for one that remembers. +var newDesktop = desktop.New diff --git a/internal/ui/notify_test.go b/internal/ui/notify_test.go new file mode 100644 index 0000000..c3f421d --- /dev/null +++ b/internal/ui/notify_test.go @@ -0,0 +1,112 @@ +package ui + +import ( + "strings" + "testing" + + "github.com/tracklines/tui/internal/desktop" +) + +// told remembers what went to the desktop. +type told struct{ got []string } + +func (d *told) Notify(summary, body string, urgent bool) { + if urgent { + body += " (urgent)" + } + d.got = append(d.got, summary+": "+body) +} + +// withNotices starts the TUI with these in the bell and a desktop that remembers. +func withNotices(t *testing.T, notices ...map[string]any) (*app, *[]string, *told) { + t.Helper() + fakeNotices = notices + d := &told{} + was := newDesktop + newDesktop = func() desktop.Notifier { return d } + t.Cleanup(func() { fakeNotices, newDesktop = nil, was }) + a, calls := start(t) + return a, calls, d +} + +// A new one goes to the desktop and the header counts it; N lists them, enter reads and opens its +// ticket, x clears one, a reads them all (TL-886). +func TestNotifications(t *testing.T) { + old := map[string]any{"id": "n2", "kind": "mention", "text": "mentioned you on TL-1", "actor": "user_2", "ticket_id": "t1", "created_at": "2026-01-01T10:00:00Z", "read_at": "2026-01-01T11:00:00Z"} + a, calls, d := withNotices(t, old) + // one arrives: the next look finds it + fakeNotices = []map[string]any{{"id": "n1", "kind": "assigned", "text": "assigned you TL-1: Fix login", "actor": "user_2", "ticket_id": "t1", "created_at": "2099-01-01T10:00:00Z"}, old} + pump(a, a.pollNotices(), 0) + if len(d.got) != 1 || d.got[0] != "TrackLin.es: Alex Roe assigned you TL-1: Fix login" { + t.Fatalf("desktop: %v", d.got) // only the new one; the read one was there before + } + expect(t, a, "N 1 unread") + press(a, "N") + expect(t, a, "Notifications", "● Alex Roe assigned you TL-1: Fix login", "Alex Roe mentioned you on TL-1") + press(a, "enter") + if find(*calls, "POST /api/notifications/n1/read") == "" { + t.Fatalf("not read: %v", *calls) + } + expect(t, a, "Fix login", "Login fails") + press(a, "esc", "j", "x") + if find(*calls, "DELETE /api/notifications/n2") == "" { + t.Fatalf("not cleared: %v", *calls) + } + press(a, "a") + if find(*calls, "POST /api/notifications/read-all") == "" { + t.Fatalf("not all read: %v", *calls) + } +} + +// An urgent one no client has opened them for opens the screen, once (shown); one that's old isn't +// sent to the desktop, and one about no ticket says where it is on the website. +func TestUrgentNoticeOpensNotifications(t *testing.T) { + a, calls, d := withNotices(t, map[string]any{"id": "o1", "kind": "billing", "urgent": true, "actor": "TrackLin.es", + "text": "is giving your organization a free year of Pro.", "link": "/settings?offer=1", "created_at": "2026-01-01T10:00:00Z"}) + if find(*calls, "POST /api/notifications/o1/shown") == "" { + t.Fatalf("not recorded as shown: %v", *calls) + } + if _, open := a.top().(*notificationsView); !open { + t.Fatalf("not opened:\n%s", a.View()) + } + if len(d.got) != 0 { + t.Fatalf("an old one went to the desktop: %v", d.got) + } + press(a, "enter") + expect(t, a, "Open it on the website:", "/settings?offer=1") + + // shown already (here or another client): it doesn't open again + a, calls, _ = withNotices(t, map[string]any{"id": "o1", "kind": "billing", "urgent": true, "text": "x", "created_at": "2026-01-01T10:00:00Z", "shown_at": "2026-01-01T10:01:00Z"}) + if _, open := a.top().(*notificationsView); open || find(*calls, "POST /api/notifications/o1/shown") != "" { + t.Fatalf("opened again: %v", *calls) + } +} + +// Not over what you're typing: it waits for the next look. +func TestUrgentNoticeWaitsWhileTyping(t *testing.T) { + a, calls, _ := withNotices(t) + press(a, "/") // the search box takes text + fakeNotices = []map[string]any{{"id": "o1", "kind": "billing", "urgent": true, "text": "x", "created_at": "2099-01-01T10:00:00Z"}} + pump(a, a.pollNotices(), 0) + if _, typing := a.top().(*searchView); !typing || find(*calls, "POST /api/notifications/o1/shown") != "" { + t.Fatalf("opened over typing: %v", *calls) + } + press(a, "esc") + pump(a, a.pollNotices(), 0) + if _, open := a.top().(*notificationsView); !open { + t.Fatalf("not opened after:\n%s", a.View()) + } +} + +func TestFreshNoticesAreTheLatestThreeUnread(t *testing.T) { + read := "2026-01-01T00:00:00Z" + list := []Notice{{ID: "a", CreatedAt: "2026-01-05T00:00:00Z"}, {ID: "b", CreatedAt: "2026-01-02T00:00:00Z"}, {ID: "c", CreatedAt: "2026-01-04T00:00:00Z"}, + {ID: "d", CreatedAt: "2026-01-03T00:00:00Z"}, {ID: "e", CreatedAt: "2026-01-06T00:00:00Z", ReadAt: &read}, {ID: "f", CreatedAt: "2025-12-31T00:00:00Z"}} + var ids []string + for _, n := range fresh(list, "2026-01-01T00:00:00Z") { + ids = append(ids, n.ID) + } + if strings.Join(ids, "") != "dca" { + t.Fatalf("fresh: %v", ids) + } +} diff --git a/internal/ui/types.go b/internal/ui/types.go index 034b972..1da2602 100644 --- a/internal/ui/types.go +++ b/internal/ui/types.go @@ -21,6 +21,7 @@ type ( TicketInput = api.TicketInput Project = api.Project Mention = api.Mention + Notice = api.Notification Column = api.Column Board = api.Board Comment = api.Comment diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 68ef86f..46f8cd4 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -14,6 +14,7 @@ import ( "github.com/tracklines/tui/internal/api" "github.com/tracklines/tui/internal/config" + "github.com/tracklines/tui/internal/desktop" "github.com/tracklines/tui/internal/drafts" "github.com/tracklines/tui/internal/help" "github.com/tracklines/tui/internal/i18n" @@ -60,6 +61,10 @@ type app struct { drafts drafts.Store // comments and edits that didn't reach the server (TL-599) favourites []usage.Favourite // tabs 3–5: the projects you open most (TL-477) help *help.Store // the help answers, kept up to date in the background (TL-657) + desktop desktop.Notifier // new notifications on the desktop too (TL-886) + unread int // the header's count + unreadSeen int // the count the list was last fetched at; -1: fetch it next time + noticesSince string // the desktop has been told about everything up to here (RFC 3339) } type ( @@ -93,7 +98,8 @@ type ( ) func newApp(api *Client) *app { - a := &app{api: api, usage: usage.Load(), drafts: drafts.Load()} + a := &app{api: api, usage: usage.Load(), drafts: drafts.Load(), desktop: newDesktop(), unreadSeen: -1, + noticesSince: time.Now().UTC().Format(time.RFC3339)} // only what arrives from now on goes to the desktop dir, _ := config.StateDir() // ponytail: no state dir, no cache: the baked answers, then the API's a.help = help.Open(i18n.Lang(), dir) a.favourites = a.usage.Top(3) @@ -164,7 +170,7 @@ func (a *app) refresh() tea.Cmd { return nil } switch v.(type) { - case *homeView, *listView, *projectsView, *projectView, *boardView, *ticketView, *historyView: + case *homeView, *listView, *projectsView, *projectView, *boardView, *ticketView, *historyView, *notificationsView: return v.load(a) } return nil @@ -172,7 +178,7 @@ func (a *app) refresh() tea.Cmd { func (a *app) Init() tea.Cmd { a.loading = true - return tea.Batch(a.top().load(a), a.checkUpdate(), refreshLater(), a.fetchHelp(), func() tea.Msg { + return tea.Batch(a.top().load(a), a.checkUpdate(), refreshLater(), a.fetchHelp(), a.pollNotices(), noticesLater(), func() tea.Msg { p, me, _ := a.api.People(context.Background()) // ponytail: without names, comments show ids; not worth an error return peopleMsg{p, me} }, func() tea.Msg { @@ -258,6 +264,19 @@ func (a *app) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return a, refreshLater() } return a, tea.Batch(refreshLater(), a.refresh(), a.fetchHelp()) + case noticeTick: // even while away: the desktop still hears about new ones + return a, tea.Batch(noticesLater(), a.pollNotices()) + case noticesMsg: + return a, a.notices(msg) + case urgentShownMsg: + if msg.err != nil { + a.unreadSeen = -1 // try again on the next look + return a, nil + } + if _, already := a.top().(*notificationsView); already { + return a, a.top().load(a) + } + return a, msgOf(pushMsg{¬ificationsView{}}) case helpUpdatedMsg: return a, nil // the help screen, if it's showing, redraws with them case tea.BlurMsg: @@ -365,6 +384,10 @@ func (a *app) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if _, already := a.top().(*draftsView); !already { return a, msgOf(pushMsg{&draftsView{sending: map[string]bool{}}}) } + case "N": // notifications (TL-886) + if _, already := a.top().(*notificationsView); !already { + return a, msgOf(pushMsg{¬ificationsView{}}) + } case "t": // go to a ticket by its key return a, msgOf(pushMsg{newGoto()}) case "esc", "backspace": @@ -394,6 +417,9 @@ func (a *app) View() string { } else if a.status != "" { foot = a.status + "\n" + foot } + if a.unread > 0 { + head = append(head, accent.Render(" "+F("N %d unread", a.unread))) + } if a.latest != nil { head = append(head, ok.Render(" "+F("%s is out · ? to update", a.latest.Tag))) }