Compare commits

..
36 Commits
Author SHA1 Message Date
trav cf7ad66e0f v0.9.9: bubble for Android 0.7.9 — Not sent texts get an Edit button; the desktop's alert no longer breaks through Do Not Disturb; the Rabbit catches sends a killed process left behind, tells the desktop about them, and shows failures loudly too 2026-11-20 10:27:14 -08:00
trav 11037a7770 v0.9.8: bubble for Android 0.7.8 — a text that doesn't go out is loud: closing mid-send asks first, sends stranded by a quit come back as Not sent, and failures pop up a notification, a red banner and a mark in the chat list 2026-11-20 10:00:02 -08:00
trav 512f481ba3 v0.9.7: bubble for Android 0.7.8 — desktop notifications come down when the chat's read elsewhere, and on quit instead of being stranded in the list 2026-11-19 12:16:37 -08:00
trav 5663344933 v0.9.6: bubble for Android 0.7.8 — the chat search's arrows stay on the match instead of snapping back to the newest messages 2026-11-17 00:15:46 -08:00
trav 6f365df087 v0.9.5: bubble for Android 0.7.8 — the relay is just a relay server: its address is a setting, and deploy-relay.sh reads scripts/relay.env 2026-11-16 11:19:54 -08:00
travandClaude Opus 5.5 8b3cfdca24 Keep CLAUDE.md, the signing keystore and __pycache__ out of the repo
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:15:25 -08:00
travandClaude Opus 5.5 0099fdec8b Concise README with a screenshot (Signal vibes, made-up data)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:12:43 -08:00
trav 0e4ed7f4fe v0.9.4: bubble for Android 0.7.7 — tap the paperclip, then tap a choice (holding and swiping up went home) 2026-11-15 15:07:35 -08:00
travandClaude Opus 5.5 a238800b32 v0.9.3: the unread button's bubbles don't touch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:22:52 -08:00
travandClaude Opus 5.5 0b2338e1c0 v0.9.2: an unread view
A button with three outlined bubbles, between Check for new messages and Archived chats, lists only unread chats (archived ones too) under an "Unread chats" header, like the archive's. The chat you open from it reads as usual but stays in the list, to keep replying, until you open another one; then it drops out.

Tried on the sandbox's made-up chats: an archived unread chat listed, an opened chat kept until the next was opened, and the view emptying back to the still-unread ones when left and reopened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 13:15:10 -08:00
travandClaude Opus 5.5 4129f72f39 v0.9.1: bubble for Android 0.7.6 — pictures have the bubble's round corners; no "MMS Sent"
Android: a picture in a chat is clipped to the bubble's 30 dp corner, sent and received. Checked on the Rabbit with the dev app (the sandbox now has a made-up picture each way).

Both: voip.ms gives a picture we sent with no words the text "MMS Sent", like the "MMS Received" already dropped; that goes too, from new messages and (once) from ones already stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:39:02 -08:00
trav bd10daeb8b v0.9.0: the history lives in ~/Documents/bubble-data
On its first launch bubble copies ~/Documents/voipms-desktop-data to ~/Documents/bubble-data (through a .partial folder, renamed only once the copy is whole) and uses that. The old folder stays as a backup with a "MOVED TO bubble-data.txt" note, to delete once everything looks right. A data folder chosen in Settings elsewhere stays put; if the copy fails, bubble keeps using the old folder rather than starting empty.

Tried with a throwaway home holding the sandbox's made-up history: the copy, the note, the chats loading from the new folder, no second copy on the next launch, and a saved pointer to the old folder moving along with it.
2026-11-13 12:15:09 -08:00
trav dd994c5bc3 v0.8.8: bubble for Android 0.7.5 — the composer is always the small size; smoother scrolling past photos
Android: the composer used to shrink only with the keyboard up; now it is always that size (small text, tight padding, 60 dp buttons), and the keyboard only takes a line off the text box and the subtitle. Checked on the Rabbit with the dev app, at rest and typing.

Desktop: the chat and Get info show a smaller copy of each still picture (720 px long edge, made once into <dataDir>/thumbs) instead of decoding a phone's 4000 px photo every time a row scrolls in. Full size, Save and Copy still use the original; GIFs and pictures already that small are served as they are. Pictures decode off the main thread.
2026-11-13 12:01:56 -08:00
trav a3017bdd50 v0.8.7: a bubble round a picture follows its corner evenly
Its corners were 18 px round round an 8 px picture with 4 px of padding, so the gap across each corner shrank to about 1.5 px. They are 12 px now (the picture's 8 plus the padding), the same 4 px all the way round.
2026-11-13 11:51:18 -08:00
trav 95ec0b839c v0.8.6: bubble for Android 0.7.4 — the message box sits inside the composer again
The composer row lined its children up by text baseline, and the attach/send glyphs have no text, so the text box was lifted 27 px out the top of the composer and cut off. Rows now line up by their bottoms. Checked on the Rabbit with the dev app and made-up chats: at rest, with the keyboard up, and with three lines typed.
2026-11-13 11:43:44 -08:00
trav a6d6e193c1 v0.8.5: the chat search field is just its glyph
No "Search in chat" placeholder; the field keeps it as its accessible name.
2026-11-13 11:28:02 -08:00
trav 71987ec387 v0.8.4: a one-line chat header with the search field always there
The name, a group's size and the [GV]/[MS]/[SIM] tag (at the right) share one line, so the header, its picture included, is smaller. Search in chat is a field at the end of the name panel: click in and type; Esc clears it, Enter/Shift+Enter step, Ctrl+Shift+F still jumps there. The panel still opens Get info, except over the field.
2026-11-12 17:19:18 -08:00
trav 1eb80cc075 v0.8.3: chat list rows are two lines, with bigger text
The [GV]/[MS]/[SIM] tag sits at the end of the preview line, under the time, instead of a third line of its own; the name, preview and time are a size up in the room it left.
2026-11-12 16:19:02 -08:00
trav e4936b7fc8 v0.8.2: the chat list and header say just [GV], [MS] or [SIM]
Not "via [GV] (541) …": the tag alone, with the full number as its tooltip. Get info still says it in full (now [MS] for voip.ms too).
2026-11-12 15:35:23 -08:00
trav 0b635cb7a1 v0.8.1: Get info shows the newest photos first
The thumbnails run newest first, like Signal; the full-size view still steps ← older, → newer, as in the chat.
2026-11-12 15:18:59 -08:00
trav 1106de26f2 v0.8.0: bubble for Android 0.7.3 — Get info for everyone, with the chat's photos; no more "MMS Received"
Desktop:
- Click a chat's picture or name (or right-click it in the list → Get info…)
  for any chat, not only groups. One person: their picture, name, number
  (and its label), which of your numbers you're texting from, Add to
  contacts… if they aren't one. The number no longer sits in the header.
- Get info lists every photo and video in the chat as thumbnails, oldest
  first like the chat, scrolled to the newest. Each opens full size.
- The full-size view steps through the chat's photos with ← and → (or the
  side buttons) and says "n of N · date", from Get info or from the chat.
  Its glyphs were light gray on the white buttons; now the usual glyph color.

Both: voip.ms puts "MMS Received" as the text of a received picture that
came without words. Nobody wrote it, so it's dropped as messages come in,
and once from the ones already stored (only on messages with pictures, so
someone typing "MMS received" still shows).

Tried in a sandbox with made-up chats and generated pictures, driven over
DevTools: the header, Get info for a person and a group, thumbnails,
←/→ through 14 pictures, Esc closing the picture then the dialog, and the
v11 migration clearing a stored "MMS Received".
2026-11-12 15:01:56 -08:00
trav 50ff68b6ee v0.7.2: bubble for Android 0.7.2 — reactions quote the message exactly, so the other phone can find it 2026-11-11 04:50:28 -08:00
trav 5f68bb7267 v0.7.1: bubble for Android 0.7.1 — your own reaction shows as a white disc in the long-press row
Tried on the Rabbit with the dev app and made-up chats: long-press row, +
grid, sending, replacing and taking back a reaction, the Spanish tapback and
the edit with its history, and Settings → Reactions. The only fix: the dark
gray highlight on your reaction was hard to see, so it's the picked-tile
white of rabbit.html#looks, inset to a circle.
2026-11-10 18:07:02 -08:00
trav 09a46aa35c v0.7.0: bubble for Android 0.7.0 — react to messages, reactions in other languages, and edits
Android, ported from the desktop's reactions.ts / edits.ts (same readings:
checked side by side on the same 32 cases):
- Long-press a message: the quick reaction row (yours lit, tap again to take
  it back), + for every emoji (EmojiPicker, the desktop's emoji list as
  res/raw/emoji_list.txt, minus any the font can't draw), and Copy text.
- Settings → Reactions → Quick reactions: pick a spot, then its emoji; Reset.
- Tapbacks in other languages fold like the desktop's; "Edited to “…”" edits
  its message, which says "Edited · time"; tap it for the earlier texts.
- Chat list and notifications preview an edit as "✏️ new text".
- push_sandbox.py has a Spanish tapback and an edit to try it on.

Desktop: version 0.7.0; gen-emoji also writes the Android list.
2026-11-10 17:38:09 -08:00
trav fcabae81e5 Desktop: react to messages, reactions in other languages, and edits
- Right-click a message (or photo): a quick reaction row above Copy, + for
  every emoji, and "Customize quick reactions…" there to change the row
  (saved in settings as quickReactions; default ❤️ 👍 👎 😂 ‼️ ❓). Yours
  shows sunk; clicking it again takes it back. A reaction goes out as an
  ordinary text worded like an iPhone's ("Loved “…”", "Reacted 🎉 to “…”",
  "Removed a heart from “…”"), long messages quoted cut short.
- Tapbacks in other languages ("Le encanta “…”", "Hat „…“ geliebt",
  "A aimé « … »"...): read from the words around the quote, and only folded
  when the quote matches an earlier message. A failed reaction stays in view.
- "Edited to “…”": applied to the sender's message from the last 20 minutes
  that reads most like it (or their only one); the bubble says "Edited", and
  clicking it shows the earlier texts. Reactions to the old text still land.
- Popovers re-fit the window when they grow.
2026-11-10 17:33:48 -08:00
travandClaude Opus 5.5 a2d8f7761e Title bar: window buttons on the left are clickable again
The centred title spans the whole bar and inherits its drag region; it came
after the left button group, so its drag covered their no-drag and a click
started a window move instead. The title now goes first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:37:24 -08:00
trav 8927c5c59c Preferences: one Accounts page (voip.ms, Google Voice, Numbers with checking), and jai gets its own page 2026-11-08 20:42:18 -08:00
trav 4d0c15757d v0.6.0: bubble for Android 0.6.0 — the house look on the Rabbit, and a stretchy pull-to-refresh that pops
Desktop: Signal vibes or travewave, chosen in Preferences → Appearance.
Rabbit: white on pure black, 22/28/32 sp text, outlined buttons and dim-edged
text boxes, and drawn icons instead of emoji (rabbit.html). Pulling the chat
list further once the search box shows stretches a bubble that pops at the
mark and starts the check, then a spinner until it's done.
2026-11-08 19:39:58 -08:00
trav 357a2312ce Desktop: the travewave house look (shared-resources design.html), switchable with Signal vibes
Preferences → Appearance → Style picks Signal vibes (the look so far) or
travewave: house grays, embossed buttons and tiles, a debossed chat-name
panel, 8 px framed lists, button-like scrollbars, Century Gothic for names
and messages. Either way the window is now one rounded frameless tile with
its own title bar (GNOME's button layout) and a menu bar shown by tapping
Alt (Edit → Preferences…, Ctrl+,), tooltips drawn by the page with a
"Show tooltips" preference, and Preferences laid out like VLC's
(categories left, changes apply at once, Close).
2026-11-08 19:36:53 -08:00
travandClaude Opus 5.5 6d31a5585e Marked-unread dot is magenta instead of blue
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 16:39:08 -08:00
trav 2e2086e178 v0.5.1: bubble for Android 0.5.1 — no double sends when a text with an emoji is cut off mid-send
voip.ms's listing drops emoji, so a send whose reply was lost (here the
laptop slept 8 s after Send) never matched its own copy in the listing and
went out a second time. Match with the emoji taken out (exact match first),
and after an uncertain send only send again once a listing check actually
got through; if none can, mark it failed with a note instead.
2026-11-07 14:05:23 -08:00
trav 96c368dfd1 v0.5.0: bubble for Android 0.5.0 — text from the Rabbit's SIM on the desktop, and chat names and read status sync, through jai
A relay on jai (server/bubble_relay.py, stdlib + SQLite, tailscale address
only, bearer token) carries sealed blobs between the desktop and the Rabbit:
AES-256-GCM with a key the desktop makes and hands over USB (Sync to Rabbit),
so jai can neither read nor forge anything. It deletes what's been picked up,
and anything after 14 days.

- Desktop (src/main/relay.ts): "Rabbit SIM" is a number to text from, groups
  included; the SIM's history and new texts arrive; older photos are fetched
  when shown; names and read/unread/archived go both ways. Settings → Rabbit
  relay connects it.
- Rabbit (Relay.java, RelayJob): no timer of its own for the battery; it rides
  along with the background checks, plus one network job after a text, a send
  or a swipe. Each send from the desktop goes out at most once and not after a
  day. Plain http only to jai and localhost (network_security_config).
- scripts/deploy-jai.sh; tests: server unit tests, an end-to-end relay test,
  and DEVICE=1 relay.device.test.ts against the dev app.
2026-11-06 17:35:00 -08:00
trav e1bceb06a3 v0.4.0: bubble for Android 0.4.0 — an inverted (lighter) icon, chosen in Settings on both
The original icon is a little dark: resources/icon-inverted.png and
ic_launcher_inverted.png are its negative (alpha kept).

- Desktop: Settings → Appearance → Icon (Dark / Inverted), saved on click;
  sets the window icon and rewrites the launcher's installed copy
- Android: Settings → Icon; two launcher activity-aliases, one enabled
2026-11-06 17:20:56 -08:00
trav 94188a42c7 v0.3.0: bubble for Android 0.3.0 — texts over the Rabbit's own SIM card
A third source next to voip.ms and Google Voice, while bubble is Android's
default SMS app (Settings → SIM card asks for the role). SMS and MMS in and
out, group chats as MMS, the phone's existing texts imported, and Android's
message store kept as the record so another app still agrees.

- Sim: role check, sending (SmsManager, waits for the radio), receiving,
  chunked import from content://sms and content://mms
- Pdu: MMS wire format (notification-ind, retrieve-conf, send-req, ack)
- SmsReceiver, MmsReceiver, MmsDownloaded, MmsFiles, RespondService,
  SendToActivity: what Android requires of a default SMS app
- The import no longer shares a lock with Config.get, which froze the screens
  on the first copy of a long history
2026-11-06 17:18:58 -08:00
trav 8c84feaa91 v0.2.0: bubble for Android 0.2.0 — chat search, swipe for unread, faster chat opening
Desktop:
- Search lists chats whose own name matches first, so a named group
  isn't pushed out of the top 8 by chats that merely include a member.

Android (Rabbit R1) app, 0.2.0:
- Pull the chat list past its top for a search box (name, person,
  number, then group members; archived chats too; Back clears it).
- Swipe right to left marks a chat unread / read over a magenta band;
  left to right still archives (SwipeActions replaces SwipeArchive).
- Google Voice chats don't offer voice notes in the paperclip bubble.
- Chats open with their newest 60 messages, then the full history;
  marking read (and the Google Voice network call) waits until they're
  on screen. Cached pictures show at once, and one slow download no
  longer blocks the other images. Fixed a contacts reload race.
- Sandbox data gains filler chats, a named group and a 4,000-message chat.

Also: the Android app, Google Voice support, media, export, emoji and
the other work since the first commit, and a CLAUDE.md carrying the
privacy rule.
2026-11-06 02:19:56 -08:00
travandClaude Opus 5 a2b8f764db voip.ms Messages: Signal-style desktop SMS client
Electron + React app that imports the full voip.ms SMS history into a
local SQLite/FTS5 database, polls for new messages, sends SMS, resolves
names/photos from GNOME EDS address books, and supports global and
per-chat search with jump-to-message.

Data lives in ~/Documents/voipms-desktop-data (covered by Deja Dup) with
daily consistent snapshots.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 21:25:12 -07:00
44 changed files with 714 additions and 203 deletions
+6
View File
@@ -6,3 +6,9 @@ dist/
# Android build output
android/build/
# Local only
CLAUDE.md
android/*.keystore
__pycache__/
scripts/relay.env
-39
View File
@@ -1,39 +0,0 @@
# bubble (voip.ms Messages)
Desktop SMS client (Electron, `src/`) plus its Rabbit R1 companion app
(plain Java, `android/`, see `android/README.md`).
## trav's data is off limits
Never read trav's messages, contacts, accounts or anything the apps keep
about him, and never screenshot the real app showing them. Standard:
`~/Documents/shared-resources/privacy.html`. If reading it seems necessary,
ask trav first, every time (what and why); one yes covers one look. No
exceptions granted so far.
Where his data lives:
- Desktop: `~/.config/voip.ms Messages/` (Electron userData: the message
database, settings, secrets, photo cache, ui-state.json).
- Rabbit R1: the private storage of `me.teafry.voipmessages`
(`files/messages.db`, `files/config.json`, `files/media/`,
`files/state*.json`). Don't `run-as` into it, and don't screenshot that app.
- Rabbit R1 SIM texts: Android's shared message store (`content://sms`,
`content://mms`, the telephony provider), which bubble reads and writes as
the default SMS app. Don't query it over adb, and don't make an app the
default SMS app yourself (it hands that app his texts).
- jai: `~/Documents/bubble-server/data/` (the relay's mailbox and token).
Everything in relay.db is sealed, but it's still his messages: don't read
it, and never print the token (`scripts/deploy-jai.sh --token` is for trav).
The desktop keeps the relay's address, token and key in
`~/.config/voip.ms Messages/relay.bin`.
Test with fake data only:
- Desktop: `VOIPMS_SANDBOX=/tmp/x npm run dev`.
- Relay: `server/test_bubble_relay.py` and `test/relay.test.ts` run a throwaway
local server; `DEVICE=1 npm test -- test/relay.device.test.ts` drives the dev
app on a plugged-in Rabbit through `adb reverse`. Never test against jai's.
- Android: the dev app `me.teafry.voipmessages.dev`
(`python3 android/build.py --dev --install`, then
`python3 android/tools/push_sandbox.py` for made-up conversations).
+1 -1
View File
@@ -6,7 +6,7 @@ A Signal-style desktop SMS/MMS client for [voip.ms](https://voip.ms) and Google
- Keeps your whole message history locally (SQLite), with full-text search
- Group chats, MMS, reactions, emoji shortcodes, GNOME contacts
- Optional end-to-end-sealed relay to sync with the Rabbit R1 (`server/`)
- Optional relay server to sync with the Rabbit R1: it only ever holds sealed messages (`server/`, deployed with `scripts/deploy-relay.sh`)
## Run
+3 -3
View File
@@ -87,7 +87,7 @@ Install/Sync buttons then target the dev app with the sandbox's made-up data.
side, through `MmsFiles`. Long texts go as multipart SMS; photos, voice notes
and group chats as MMS (needs mobile data on). The dev app's sandbox never
uses the SIM.
- Relay (`Relay`, `RelayJob`): the desktop's link through jai (its
- Relay (`Relay`, `RelayJob`): the desktop's link through the relay server (its
`src/main/relay.ts`, server `server/bubble_relay.py`). config.json's `relay`
(address, token, AES-256-GCM key) comes from Sync to Rabbit. The SIM's
messages go to the desktop, sends typed there go out here (each one at most
@@ -96,7 +96,7 @@ Install/Sync buttons then target the dev app with the sandbox's made-up data.
of its own: it rides along with `PollJob`'s checks, plus one network job a few
seconds after something happens here (a text in, a send done, a swipe or
rename), and a catch-up when the app is opened (at most once a minute). Plain
http is allowed only to jai's tailscale address and localhost
(`res/xml/network_security_config.xml`).
http is allowed only to a tailscale (100.64/10) address and localhost
(`Config`; `res/xml/network_security_config.xml` lets cleartext through).
- The scroll wheel is left alone: it stays the volume control (and volume
down + the side button still takes a screenshot).
@@ -46,6 +46,7 @@ public final class ChatActivity extends BaseActivity {
private ListView list;
private TextView titleView, subView, counter, attach, send;
private EditText input;
private TextView unsentBanner;
private LinearLayout header, composerBox, tray, fromRow;
// The keyboard is up: the composer shrinks so what's being typed and the
// last few messages both fit above it (see setCompact).
@@ -106,6 +107,21 @@ public final class ChatActivity extends BaseActivity {
list.setAdapter(adapter);
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
// Texts here that didn't go out: never just a quiet line on a bubble.
unsentBanner = Ui.bold(Ui.text(this, "", Ui.T_SMALL, 0xFFFFFFFF));
unsentBanner.setBackgroundColor(Ui.DANGER);
unsentBanner.setPadding(Ui.dp(this, 32), Ui.dp(this, 16), Ui.dp(this, 32), Ui.dp(this, 16));
unsentBanner.setVisibility(View.GONE);
unsentBanner.setOnClickListener(v -> {
for (int i = 0; i < rows.size(); i++)
if (rows.get(i) instanceof Store.Msg && "failed".equals(((Store.Msg) rows.get(i)).status)) {
list.setSelection(i);
failedMenu((Store.Msg) rows.get(i));
return;
}
});
root.addView(unsentBanner);
root.addView(composer());
setContentView(root);
root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
@@ -246,6 +262,7 @@ public final class ChatActivity extends BaseActivity {
protected void onResume() {
super.onResume();
Notifier.clear(this, did, contact);
Notifier.clearUnsent(this, did, contact);
}
@Override
@@ -310,6 +327,11 @@ public final class ChatActivity extends BaseActivity {
View firstView = list.getChildAt(0);
Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null;
int anchorTop = firstView == null ? 0 : firstView.getTop();
int unsent = 0;
for (Store.Msg m : msgs) if ("failed".equals(m.status)) unsent++;
unsentBanner.setVisibility(unsent > 0 ? View.VISIBLE : View.GONE);
unsentBanner.setText("⚠ " + (unsent > 1 ? unsent + " of your texts weren't sent." : "Your text wasn't sent.")
+ " Tap to retry, edit or delete.");
rows.clear();
for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i);
@@ -644,7 +666,8 @@ public final class ChatActivity extends BaseActivity {
bubble.addView(media);
bubble.addView(body);
bubble.addView(meta);
failed = Ui.text(c, "", Ui.T_TINY, Ui.DANGER);
failed = Ui.bold(Ui.text(c, "", Ui.T_SMALL, Ui.DANGER));
failed.setPadding(Ui.dp(c, 14), Ui.dp(c, 6), Ui.dp(c, 14), Ui.dp(c, 6));
reacts = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT);
reacts.setBackground(Ui.round(Ui.BUBBLE_IN, Ui.dp(c, 30)));
reacts.setPadding(Ui.dp(c, 14), Ui.dp(c, 4), Ui.dp(c, 14), Ui.dp(c, 4));
@@ -680,7 +703,11 @@ public final class ChatActivity extends BaseActivity {
setGravity(out ? Gravity.END : Gravity.START);
((LayoutParams) bubble.getLayoutParams()).gravity = out ? Gravity.END : Gravity.START;
bubble.setBackground(Ui.round(out ? Ui.ACCENT : Ui.BUBBLE_IN, Ui.dp(c, 30)));
bubble.setAlpha("failed".equals(msg.status) ? 0.6f : 1f);
if ("failed".equals(msg.status)) {
android.graphics.drawable.GradientDrawable g = Ui.round(Ui.ACCENT, Ui.dp(c, 30));
g.setStroke(Ui.dp(c, 4), Ui.DANGER);
bubble.setBackground(g);
}
bubble.setMinimumWidth(0);
// Keep bubbles to ~80% of the width.
body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f));
@@ -693,7 +720,8 @@ public final class ChatActivity extends BaseActivity {
meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE);
failed.setText("⚠ Not sent" + (msg.error != null ? ": " + msg.error : "") + " · tap to retry");
failed.setText("⚠ Not sent. " + (msg.error != null ? msg.error + " " : "") + "Tap to retry, edit or delete.");
failed.setGravity(out ? Gravity.END : Gravity.START);
List<Reactions.Reaction> rs = reactions.get(msg.id);
reacts.setVisibility(rs == null ? GONE : VISIBLE);
if (rs != null) {
@@ -861,7 +889,33 @@ public final class ChatActivity extends BaseActivity {
Store.get(this).deleteMessage(m.id);
changed();
})
.setNeutralButton("Cancel", null)
.setNeutralButton("Edit", (d, w) -> editFailed(m))
.show();
}
/**
* Back into the box to change before sending again: its words (and
* photos) go into the composer and the failed copy goes. A voice note
* can't be edited, so it just goes back to Retry.
*/
private void editFailed(Store.Msg m) {
List<Sender.Photo> back = new ArrayList<>();
for (JSONObject ref : m.media()) {
String mime = ref.optString("mime");
if (!mime.startsWith("image/")) {
Toast.makeText(this, "A voice note can't be edited: retry or delete it.", Toast.LENGTH_LONG).show();
return;
}
back.add(new Sender.Photo(ref.optString("file"), mime, ref.optInt("width"), ref.optInt("height")));
}
String cur = input.getText().toString();
input.setText(cur.trim().isEmpty() ? m.body : m.body + "\n" + cur);
input.setSelection(input.getText().length());
for (Sender.Photo p : back) addToTray(p);
input.requestFocus();
MainActivity.bg.execute(() -> {
Store.get(this).deleteMessage(m.id);
changed();
});
}
}
@@ -53,7 +53,7 @@ final class Config {
final List<Did> dids = new CopyOnWriteArrayList<>();
private boolean hasSim;
String defaultDid;
/** The relay through jai (Relay.java): address, bearer token, and the 32-byte key that seals everything. */
/** The relay server (Relay.java): address, bearer token, and the 32-byte key that seals everything. */
String relayUrl, relayToken;
byte[] relayKey;
/** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */
@@ -127,8 +127,8 @@ final class Config {
if (r != null) {
String url = r.optString("url", ""), token = r.optString("token", "");
byte[] key = android.util.Base64.decode(r.optString("key", ""), android.util.Base64.DEFAULT);
// Only the addresses network_security_config lets through, and a real key.
if (url.matches("http://(100\\.\\d+\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) {
// Plain http only to a tailscale (100.64/10) address or localhost, as the desktop allows, and a real key.
if (url.matches("http://(100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) {
cfg.relayUrl = url;
cfg.relayToken = token;
cfg.relayKey = key;
@@ -430,11 +430,21 @@ public final class MainActivity extends BaseActivity {
String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim();
if (body.isEmpty() && c.lastMediaJson != null) body = "Photo";
String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : "";
preview.setText(who + body);
boolean unread = c.unread > 0 || c.markedUnread;
preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED);
badge.setVisibility(unread ? VISIBLE : GONE);
badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•");
if (c.failed > 0) {
// A text here didn't go out: red, ahead of everything else.
preview.setText("Not sent · " + who + body);
preview.setTextColor(Ui.DANGER);
badge.setVisibility(VISIBLE);
badge.setText("!");
badge.setBackground(Ui.round(Ui.DANGER, Ui.dp(ctx, 20)));
} else {
preview.setText(who + body);
preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED);
badge.setVisibility(unread ? VISIBLE : GONE);
badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•");
badge.setBackground(Ui.round(Ui.ACCENT, Ui.dp(ctx, 20)));
}
via.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : "");
via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE);
}
@@ -19,6 +19,7 @@ final class Notifier {
private Notifier() {}
private static final String CHANNEL = "messages";
private static final String UNSENT = "unsent";
// Only messages this recent notify (not a big catch-up after being offline).
private static final long RECENT = 6 * 60 * 60_000L;
@@ -65,6 +66,44 @@ final class Notifier {
c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode());
}
/**
* Your text didn't go out. Its own channel, whatever the notification
* setting and even with a screen in front: a send that fails quietly is
* the worst thing a phone can do. Do Not Disturb still applies.
*/
static void notifyUnsent(Context c, List<Store.Msg> msgs) {
NotificationManager nm = c.getSystemService(NotificationManager.class);
nm.createNotificationChannel(new NotificationChannel(UNSENT, "Texts that didn't send", NotificationManager.IMPORTANCE_HIGH));
Map<String, List<Store.Msg>> byConv = new LinkedHashMap<>();
for (Store.Msg m : msgs) byConv.computeIfAbsent(m.did + "\n" + m.contact, k -> new ArrayList<>()).add(m);
Store store = Store.get(c);
for (List<Store.Msg> list : byConv.values()) {
Store.Msg first = list.get(0);
String who = Contacts.title(c, first.contact, store.getName(first.did, first.contact));
String title = list.size() > 1 ? list.size() + " texts to " + who + " weren't sent" : "Text to " + who + " wasn't sent";
String preview = first.body.trim().isEmpty() ? "Your message" : "“" + first.body.trim() + "”";
String body = list.size() > 1 ? "Open the chat to retry, edit or delete them."
: preview + " · " + (first.error != null ? first.error : "Open the chat to retry it.");
int id = ("unsent" + first.did + first.contact).hashCode();
PendingIntent pi = PendingIntent.getActivity(c, id, ChatActivity.intent(c, first.did, first.contact),
PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
nm.notify(id, new Notification.Builder(c, UNSENT)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setStyle(new Notification.BigTextStyle().bigText(body))
.setShowWhen(true)
.setAutoCancel(true)
.setContentIntent(pi)
.build());
}
}
/** The chat's open, and its banner says the same. */
static void clearUnsent(Context c, String did, String contact) {
c.getSystemService(NotificationManager.class).cancel(("unsent" + did + contact).hashCode());
}
private static Bundle conversation(String did, String contact) {
Bundle b = new Bundle();
b.putString("did", did);
@@ -28,13 +28,13 @@ import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* The relay through jai (the desktop's src/main/relay.ts; server in
* The relay server (the desktop's src/main/relay.ts; server in
* server/bubble_relay.py): the SIM's texts go to the desktop, texts typed
* there go out over the SIM here, and chat names and read/unread/archived
* stay in step without a cable.
*
* Everything is AES-256-GCM sealed with the key the desktop handed over USB
* (config.json "relay"); jai only passes blobs on. It runs with the checks
* (config.json "relay"); the relay server only passes blobs on. It runs with the checks
* the Rabbit already makes (PollJob) plus one network job after something
* happens here (a text, a send, a swipe), never on a timer of its own: the
* battery pays for nothing new while nothing's going on.
@@ -141,7 +141,7 @@ final class Relay {
// ---- one sync ----
/** One round with jai (more while there's more). Off the main thread; quiet when jai's unreachable. */
/** One round with the relay server (more while there's more). Off the main thread; quiet when it's unreachable. */
static void sync(Context c) {
Config cfg = Config.get(c);
if (!configured(cfg)) return;
@@ -241,11 +241,11 @@ final class Relay {
h.put("Authorization", "Bearer " + cfg.relayToken);
h.put("Content-Type", "application/json");
Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000);
if (r.status == 401) throw new Exception("jai turned down the token (Sync to Rabbit from the desktop again)");
if (r.status != 200) throw new Exception("jai answered " + r.status);
if (r.status == 401) throw new Exception("The relay server turned down the token (Sync to Rabbit from the desktop again)");
if (r.status != 200) throw new Exception("The relay server answered " + r.status);
JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8));
// jai has them now.
// The relay server has them now.
if (resultsPushed > 0) takeList(c, "results", resultsPushed);
if (wantsDone > 0) takeList(c, "wants", wantsDone);
SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]);
@@ -346,6 +346,7 @@ final class Relay {
}
private static void result(Context c, String id, long msgId, String error) {
inflight(c, id, 0);
try {
JSONObject o = new JSONObject().put("t", "sent").put("id", id);
o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL);
@@ -394,6 +395,44 @@ final class Relay {
result(c, id, 0, "It was empty.");
return;
}
Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error));
long temp = Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error));
// Until its result is posted: if this process dies first, the next one
// still answers the desktop (orphaned), so it never waits forever.
if (temp < 0) inflight(c, id, temp);
}
/** Remember (tempId < 0) or forget (0) the local message a desktop send became. */
private static synchronized void inflight(Context c, String id, long tempId) {
SharedPreferences p = prefs(c);
Set<String> s = new HashSet<>(p.getStringSet("inflight", new HashSet<>()));
s.removeIf(e -> e.startsWith(id + "\t"));
if (tempId < 0) s.add(id + "\t" + tempId);
p.edit().putStringSet("inflight", s).commit();
}
/**
* Sends an earlier process left unfinished: those the desktop asked for are
* reported back to it as failed (it alerts there). Returns the others.
*/
static List<Store.Msg> orphaned(Context c, List<Store.Msg> orphans) {
Map<Long, String> byTemp = new HashMap<>();
synchronized (Relay.class) {
for (String e : prefs(c).getStringSet("inflight", new HashSet<>())) {
int tab = e.indexOf('\t');
try {
byTemp.put(Long.parseLong(e.substring(tab + 1)), e.substring(0, tab));
} catch (Exception ignored) {
}
}
// Whatever isn't an orphan finished (or will be answered by this process).
prefs(c).edit().remove("inflight").commit();
}
List<Store.Msg> mine = new ArrayList<>();
for (Store.Msg m : orphans) {
String id = byTemp.get(m.id);
if (id == null) mine.add(m);
else result(c, id, 0, m.error);
}
return mine;
}
}
@@ -69,7 +69,12 @@ final class Sender {
send(ctx, did, contact, text, photos, null);
}
static void send(Context ctx, String did, String contact, String text, List<Photo> photos, Done done) {
/**
* Returns the local id of the (first) pending message. With `done` (the
* desktop's sends over the relay) the outcome goes back to whoever asked,
* who alerts on failure; without, a failure notifies here.
*/
static long send(Context ctx, String did, String contact, String text, List<Photo> photos, Done done) {
Context c = ctx.getApplicationContext();
Config cfg = Config.get(c);
if (cfg.sandbox) {
@@ -81,12 +86,13 @@ final class Sender {
store.confirmPending(id, real);
Sync.changed();
if (done != null) done.done(real, null);
return;
return real;
}
if (cfg.isGv(did)) {
if (photos.isEmpty()) {
enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done);
return enqueue(c, pending(did, contact, text, null), () -> gvSend(c, did, contact, text, null), true, done);
} else {
long first = 0;
// Google Voice carries one photo per message: the text rides with the first.
for (int i = 0; i < photos.size(); i++) {
String body = i == 0 ? text : "";
@@ -95,26 +101,27 @@ final class Sender {
one.add(p);
Store.Msg m = pending(did, contact, body, one);
m.ts += i;
enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null);
long id = enqueue(c, m, () -> gvSend(c, did, contact, body, p), true, i == 0 ? done : null);
if (i == 0) first = id;
}
return first;
}
return;
}
if (Sim.isSim(did)) {
// A long text goes as several SMS parts; photos, voice notes and groups as one MMS.
boolean mms = !photos.isEmpty() || Phone.isGroup(contact);
Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms";
enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, (id, err) -> {
Done told = (id, err) -> {
if (done != null) done.done(id, err);
Relay.soon(c); // the desktop hears about it on the next round
});
return;
};
return enqueue(c, m, () -> mms ? Sim.sendMms(c, contact, text, photos) : Sim.sendSms(c, contact, text), false, told, done == null);
}
boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT;
Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms";
enqueue(c, m, () -> {
return enqueue(c, m, () -> {
VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass);
if (!mms) return api.sendSms(did, contact, text);
List<String> media = new ArrayList<>();
@@ -140,7 +147,11 @@ final class Sender {
return m;
}
private static void enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) {
private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done) {
return enqueue(c, m, attempt, gv, done, done == null);
}
private static long enqueue(Context c, Store.Msg m, Attempt attempt, boolean gv, Done done, boolean alert) {
Store store = Store.get(c);
long tempId = store.insertPending(m);
Sync.changed();
@@ -149,7 +160,28 @@ final class Sender {
String error = deliver(c, store, tempId, attempt, gv, id);
Sync.changed();
if (done != null) done.done(id[0], error);
Store.Msg after = store.getMessage(tempId);
if (alert && after != null && "failed".equals(after.status)) {
List<Store.Msg> one = new ArrayList<>();
one.add(after);
Notifier.notifyUnsent(c, one);
}
});
return tempId;
}
/**
* At startup, the sends an earlier process left unfinished (already marked
* failed): the desktop's go back to it as failed, the rest notify here.
*/
static void recover(Context c, List<Store.Msg> orphans) {
if (orphans.isEmpty()) return;
// Now, before this process's own sends add to the relay's in-flight list.
List<Store.Msg> mine = Relay.orphaned(c, orphans);
new Thread(() -> {
if (!mine.isEmpty()) Notifier.notifyUnsent(c, mine);
Sync.changed();
}, "recover-sends").start();
}
/** Null when it went out (its id in id[0]), else why not. */
@@ -144,7 +144,7 @@ public final class SettingsActivity extends BaseActivity {
}
if (Relay.configured(cfg)) {
section("Relay (jai)");
section("Relay server");
kv("Desktop link", Relay.status(c));
note("Texts typed on the desktop for \"via SIM\" go out at this Rabbit's background check, and chat names and read status"
+ " go both ways. Sealed with a key only the desktop and this Rabbit have.");
@@ -29,7 +29,11 @@ final class Store {
private static final long MATCH_AFTER = 15 * 60_000L;
static synchronized Store get(Context c) {
if (instance == null) instance = new Store(c.getApplicationContext());
if (instance == null) {
instance = new Store(c.getApplicationContext());
// A new process: any send still 'pending' belonged to one that died.
Sender.recover(c.getApplicationContext(), instance.failOrphanedSends());
}
return instance;
}
@@ -222,6 +226,32 @@ final class Store {
db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId});
}
/**
* Sends left 'pending' by an earlier process (Android killed it, or it
* crashed, mid-send): their send loop died with it, so nothing will ever
* finish them. 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 check still replaces it (reconcileSent matches failed rows too).
*/
List<Msg> failOrphanedSends() {
List<Long> ids = new ArrayList<>();
try (Cursor c = db.rawQuery("SELECT id FROM messages WHERE id < 0 AND status = 'pending' AND direction = 'out'", null)) {
while (c.moveToNext()) ids.add(c.getLong(0));
}
List<Msg> out = new ArrayList<>();
for (long id : ids) {
Msg m = getMessage(id);
if (m == null) continue;
// A SIM text may already be with the radio, which sends it whether or not we're alive.
markFailed(id, Sim.isSim(m.did) ? ORPHAN_SIM : ORPHAN);
out.add(getMessage(id));
}
return out;
}
static final String ORPHAN = "bubble stopped before this finished sending, so it most likely didn't go out.";
static final String ORPHAN_SIM = "bubble stopped before the SIM said whether this went out. Check before retrying.";
/** Sent messages that turned up in a poll replace our pending/failed copies. */
void reconcileSent(List<Msg> added) {
List<Msg> sorted = new ArrayList<>(added);
@@ -308,6 +338,7 @@ final class Store {
String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name;
long lastTs;
int unread;
int failed; // your texts here that didn't send
boolean archived, markedUnread;
}
@@ -319,7 +350,8 @@ final class Store {
+ " SELECT l.did, l.contact, l.mts, last.body, last.direction, last.sender, last.media_json,"
+ " (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), CAST(? AS INTEGER))),"
+ " r.archived_at IS NOT NULL, COALESCE(r.marked_unread, 0), r.name"
+ " r.archived_at IS NOT NULL, COALESCE(r.marked_unread, 0), r.name,"
+ " (SELECT COUNT(*) FROM messages m WHERE m.did = l.did AND m.contact = l.contact AND m.id < 0 AND m.status = 'failed')"
+ " FROM latest l JOIN messages last ON last.id ="
+ " (SELECT id FROM messages m WHERE m.did = l.did AND m.contact = l.contact ORDER BY ts DESC, id DESC LIMIT 1)"
+ " LEFT JOIN read_state r ON r.did = l.did AND r.contact = l.contact"
@@ -338,6 +370,7 @@ final class Store {
v.archived = c.getInt(8) != 0;
v.markedUnread = c.getInt(9) != 0;
v.name = c.getString(10);
v.failed = c.getInt(11);
if (archived == null || v.archived == archived) out.add(v);
}
}
@@ -1,11 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Everything is https, except the relay on jai over tailscale (WireGuard
<!-- Everything is https, except the relay server over tailscale (WireGuard
already encrypts that hop, and what it carries is sealed: Relay.java) and
localhost for testing it with adb reverse. -->
localhost for testing it with adb reverse. Its address is a setting, so
cleartext can't be pinned to it here: Config only accepts http:// for a
tailscale (100.64/10) address or 127.0.0.1, and nothing else uses http. -->
<network-security-config>
<base-config cleartextTrafficPermitted="false" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">100.69.139.40</domain>
<domain includeSubdomains="false">127.0.0.1</domain>
</domain-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
+2 -2
View File
@@ -26,8 +26,8 @@ import sys
import zipfile
from pathlib import Path
VERSION_NAME = "0.7.7"
VERSION_CODE = 15
VERSION_NAME = "0.7.9"
VERSION_CODE = 17
PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev"
Binary file not shown.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "voipms-desktop",
"version": "0.7.1",
"version": "0.9.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "voipms-desktop",
"version": "0.7.1",
"version": "0.9.5",
"hasInstallScript": true,
"dependencies": {
"better-sqlite3": "^13.0.3"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "voipms-desktop",
"productName": "bubble",
"version": "0.9.4",
"version": "0.9.9",
"description": "Signal-style desktop SMS client for voip.ms",
"author": "trav <trav@teafry.me>",
"private": true,
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"version_name": "0.7.7", "version_code": 15, "package": "me.teafry.voipmessages"}
{"version_name": "0.7.9", "version_code": 17, "package": "me.teafry.voipmessages"}
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
# Deploy bubble-relay to jai (see ~/Documents/shared-resources/jai.html#run).
# jai is production: this only ever touches ~/Documents/bubble-server and its
# own screen session, and installs nothing.
#
# scripts/deploy-jai.sh copy the code and (re)start the service
# scripts/deploy-jai.sh --stop stop it
# scripts/deploy-jai.sh --token print the bearer token, for Settings → Rabbit relay on the desktop
#
# What runs is server/run.sh, also started by jai's ~/startup.sh (re-run by its
# watchdog every 5 minutes), so it comes back after a crash or a reboot.
set -euo pipefail
HOST=${JAI_HOST:-jai-ext}
DIR=/home/jai/Documents/bubble-server
NAME=bubble-relay
cd "$(dirname "$0")/.."
case "${1:-}" in
--token) ssh "$HOST" "cat $DIR/data/token"; echo; exit 0 ;;
--stop) ssh "$HOST" "screen -S $NAME -X quit || true"; echo "stopped"; exit 0 ;;
esac
ssh "$HOST" "mkdir -p $DIR/app $DIR/data ~/service-logs && chmod 700 $DIR $DIR/data"
rsync -a server/bubble_relay.py server/run.sh "$HOST:$DIR/app/"
ssh "$HOST" bash -s <<REMOTE
set -e
screen -S $NAME -X quit 2>/dev/null || true
sleep 1
screen -dmS $NAME bash -c 'bash $DIR/app/run.sh 2>&1 | tee ~/service-logs/$NAME.log'
sleep 2
for pid in \$(pgrep -f bubble_relay.py); do echo 1000 > /proc/\$pid/oom_score_adj; done
curl -s -m 5 http://100.69.139.40:8080/health; echo
REMOTE
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
# Deploy the relay server (server/bubble_relay.py) over ssh. Where it goes
# comes from scripts/relay.env (not in git; see scripts/relay.env.example).
# This only touches $RELAY_DIR and its own screen session, and installs nothing.
#
# scripts/deploy-relay.sh copy the code and (re)start it
# scripts/deploy-relay.sh --stop stop it
# scripts/deploy-relay.sh --token print the bearer token, for Settings → Relay server on the desktop
#
# What runs is server/run.sh; have the server start that at boot too, e.g.
# screen -dmS bubble-relay bash -c 'bash $RELAY_DIR/app/run.sh'
set -euo pipefail
cd "$(dirname "$0")/.."
[ -f scripts/relay.env ] || { echo "No scripts/relay.env: copy scripts/relay.env.example and fill it in." >&2; exit 1; }
. scripts/relay.env
: "${RELAY_SSH:?}" "${RELAY_DIR:?}" "${RELAY_BIND:?}"
PORT=${RELAY_PORT:-8080}
NAME=bubble-relay
case "${1:-}" in
--token) ssh "$RELAY_SSH" "cat $RELAY_DIR/data/token"; echo; exit 0 ;;
--stop) ssh "$RELAY_SSH" "screen -S $NAME -X quit || true"; echo "stopped"; exit 0 ;;
esac
ssh "$RELAY_SSH" "mkdir -p $RELAY_DIR/app $RELAY_DIR/data ~/service-logs && chmod 700 $RELAY_DIR $RELAY_DIR/data"
rsync -a server/bubble_relay.py server/run.sh "$RELAY_SSH:$RELAY_DIR/app/"
printf 'RELAY_BIND=%q\nRELAY_PORT=%q\n' "$RELAY_BIND" "$PORT" | ssh "$RELAY_SSH" "cat > $RELAY_DIR/app/relay.env"
ssh "$RELAY_SSH" bash -s <<REMOTE
set -e
screen -S $NAME -X quit 2>/dev/null || true
sleep 1
screen -dmS $NAME bash -c 'bash $RELAY_DIR/app/run.sh 2>&1 | tee ~/service-logs/$NAME.log'
sleep 2
for pid in \$(pgrep -f bubble_relay.py); do echo 1000 > /proc/\$pid/oom_score_adj; done
curl -s -m 5 http://$RELAY_BIND:$PORT/health; echo
REMOTE
+5
View File
@@ -0,0 +1,5 @@
# Copy to scripts/relay.env (git ignores it) for scripts/deploy-relay.sh.
RELAY_SSH=myserver # ssh host (an alias from ~/.ssh/config is fine)
RELAY_DIR=/home/me/bubble-server # on the server: app/ and data/ (token, mailbox) go here
RELAY_BIND=100.101.102.103 # the server's tailscale address; the desktop's Settings → Relay server uses http://<this>:<port>
RELAY_PORT=8080
Binary file not shown.
+4 -3
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env python3
"""bubble-relay: a mailbox between the desktop app and the Rabbit R1. Runs on jai.
"""bubble-relay: a mailbox between the desktop app and the Rabbit R1. Runs on a
server of yours that both can reach (a tailscale address is the easy way).
It never sees a message: every blob is AES-256-GCM sealed by the apps with a
key jai doesn't have (the desktop makes it and hands it to the Rabbit over
key the server doesn't have (the desktop makes it and hands it to the Rabbit over
USB). This only stores opaque base64 strings, hands each device what the
other one posted, and forgets them once picked up (or after KEEP_DAYS).
@@ -19,7 +20,7 @@ to it, which the other side posted, so those are deleted. `more` = there's
more than fits in one answer: call again with the new cursor. A cursor past
anything this server ever issued (a wiped server) means "from the start".
python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data DIR
python3 bubble_relay.py --host <tailscale address> --port 8080 --data DIR
"""
import argparse
+6 -3
View File
@@ -1,4 +1,7 @@
#!/bin/bash
# The one real command line for bubble-relay on jai (~/startup.sh and scripts/deploy-jai.sh both run this).
cd /home/jai/Documents/bubble-server/app || exit 1
exec python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data /home/jai/Documents/bubble-server/data
# The one real command line for the relay server (scripts/deploy-relay.sh runs
# it; run it at boot too). relay.env next to it, written by the deploy, says
# which address and port to listen on.
cd "$(dirname "$(readlink -f "$0")")" || exit 1
. ./relay.env
exec python3 bubble_relay.py --host "$RELAY_BIND" --port "${RELAY_PORT:-8080}" --data ../data
+17
View File
@@ -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
+65 -8
View File
@@ -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, notifyNew } 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'
@@ -49,7 +49,7 @@ let dids: Did[] = []
let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | undefined
// The relay through jai: the Rabbit's SIM, names and read state (relay.ts).
// The relay server: the Rabbit's SIM, names and read state (relay.ts).
let relay: RelayEngine | undefined
const send = (channel: string, ...args: unknown[]): void => {
@@ -101,6 +101,13 @@ function onNewMessages(msgs: NewMessage[]): void {
if (settings.notifications && !win?.isFocused()) notifyNew(msgs, { db, contacts, onClick: openFromNotification })
}
// Read/unread changed from outside the app: chats read elsewhere lose their
// notifications here too.
function readStateChanged(): void {
sweepNotifications((did, contact) => db.hasUnread(did, contact))
send('conversationsChanged')
}
function openFromNotification(key: { did: string; contact: string }): void {
if (!win || win.isDestroyed()) return
if (win.isMinimized()) win.restore()
@@ -112,7 +119,7 @@ function openFromNotification(key: { did: string; contact: string }): void {
const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's, then
// the Rabbit's SIM (through jai).
// the Rabbit's SIM (through the relay server).
function allDids(): Did[] {
const n = gvNumber()
const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids]
@@ -129,15 +136,16 @@ function startRelay(): void {
if (!cfg) return
relay = new RelayEngine(db, media, cfg, settings.pollSeconds)
relay.on('messages', onNewMessages)
relay.on('changed', () => send('conversationsChanged'))
relay.on('changed', readStateChanged)
relay.on('status', () => send('relayStatus', relay?.status()))
relay.on('unsent', (m: Message) => alertUnsent([m]))
relay.start()
}
// A text over the Rabbit's SIM: pending here until the Rabbit's next check
// sends it and says how it went (relay.ts).
function relaySend(contact: string, text: string, refs: MediaRef[]): void {
if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → jai.')
if (!relay) throw new Error('The Rabbit relay is off: connect it in Settings → Relay server.')
const kind = refs.length || isGroup(contact) ? 'mms' : 'sms'
const tempId = db.insertPending({ did: SIM_DID, contact, direction: 'out', body: text, ts: Date.now(), kind, ...(refs.length ? { media: refs } : {}) })
relay.send(tempId, contact, text, refs)
@@ -159,7 +167,7 @@ function startGvSync(): void {
gvSync = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor })
gvSync.on('messages', onNewMessages)
gvSync.on('status', () => send('syncStatus', syncStatus()))
gvSync.on('readChanged', () => send('conversationsChanged'))
gvSync.on('readChanged', readStateChanged)
gvSync.start()
}
@@ -414,6 +422,7 @@ function enqueue<T>(key: string, job: () => Promise<T>): Promise<T> {
async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> {
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}`, () =>
@@ -425,11 +434,49 @@ async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>
})
)
} 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<number>()
// 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<number>) => (): Promise<number> => {
if (!api) throw new VoipMsError('not_signed_in')
return call(api)
@@ -682,8 +729,8 @@ function registerIpc(): void {
signal: AbortSignal.timeout(15_000)
}).catch(() => undefined)
if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`)
if (res.status === 401) throw new Error('jai turned down that token.')
if (!res.ok) throw new Error(`jai answered ${res.status}.`)
if (res.status === 401) throw new Error('The relay server turned down that token.')
if (!res.ok) throw new Error(`The relay server answered ${res.status}.`)
// Keep the key across reconnects so the Rabbit's copy stays good.
saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() })
startRelay()
@@ -782,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()
@@ -801,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) => {
@@ -829,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)
})
@@ -837,7 +892,9 @@ let quitting = false
app.on('before-quit', (e) => {
if (quitting || !db) return
e.preventDefault()
if (!okToLeave()) return
quitting = true
closeAllNotifications()
sync?.stop()
stopGv()
relay?.stop()
+47 -1
View File
@@ -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<string, Set<Notification>>()
// "Not sent" alerts, kept referenced for their click handlers.
const unsent = new Set<Notification>()
const convKey = (did: string, contact: string): string => `${did}\n${contact}`
// The conversation's been read: its notifications are stale.
@@ -31,6 +35,24 @@ export function clearNotifications(did: string, contact: string): void {
for (const n of shown) n.close()
}
// Read state changed somewhere else (the Rabbit, the phone, Google Voice's
// site): take down what's no longer unread, like the Android app's sweep.
export function sweepNotifications(isUnread: (did: string, contact: string) => boolean): void {
for (const key of [...live.keys()]) {
const [did, contact] = key.split('\n')
if (!isUnread(did, contact)) clearNotifications(did, contact)
}
}
// Quitting: once this process is gone nothing can close them (or answer
// their clicks), so they'd sit in the list for good. Take them all down.
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)
export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did: string, contact: string): string {
@@ -42,7 +64,7 @@ export function conversationTitle(db: MessageDb, contacts: ContactDirectory, did
.join(', ')
}
function preview(m: NewMessage): string {
function preview(m: Pick<NewMessage, 'body' | 'media'>): string {
const reaction = reactionPreview(m.body)
if (reaction) return reaction
const edit = editPreview(m.body)
@@ -82,3 +104,27 @@ export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyD
n.show()
}
}
// Your text didn't go out. Normal urgency (new messages are low): it pops up
// unless Do Not Disturb is on, and stays in the list either way. Never
// critical, which would break through Do Not Disturb.
export function notifyUnsent(msgs: Message[], { db, contacts, onClick }: NotifyDeps): void {
if (!Notification.isSupported()) return
const byConv = new Map<string, Message[]>()
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: 'normal'
})
// 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()
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ export interface RabbitConfig {
gvoice: { number: string; cookies: Record<string, string> } | null
dids: Array<{ did: string; description: string }>
defaultDid?: string
// The relay through jai (relay.ts): address, token, and the key that seals everything.
// The relay server (relay.ts): address, token, and the key that seals everything.
relay?: { url: string; token: string; key: string } | null
}
+13 -10
View File
@@ -1,11 +1,11 @@
// The relay through jai: the Rabbit's SIM texts reach this computer, texts
// The relay server: the Rabbit's SIM texts reach this computer, texts
// typed here go out over the Rabbit's SIM, and chat names and read/unread/
// archived stay in step between the two, all without a USB cable.
//
// jai only ever holds sealed blobs: AES-256-GCM with a key made here and handed
// The relay server only ever holds sealed blobs: AES-256-GCM with a key made here and handed
// to the Rabbit over USB (Install/Sync to Rabbit puts it in the app's private
// config.json). The bearer token only lets a device talk to the mailbox; the
// key is what keeps jai (and anyone else on it) from reading or forging
// key is what keeps the relay server (and anyone else on it) from reading or forging
// anything. Server: server/bubble_relay.py. Android side: Relay.java.
//
// What travels (inside the seal; `t` is the kind):
@@ -27,7 +27,6 @@ import type { MessageDb, NameChange, NewMessage, ReadState } from './db'
import type { MediaStore } from './media'
export { SIM_DID } from '@shared/phone'
export const DEFAULT_URL = 'http://100.69.139.40:8080'
export interface RelayConfig {
url: string
@@ -228,10 +227,10 @@ export class RelayEngine extends EventEmitter {
body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }),
signal: AbortSignal.timeout(120_000)
})
if (res.status === 401) throw new Error('jai turned down the token. Check it in Settings → jai.')
if (!res.ok) throw new Error(`jai answered ${res.status}`)
if (res.status === 401) throw new Error('The relay server turned down the token. Check it in Settings → Relay server.')
if (!res.ok) throw new Error(`The relay server answered ${res.status}`)
const body = (await res.json()) as { cursor: number; events: string[]; more: boolean }
// Only now that jai has them: out of the outbox.
// Only now that the relay server has them: out of the outbox.
if (push.length) this.db.db.prepare('DELETE FROM relay_outbox WHERE seq <= ?').run(push.at(-1)!.seq)
for (const blob of body.events) this.handle(unseal(this.key, 'rabbit', blob) as Incoming | undefined)
this.db.set('relay_cursor', String(body.cursor))
@@ -240,8 +239,8 @@ export class RelayEngine extends EventEmitter {
this.lastSync = Date.now()
this.error = undefined
} catch (e) {
// Can't reach jai: an ordinary, quiet outcome; try again next round.
this.error = (e as Error).name === 'TimeoutError' ? "jai didn't answer" : (e as Error).message
// Can't reach the relay server: an ordinary, quiet outcome; try again next round.
this.error = (e as Error).name === 'TimeoutError' ? "The relay server didn't answer" : (e as Error).message
}
this.emit('status', this.status())
}
@@ -298,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')
}
+32 -1
View File
@@ -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,22 @@ 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])
// Edit on a text that wasn't sent: its words (and pictures) go back into the
// box, and the failed copy goes, so what's sent next is the edited one.
const editFailed = useCallback(async (m: Message) => {
const files = await Promise.all(
(m.media ?? []).map(async (ref, i) => {
const { mime, data } = await window.api.readMedia(m.id, i)
return new File([data], ref.file ?? `photo-${i + 1}`, { type: mime })
})
).catch(() => undefined)
if (!files) return // keep it rather than lose its pictures
composer.current?.edit(m.body, files)
await window.api.deleteFailed(m.id)
}, [])
const indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
const flash = useCallback((id: number) => {
@@ -177,6 +193,10 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
(id: number) => {
const index = indexOf(id)
if (index < 0) return
// Leaving the bottom: otherwise pictures that finish loading around the
// target (onMediaLoad) see the stale "at bottom" and snap back down
// before Virtuoso reports we've moved.
atBottom.current = false
virtuoso.current?.scrollToIndex({ index, align: 'center' })
flash(id)
},
@@ -389,6 +409,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
reactions={folded.reactions.get(r.m.id)}
onShowReactions={showReactions}
onMenu={showMsgMenu}
onEditFailed={editFailed}
versions={folded.versions.get(r.m.id)}
onShowEdits={showEdits}
/>
@@ -398,6 +419,16 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
)}
</div>
{unsent.length > 0 && (
<div className="unsent-banner" role="alert">
<AlertIcon />
<span className="unsent-text">
<b>{unsent.length > 1 ? `${unsent.length} of your texts weren't sent.` : "Your text wasn't sent."}</b> Retry or delete{' '}
{unsent.length > 1 ? 'them' : 'it'} below.
</span>
<button onClick={() => scrollTo(unsent[0].id)}>Show</button>
</div>
)}
<Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
{dragging && <div className="drop-hint">Drop to attach</div>}
{lightbox && (
+10 -1
View File
@@ -17,6 +17,8 @@ const attachmentDrafts = new Map<string, Attachment[]>()
export interface ComposerHandle {
addFiles: (files: File[]) => void
// Back into the box to change before sending again (a text that wasn't sent).
edit: (text: string, files: File[]) => void
}
interface Props {
@@ -118,7 +120,14 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P
textarea.current?.focus()
}
useImperativeHandle(ref, () => ({ addFiles }))
const edit = (body: string, files: File[]): void => {
// Anything already being typed stays, after it.
setText((cur) => (cur.trim() ? `${body}\n${cur}` : body))
if (files.length) addFiles(files)
textarea.current?.focus()
}
useImperativeHandle(ref, () => ({ addFiles, edit }))
const remove = (a: Attachment): void => {
URL.revokeObjectURL(a.previewUrl)
@@ -117,7 +117,15 @@ const ConversationRow = memo(function ConversationRow({
<span className="row-time">{shortTime(conv.lastTs)}</span>
</div>
<div className="row-bottom">
<span className="row-preview">{preview}</span>
<span className="row-preview">
{conv.failed > 0 && <b className="row-unsent">Not sent · </b>}
{preview}
</span>
{conv.failed > 0 && (
<span className="badge unsent" title={conv.failed > 1 ? `${conv.failed} texts weren't sent` : "A text wasn't sent"}>
!
</span>
)}
{conv.unread > 0 ? (
<span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>
) : (
+21 -5
View File
@@ -88,9 +88,13 @@ interface Props {
onOpenMedia: (id: number, index: number) => void
onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void
onMediaLoad: () => void
onEditFailed?: (m: Message) => void
}
export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMenu, reactions, onShowReactions, onMenu, versions, onShowEdits, groupStart, groupEnd, flash, highlight, onOpenMedia, onMediaMenu, onMediaLoad }: Props) {
// 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, onEditFailed }: Props) {
const media = m.media ?? []
const cls = [
'msg',
@@ -137,6 +141,11 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
{m.status === 'pending' && (
<span className="status" title="Sending…">
<ClockIcon />
{/* Appears once a send has taken a while (the negative delay
counts time already spent, so it survives re-renders). */}
<span className="slow-send" style={{ animationDelay: `${SLOW_SEND_MS - (Date.now() - m.ts)}ms` }}>
Still sending…
</span>
</span>
)}
</span>
@@ -152,10 +161,17 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
</button>
)}
{m.status === 'failed' && (
<div className="failed-row">
<AlertIcon /> Not sent{m.error ? `: ${m.error}` : ''} ·
<button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>·
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
<div className="failed-row" role="alert">
<span className="failed-why">
<AlertIcon /> <b>Not sent.</b> {m.error ?? ''}
</span>
<span className="failed-actions">
<button className="failed-retry" onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>
Retry
</button>
{onEditFailed && <button onClick={() => onEditFailed(m)}>Edit</button>}
<button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
</span>
</div>
)}
</div>
@@ -225,7 +225,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
),
Contacts: <ContactsSection value={s.contactBook} onChange={(contactBook) => change({ ...s, contactBook })} />,
Rabbit: <RabbitSection onChanged={onChanged} />,
jai: <RelaySection onChanged={onChanged} />,
'Relay server': <RelaySection onChanged={onChanged} />,
Storage: (
<section className="group">
<h3>Storage &amp; backups</h3>
@@ -499,10 +499,10 @@ function RabbitSection({ onChanged }: { onChanged: () => void }) {
)
}
// The Rabbit's SIM (and names + read status) through jai, no cable needed.
// The Rabbit's SIM (and names + read status) through the relay server, no cable needed.
function RelaySection({ onChanged }: { onChanged: () => void }) {
const [st, setSt] = useState<RelayStatus>()
const [url, setUrl] = useState('http://100.69.139.40:8080')
const [url, setUrl] = useState('')
const [token, setToken] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>()
@@ -550,10 +550,10 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
: undefined
return (
<section className="group">
<h3>Rabbit relay</h3>
<h3>Relay server</h3>
<p className="muted small">
Texts the Rabbit's SIM card sends and gets show up here, you can text from it here (as "Rabbit SIM"), and chat names and
read/unread/archived stay in step with the Rabbit without plugging it in. It goes through jai, which only passes on sealed messages
read/unread/archived stay in step with the Rabbit without plugging it in. It goes through your relay server (server/bubble_relay.py), which only passes on sealed messages
it can't read: the key stays on this computer and the Rabbit. A text sent from here goes out at the Rabbit's next background check
(Settings there: how often), so it can take a while.
</p>
@@ -583,7 +583,7 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
<>
<label className="field">
Address
<input value={url} onChange={(e) => setUrl(e.target.value)} spellCheck={false} />
<input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="http://100.x.y.z:8080" spellCheck={false} />
</label>
<label className="field">
Token
@@ -591,12 +591,12 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
type="password"
value={token}
onChange={(e) => setToken(e.target.value)}
placeholder="from scripts/deploy-jai.sh --token"
placeholder="from scripts/deploy-relay.sh --token"
autoComplete="off"
/>
</label>
<div className="btn-row">
<button className="primary" disabled={busy || !token.trim()} onClick={connect}>
<button className="primary" disabled={busy || !url.trim() || !token.trim()} onClick={connect}>
Connect
</button>
</div>
+143 -18
View File
@@ -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;
+1 -1
View File
@@ -8,7 +8,7 @@ export function normalizeNumber(raw: string): string {
return digits
}
// The Rabbit's SIM, reached through jai (main/relay.ts): a number we text
// The Rabbit's SIM, reached through the relay server (main/relay.ts): a number we text
// from that isn't a phone number here.
export const SIM_DID = 'sim'
+1
View File
@@ -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
}
+14
View File
@@ -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 })
+5 -5
View File
@@ -3,16 +3,16 @@ import { charCount, formatNumber, normalizeNumber } from '@shared/phone'
describe('phone numbers', () => {
it('normalizes NANP numbers to 10 digits', () => {
expect(normalizeNumber('+1 (541) 280-2626')).toBe('5412802626')
expect(normalizeNumber('15412802626')).toBe('5412802626')
expect(normalizeNumber('541.280.2626')).toBe('5412802626')
expect(normalizeNumber('tel:+15412802626')).toBe('5412802626')
expect(normalizeNumber('+1 (541) 555-0142')).toBe('5415550142')
expect(normalizeNumber('15415550142')).toBe('5415550142')
expect(normalizeNumber('541.555.0142')).toBe('5415550142')
expect(normalizeNumber('tel:+15415550142')).toBe('5415550142')
})
it('leaves short codes alone', () => {
expect(normalizeNumber('72975')).toBe('72975')
})
it('formats', () => {
expect(formatNumber('5412802626')).toBe('(541) 280-2626')
expect(formatNumber('5415550142')).toBe('(541) 555-0142')
expect(formatNumber('72975')).toBe('72975')
})
})
+1 -1
View File
@@ -1,7 +1,7 @@
// The relay against the dev app on a plugged-in Rabbit (DEVICE=1 npm test --
// test/relay.device.test.ts). A throwaway local relay, reached from the Rabbit
// through adb reverse; the dev app's made-up data (tools/push_sandbox.py).
// Never the real app, never jai.
// Never the real app, never the real relay server.
import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
import fs from 'node:fs'
import net from 'node:net'
+2 -2
View File
@@ -73,7 +73,7 @@ describe('relay', () => {
})
it('only sends the token to tailscale or https', () => {
expect(checkUrl('http://100.69.139.40:8080/')).toBe('http://100.69.139.40:8080')
expect(checkUrl('http://100.101.102.103:8080/')).toBe('http://100.101.102.103:8080')
expect(() => checkUrl('http://example.com')).toThrow()
expect(checkUrl('https://example.com')).toBe('https://example.com')
})
@@ -143,7 +143,7 @@ describe('relay', () => {
const ref = await media.resolve(oldMms, 0)
expect(fs.readFileSync(media.filePath(ref!.file!)).toString()).toBe('fake png')
// Picked up = gone from jai.
// Picked up = gone from the relay server.
expect(await rabbit(key)).toEqual([])
engine.stop()
db.close()
+4 -4
View File
@@ -24,7 +24,7 @@ const raw = (id: number, date: string, type = '1'): RawSms => ({
date: `${date} 12:00:00`,
type,
did: '15550001111',
contact: '5412802626',
contact: '5415550142',
message: `m${id}`
})
@@ -33,7 +33,7 @@ describe('toNewMessage', () => {
expect(toNewMessage(raw(7, '2024-02-03', '0'))).toEqual({
id: 7,
did: '5550001111',
contact: '5412802626',
contact: '5415550142',
direction: 'out',
body: 'm7',
ts: Date.UTC(2024, 1, 3, 12)
@@ -109,12 +109,12 @@ describe('SyncEngine poll', () => {
const db = new MessageDb(path.join(dir, 'm.db'))
db.set('backfill_done', '1')
const sent = { ...raw(42, ymd(Date.now()), '0'), message: 'see you at 8' }
const t = db.insertPending({ did: '5550001111', contact: '5412802626', direction: 'out', body: 'see you at 8', ts: toNewMessage(sent).ts })
const t = db.insertPending({ did: '5550001111', contact: '5415550142', direction: 'out', body: 'see you at 8', ts: toNewMessage(sent).ts })
db.markFailed(t, "voip.ms didn't respond in time.")
const engine = new SyncEngine(db, fakeApi([sent]) as unknown as VoipMs, { pollSeconds: 3600, dids: [], backfillFloor: '2010-01-01' })
await engine.pollNow()
expect(db.getMessage(t)).toBeUndefined()
expect(db.getConversationMessages('5550001111', '5412802626').map((m) => [m.id, m.status])).toEqual([[42, 'delivered']])
expect(db.getConversationMessages('5550001111', '5415550142').map((m) => [m.id, m.status])).toEqual([[42, 'delivered']])
db.close()
fs.rmSync(dir, { recursive: true, force: true })
})
+10 -10
View File
@@ -6,19 +6,19 @@ describe('parseVCard', () => {
const card = [
'BEGIN:VCARD',
'VERSION:3.0',
'FN:Collette Shade',
'N:Shade;Collette;;;',
'TEL;X-EVOLUTION-E164=4434655721,;VALUE=UNKNOWN;TYPE=CELL:(443) 465-5721',
'TEL;X-EVOLUTION-E164=5412802626,"+1";X-NC-SCOPE="v2-local";TYPE=VOICE:+1541',
' 2802626',
'FN:Alex Example',
'N:Example;Alex;;;',
'TEL;X-EVOLUTION-E164=4435550143,;VALUE=UNKNOWN;TYPE=CELL:(443) 555-0143',
'TEL;X-EVOLUTION-E164=5415550142,"+1";X-NC-SCOPE="v2-local";TYPE=VOICE:+1541',
' 5550142',
'PHOTO;VALUE=BINARY:https://lh5.googleusercontent.com/-abc/photo.jpg',
'END:VCARD'
].join('\r\n')
const c = parseVCard(card)
expect(c.name).toBe('Collette Shade')
expect(c.name).toBe('Alex Example')
expect(c.tels).toEqual([
{ number: '4434655721', label: 'cell' },
{ number: '5412802626', label: undefined }
{ number: '4435550143', label: 'cell' },
{ number: '5415550142', label: undefined }
])
expect(c.photo).toEqual({ kind: 'url', url: 'https://lh5.googleusercontent.com/-abc/photo.jpg' })
})
@@ -40,8 +40,8 @@ describe('parseVCard', () => {
})
it('handles grouped properties and escaped text', () => {
const c = parseVCard('BEGIN:VCARD\nitem1.FN:Smith\\, John\nitem1.TEL;type=CELL:+1 541 280 2626\nEND:VCARD')
const c = parseVCard('BEGIN:VCARD\nitem1.FN:Smith\\, John\nitem1.TEL;type=CELL:+1 541 555 0142\nEND:VCARD')
expect(c.name).toBe('Smith, John')
expect(c.tels[0]).toEqual({ number: '5412802626', label: 'cell' })
expect(c.tels[0]).toEqual({ number: '5415550142', label: 'cell' })
})
})