diff --git a/package.json b/package.json index 71ab500..39087e3 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "voipms-desktop", "productName": "bubble", - "version": "0.9.7", + "version": "0.9.8", "description": "Signal-style desktop SMS client for voip.ms", "author": "trav ", "private": true, diff --git a/src/main/db.ts b/src/main/db.ts index 84ecb8a..252ed70 100644 --- a/src/main/db.ts +++ b/src/main/db.ts @@ -5,6 +5,7 @@ import path from 'node:path' import type { Conversation, Direction, MediaRef, Message, MessageKind, MessageStatus, SearchHit } from '@shared/types' import { SNIPPET_END, SNIPPET_START } from '@shared/types' import { fixVoipDst } from './voipms' +import { SIM_DID } from '@shared/phone' const SCHEMA_VERSION = 12 @@ -265,6 +266,20 @@ export class MessageDb { this.db.prepare(`UPDATE messages SET status = 'failed', error = ? WHERE id = ?`).run(error ?? null, tempId) } + // At startup: sends a previous run left 'pending' (it quit or crashed + // mid-send, and that send's retry loop died with it). Nothing will ever + // finish them, so they become failed: shown as Not sent with Retry, never + // resent on their own (by now they may be stale). If one did go out, the + // next poll still replaces it (reconcileSent matches failed rows too). + // Over the Rabbit's SIM they stay pending: those wait in relay_outbox. + failOrphanedSends(error: string): Message[] { + const rows = this.db + .prepare(`SELECT id FROM messages WHERE id < 0 AND status = 'pending' AND direction = 'out' AND did != ?`) + .all(SIM_DID) as { id: number }[] + for (const { id } of rows) this.markFailed(id, error) + return rows.map(({ id }) => this.getMessage(id)!).filter(Boolean) + } + // Sent messages that turned up in a poll take the place of our local // pending/failed copies (same text, sent around the same time). A send whose // reply never came back may still have gone out; this is how we find out. @@ -337,6 +352,8 @@ export class MessageDb { json_extract(last.media_json, '$[0]') AS lastMedia, (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.direction = 'in' AND m.ts > MAX(COALESCE(r.last_read_ts, 0), @floor)) AS unread, + (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.id < 0 + AND m.status = 'failed') AS failed, r.archived_at IS NOT NULL AS archived, COALESCE(r.marked_unread, 0) AS markedUnread, r.name AS name diff --git a/src/main/index.ts b/src/main/index.ts index 5a27d40..8bcd9e5 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -26,7 +26,7 @@ import { SendMediaType } from './gvoice/schema' import { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session' import { gvMessageId, GvSyncEngine } from './gvoice/sync' import { WaaSigner } from './gvoice/waa' -import { clearNotifications, closeAllNotifications, notifyNew, sweepNotifications } from './notify' +import { clearNotifications, closeAllNotifications, notifyNew, notifyUnsent, sweepNotifications } from './notify' import * as rabbit from './rabbit' import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay' @@ -138,6 +138,7 @@ function startRelay(): void { relay.on('messages', onNewMessages) relay.on('changed', readStateChanged) relay.on('status', () => send('relayStatus', relay?.status())) + relay.on('unsent', (m: Message) => alertUnsent([m])) relay.start() } @@ -421,6 +422,7 @@ function enqueue(key: string, job: () => Promise): Promise { async function deliver(m: Omit, attempt: () => Promise): Promise { const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync const tempId = db.insertPending(m) + sending.add(tempId) send('conversationsChanged') try { await enqueue(`${m.did}:${m.contact}`, () => @@ -432,11 +434,49 @@ async function deliver(m: Omit, attempt: () => Promise }) ) } finally { + sending.delete(tempId) + const after = db.getMessage(tempId) + if (after?.status === 'failed') alertUnsent([after]) send('conversationsChanged') engine?.burst() } } +// voip.ms / Google Voice sends still being worked on (their retry loops live +// only in this process, so quitting now strands them). +const sending = new Set() + +// Always, whatever the notification setting, and even with the window focused: +// a text that didn't go out has to be impossible to miss. +function alertUnsent(msgs: Message[]): void { + if (!msgs.length) return + notifyUnsent(msgs, { db, contacts, onClick: openFromNotification }) + if (win && !win.isDestroyed()) win.flashFrame(true) +} + +// Closing or quitting with a text still on its way: ask first. Returns +// whether to go ahead. +let leaveAnyway = false +function okToLeave(): boolean { + if (leaveAnyway || !sending.size) return true + const n = sending.size + const opts: Electron.MessageBoxSyncOptions = { + type: 'warning', + title: 'Still sending', + message: n > 1 ? `${n} texts are still sending` : 'A text is still sending', + detail: + "If bubble closes now it can't finish, and it will most likely not go out. " + + 'It will show as Not sent next time, with a Retry button.', + buttons: ['Keep bubble open', 'Quit anyway'], + defaultId: 0, + cancelId: 0 + } + const choice = win && !win.isDestroyed() ? dialog.showMessageBoxSync(win, opts) : dialog.showMessageBoxSync(opts) + if (choice !== 1) return false + leaveAnyway = true + return true +} + const voipAttempt = (call: (api: VoipMs) => Promise) => (): Promise => { if (!api) throw new VoipMsError('not_signed_in') return call(api) @@ -789,6 +829,10 @@ function createWindow(): void { // from firing, leaving a windowless process holding the single-instance lock. for (const ev of ['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen', 'resize', 'focus', 'blur'] as const) win.on(ev as 'resize', sendWindowState) + win.on('close', (e) => { + if (!okToLeave()) e.preventDefault() + }) + win.on('focus', () => win?.flashFrame(false)) win.on('closed', () => { win = undefined app.quit() @@ -808,6 +852,7 @@ app.whenReady().then(async () => { moveToBubbleData() settings = loadSettings() db = new MessageDb(path.join(getDataDir(), 'messages.db')) + const orphans = db.failOrphanedSends("bubble closed before this finished sending, so it most likely didn't go out.") if (SANDBOX) seedDemo(db) dids = JSON.parse(db.get('dids') ?? '[]') as Did[] media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => { @@ -836,6 +881,9 @@ app.whenReady().then(async () => { if (gvNumber() && (await hasGvSession())) startGvSync() startRelay() + // Once contacts can name the chat. + if (orphans.length) setTimeout(() => alertUnsent(orphans), 3000) + void dailySnapshot() setInterval(() => void dailySnapshot(), 60 * 60 * 1000) }) @@ -844,6 +892,7 @@ let quitting = false app.on('before-quit', (e) => { if (quitting || !db) return e.preventDefault() + if (!okToLeave()) return quitting = true closeAllNotifications() sync?.stop() diff --git a/src/main/notify.ts b/src/main/notify.ts index 21bcfcf..bd8ba73 100644 --- a/src/main/notify.ts +++ b/src/main/notify.ts @@ -4,6 +4,7 @@ import { Notification } from 'electron' import { formatNumber, groupMembers, isGroup } from '@shared/phone' import type { ContactDirectory } from './contacts' import type { MessageDb, NewMessage } from './db' +import type { Message } from '@shared/types' import { reactionPreview } from '@shared/reactions' import { editPreview } from '@shared/edits' @@ -21,6 +22,9 @@ export interface NotifyDeps { // reading the conversation in the app can take them back out of the list. const live = new Map>() +// "Not sent" alerts, kept referenced for their click handlers. +const unsent = new Set() + const convKey = (did: string, contact: string): string => `${did}\n${contact}` // The conversation's been read: its notifications are stale. @@ -45,6 +49,8 @@ export function sweepNotifications(isUnread: (did: string, contact: string) => b export function closeAllNotifications(): void { for (const shown of live.values()) for (const n of shown) n.close() live.clear() + for (const n of unsent) n.close() + unsent.clear() } const nameOf = (contacts: ContactDirectory, n: string): string => contacts.lookup(n)?.name ?? formatNumber(n) @@ -58,7 +64,7 @@ export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did .join(', ') } -function preview(m: NewMessage): string { +function preview(m: Pick): string { const reaction = reactionPreview(m.body) if (reaction) return reaction const edit = editPreview(m.body) @@ -98,3 +104,27 @@ export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyD n.show() } } + +// Your text didn't go out. Unlike new messages this pops up (normal urgency) +// and stays until clicked or dismissed: a send that fails quietly is the +// worst thing a phone can do. +export function notifyUnsent(msgs: Message[], { db, contacts, onClick }: NotifyDeps): void { + if (!Notification.isSupported()) return + const byConv = new Map() + for (const m of msgs) byConv.set(convKey(m.did, m.contact), [...(byConv.get(convKey(m.did, m.contact)) ?? []), m]) + for (const list of byConv.values()) { + const { did, contact } = list[0] + const who = conversationTitle(db, contacts, did, contact) + const n = new Notification({ + title: list.length > 1 ? `${list.length} texts to ${who} weren't sent` : `Text to ${who} wasn't sent`, + body: list.length > 1 ? 'Open the chat to retry or delete them.' : `“${preview(list[0]) || 'Your message'}” · ${list[0].error ?? 'Open the chat to retry it.'}`, + urgency: 'critical' + }) + // Kept referenced like the others so the click survives; not filed under + // `live`, so reading the chat doesn't take it back down. + unsent.add(n) + n.on('click', () => onClick({ did, contact })) + n.on('close', () => unsent.delete(n)) + n.show() + } +} diff --git a/src/main/relay.ts b/src/main/relay.ts index 964c234..bb84ead 100644 --- a/src/main/relay.ts +++ b/src/main/relay.ts @@ -297,7 +297,11 @@ export class RelayEngine extends EventEmitter { if (temp === undefined || temp === null) return const tempId = Number(temp) if (isInt(p.msgId)) this.db.confirmPending(tempId, p.msgId) - else this.db.markFailed(tempId, typeof p.error === 'string' ? `Rabbit: ${p.error}` : "The Rabbit couldn't send it.") + else { + this.db.markFailed(tempId, typeof p.error === 'string' ? `Rabbit: ${p.error}` : "The Rabbit couldn't send it.") + const m = this.db.getMessage(tempId) + if (m) this.emit('unsent', m) + } this.db.db.prepare('DELETE FROM kv WHERE key = ?').run(key) this.emit('changed', 'sent') } diff --git a/src/renderer/src/components/ChatView.tsx b/src/renderer/src/components/ChatView.tsx index 4d362c8..066ff67 100644 --- a/src/renderer/src/components/ChatView.tsx +++ b/src/renderer/src/components/ChatView.tsx @@ -6,7 +6,7 @@ import type { ConvKey, Jump } from '../App' import { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format' import { Avatar } from './Avatar' import { Composer, type ComposerHandle } from './Composer' -import { CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' +import { AlertIcon, CloseIcon, DownIcon, SearchIcon, UpIcon } from './Icons' import { conversationMedia, Lightbox } from './Lightbox' import { MessageBubble } from './MessageBubble' import { DEFAULT_QUICK_REACTIONS, reactionText, sameEmoji, type Reaction } from '@shared/reactions' @@ -166,6 +166,8 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam return [{ label: sel ? 'Copy' : 'Copy text', onSelect: () => void navigator.clipboard.writeText(sel || m.body) }] } + const unsent = useMemo(() => (messages ?? []).filter((m) => m.status === 'failed'), [messages]) + const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows]) const flash = useCallback((id: number) => { @@ -402,6 +404,16 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam )} + {unsent.length > 0 && ( +
+ + + {unsent.length > 1 ? `${unsent.length} of your texts weren't sent.` : "Your text wasn't sent."} Retry or delete{' '} + {unsent.length > 1 ? 'them' : 'it'} below. + + +
+ )} {dragging &&
Drop to attach
} {lightbox && ( diff --git a/src/renderer/src/components/ConversationList.tsx b/src/renderer/src/components/ConversationList.tsx index 93afbfa..9898dbf 100644 --- a/src/renderer/src/components/ConversationList.tsx +++ b/src/renderer/src/components/ConversationList.tsx @@ -117,7 +117,15 @@ const ConversationRow = memo(function ConversationRow({ {shortTime(conv.lastTs)}
- {preview} + + {conv.failed > 0 && Not sent · } + {preview} + + {conv.failed > 0 && ( + 1 ? `${conv.failed} texts weren't sent` : "A text wasn't sent"}> + ! + + )} {conv.unread > 0 ? ( {conv.unread > 99 ? '99+' : conv.unread} ) : ( diff --git a/src/renderer/src/components/MessageBubble.tsx b/src/renderer/src/components/MessageBubble.tsx index 5b5e977..a710f38 100644 --- a/src/renderer/src/components/MessageBubble.tsx +++ b/src/renderer/src/components/MessageBubble.tsx @@ -90,6 +90,9 @@ interface Props { onMediaLoad: () => void } +// A send still going after this long gets a visible "Still sending…". +const SLOW_SEND_MS = 15_000 + export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) { const media = m.media ?? [] const cls = [ @@ -137,6 +140,11 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe {m.status === 'pending' && ( + {/* Appears once a send has taken a while (the negative delay + counts time already spent, so it survives re-renders). */} + + Still sending… + )} @@ -152,10 +160,16 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe )} {m.status === 'failed' && ( -
- Not sent{m.error ? `: ${m.error}` : ''} · - · - +
+ + Not sent. {m.error ?? ''} + + + + +
)}
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css index 9769123..9a61f76 100644 --- a/src/renderer/src/styles.css +++ b/src/renderer/src/styles.css @@ -527,9 +527,6 @@ mark { .msg.out:not(.g-end) .bubble { border-bottom-right-radius: 4px; } -.msg.failed .bubble { - opacity: 0.6; -} .bubble a { color: inherit; text-decoration: underline; @@ -548,21 +545,85 @@ mark { background: rgba(255, 255, 255, 0.9); color: #1b1b1b; } +/* A text that didn't go out: loud, never a quiet little icon. */ +.msg.failed .bubble { + outline: 2px solid var(--danger); + outline-offset: 2px; +} .failed-row { display: flex; align-items: center; + justify-content: flex-end; flex-wrap: wrap; - gap: 4px; - font-size: 12px; + gap: 6px 10px; + max-width: 75%; + margin: 6px 0 4px auto; + padding: 6px 10px; + border-radius: 8px; + background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); - margin-top: 3px; + font-size: 13px; +} +.failed-why { + display: inline-flex; + align-items: center; + gap: 5px; +} +.failed-actions { + display: inline-flex; + gap: 6px; } .failed-row button { - border: 0; + border: 1px solid var(--danger); + border-radius: 6px; background: none; color: var(--danger); - text-decoration: underline; - padding: 0 2px; + font: inherit; + font-weight: 600; + padding: 2px 10px; +} +.failed-row button.failed-retry { + background: var(--danger); + color: #fff; +} +.slow-send { + margin-left: 3px; + opacity: 0; + animation: slow-send 0s forwards; +} +@keyframes slow-send { + to { + opacity: 1; + } +} +.unsent-banner { + flex: none; + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + background: var(--danger); + color: #fff; + font-size: 14px; +} +.unsent-banner .unsent-text { + flex: 1; +} +.unsent-banner button { + border: 1px solid #fff; + border-radius: 6px; + background: none; + color: #fff; + font: inherit; + font-weight: 600; + padding: 3px 12px; +} +.badge.unsent { + background: var(--danger); + color: #fff; +} +.row-unsent { + color: var(--danger); } /* ---------- composer ---------- */ @@ -2290,9 +2351,6 @@ mark { .msg.out:not(.g-end) .bubble { border-bottom-right-radius: 4px; } -.msg.failed .bubble { - opacity: 0.6; -} .bubble a { color: inherit; text-decoration: underline; @@ -2311,21 +2369,80 @@ mark { background: rgba(255, 255, 255, 0.9); color: #1b1b1b; } +/* A text that didn't go out: loud, never a quiet little icon. */ +.msg.failed .bubble { + outline: 2px solid var(--danger); + outline-offset: 2px; +} .failed-row { display: flex; align-items: center; + justify-content: flex-end; flex-wrap: wrap; - gap: 4px; - font-size: 12px; + gap: 6px 10px; + max-width: 75%; + margin: 6px 0 4px auto; + padding: 6px 10px; + border-radius: 8px; + background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); - margin-top: 3px; + font-size: 13px; +} +.failed-why { + display: inline-flex; + align-items: center; + gap: 5px; +} +.failed-actions { + display: inline-flex; + gap: 6px; } .failed-row button { - border: 0; + border: 1px solid var(--danger); + border-radius: 6px; background: none; color: var(--danger); - text-decoration: underline; - padding: 0 2px; + font: inherit; + font-weight: 600; + padding: 2px 10px; +} +.failed-row button.failed-retry { + background: var(--danger); + color: #fff; +} +.slow-send { + margin-left: 3px; + opacity: 0; + animation: slow-send 0s forwards; +} +.unsent-banner { + flex: none; + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + background: var(--danger); + color: #fff; + font-size: 14px; +} +.unsent-banner .unsent-text { + flex: 1; +} +.unsent-banner button { + border: 1px solid #fff; + border-radius: 6px; + background: none; + color: #fff; + font: inherit; + font-weight: 600; + padding: 3px 12px; +} +.badge.unsent { + background: var(--danger); + color: #fff; +} +.row-unsent { + color: var(--danger); } /* ---------- composer ---------- */ @@ -3428,6 +3545,14 @@ select { background: var(--highlight-text); color: var(--highlight); } +.row.active .badge.unsent { + background: var(--danger); + color: #fff; + box-shadow: 0 0 0 1.5px #fff; +} +.row.active .row-unsent { + color: inherit; +} .sync-footer { border-top: 0; padding-top: 0; diff --git a/src/shared/types.ts b/src/shared/types.ts index 994ce4d..33c87e6 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -61,6 +61,7 @@ export interface Conversation { lastSender?: string // sender of the last message, in group chats name?: string // a name you gave the conversation (local only) unread: number + failed: number // your texts here that didn't send (shown loudly until retried or deleted) markedUnread: boolean // manually marked unread (shown as a dot) archived: boolean } diff --git a/test/db.test.ts b/test/db.test.ts index 7f6b48c..3c9cbc6 100644 --- a/test/db.test.ts +++ b/test/db.test.ts @@ -203,6 +203,20 @@ describe('MessageDb', () => { expect(db.getMessage(t)?.error).toBe('nope') }) + it('fails sends a previous run left pending, except over the SIM, and counts them per chat', () => { + const t1 = db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body: 'stranded', ts: 1000 }) + const t2 = db.insertPending({ did: 'sim', contact: 'a', direction: 'out', body: 'waits for the Rabbit', ts: 1001 }) + const orphans = db.failOrphanedSends('closed mid-send') + expect(orphans.map((m) => m.id)).toEqual([t1]) + expect(db.getMessage(t1)).toMatchObject({ status: 'failed', error: 'closed mid-send' }) + expect(db.getMessage(t2)?.status).toBe('pending') + expect(db.listConversations().find((c) => c.did === '5550001111')?.failed).toBe(1) + expect(db.listConversations().find((c) => c.did === 'sim')?.failed).toBe(0) + // Still matched if it turns out it did go out. + expect(db.reconcileSent([{ ...msg(50, 'a', 'stranded', 1000, 'out') }])).toEqual([t1]) + expect(db.listConversations().find((c) => c.did === '5550001111')?.failed).toBe(0) + }) + describe('reconcileSent', () => { const MIN = 60_000 const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts })