Compare commits

..
5 Commits
38 changed files with 690 additions and 145 deletions
+1
View File
@@ -11,3 +11,4 @@ android/build/
CLAUDE.md CLAUDE.md
android/*.keystore android/*.keystore
__pycache__/ __pycache__/
scripts/relay.env
+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 - Keeps your whole message history locally (SQLite), with full-text search
- Group chats, MMS, reactions, emoji shortcodes, GNOME contacts - 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 ## 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 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 and group chats as MMS (needs mobile data on). The dev app's sandbox never
uses the SIM. 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` `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 (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 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 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 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 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 http is allowed only to a tailscale (100.64/10) address and localhost
(`res/xml/network_security_config.xml`). (`Config`; `res/xml/network_security_config.xml` lets cleartext through).
- The scroll wheel is left alone: it stays the volume control (and volume - The scroll wheel is left alone: it stays the volume control (and volume
down + the side button still takes a screenshot). down + the side button still takes a screenshot).
@@ -46,6 +46,7 @@ public final class ChatActivity extends BaseActivity {
private ListView list; private ListView list;
private TextView titleView, subView, counter, attach, send; private TextView titleView, subView, counter, attach, send;
private EditText input; private EditText input;
private TextView unsentBanner;
private LinearLayout header, composerBox, tray, fromRow; private LinearLayout header, composerBox, tray, fromRow;
// The keyboard is up: the composer shrinks so what's being typed and the // The keyboard is up: the composer shrinks so what's being typed and the
// last few messages both fit above it (see setCompact). // last few messages both fit above it (see setCompact).
@@ -106,6 +107,21 @@ public final class ChatActivity extends BaseActivity {
list.setAdapter(adapter); list.setAdapter(adapter);
root.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1)); 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()); root.addView(composer());
setContentView(root); setContentView(root);
root.getViewTreeObserver().addOnGlobalLayoutListener(() -> { root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
@@ -246,6 +262,7 @@ public final class ChatActivity extends BaseActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
Notifier.clear(this, did, contact); Notifier.clear(this, did, contact);
Notifier.clearUnsent(this, did, contact);
} }
@Override @Override
@@ -310,6 +327,11 @@ public final class ChatActivity extends BaseActivity {
View firstView = list.getChildAt(0); View firstView = list.getChildAt(0);
Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null; Object anchor = !atBottom && firstPos < rows.size() ? rows.get(firstPos) : null;
int anchorTop = firstView == null ? 0 : firstView.getTop(); 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(); rows.clear();
for (int i = 0; i < msgs.size(); i++) { for (int i = 0; i < msgs.size(); i++) {
Store.Msg m = msgs.get(i); Store.Msg m = msgs.get(i);
@@ -644,7 +666,8 @@ public final class ChatActivity extends BaseActivity {
bubble.addView(media); bubble.addView(media);
bubble.addView(body); bubble.addView(body);
bubble.addView(meta); 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 = Ui.text(c, "", Ui.T_SMALL, Ui.TEXT);
reacts.setBackground(Ui.round(Ui.BUBBLE_IN, Ui.dp(c, 30))); 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)); 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); setGravity(out ? Gravity.END : Gravity.START);
((LayoutParams) bubble.getLayoutParams()).gravity = 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.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); bubble.setMinimumWidth(0);
// Keep bubbles to ~80% of the width. // Keep bubbles to ~80% of the width.
body.setMaxWidth(Math.round(getResources().getDisplayMetrics().widthPixels * 0.72f)); 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); meta.setTextColor(out ? 0xB3FFFFFF : Ui.MUTED);
Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true); Ui.glyph(meta, "pending".equals(msg.status) ? Glyph.Kind.CLOCK : null, true);
failed.setVisibility("failed".equals(msg.status) ? VISIBLE : GONE); 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); List<Reactions.Reaction> rs = reactions.get(msg.id);
reacts.setVisibility(rs == null ? GONE : VISIBLE); reacts.setVisibility(rs == null ? GONE : VISIBLE);
if (rs != null) { if (rs != null) {
@@ -861,7 +889,33 @@ public final class ChatActivity extends BaseActivity {
Store.get(this).deleteMessage(m.id); Store.get(this).deleteMessage(m.id);
changed(); changed();
}) })
.setNeutralButton("Cancel", null) .setNeutralButton("Edit", (d, w) -> editFailed(m))
.show(); .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<>(); final List<Did> dids = new CopyOnWriteArrayList<>();
private boolean hasSim; private boolean hasSim;
String defaultDid; 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; String relayUrl, relayToken;
byte[] relayKey; byte[] relayKey;
/** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */ /** Made-up data for testing (android/tools/push_sandbox.py): never goes online. */
@@ -127,8 +127,8 @@ final class Config {
if (r != null) { if (r != null) {
String url = r.optString("url", ""), token = r.optString("token", ""); String url = r.optString("url", ""), token = r.optString("token", "");
byte[] key = android.util.Base64.decode(r.optString("key", ""), android.util.Base64.DEFAULT); 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. // 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\\.\\d+\\.\\d+\\.\\d+|127\\.0\\.0\\.1)(:\\d+)?|https://[^/]+") && !token.isEmpty() && key.length == 32) { 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.relayUrl = url;
cfg.relayToken = token; cfg.relayToken = token;
cfg.relayKey = key; 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(); String body = reaction != null ? reaction : c.lastBody == null ? "" : c.lastBody.replaceAll("\\s+", " ").trim();
if (body.isEmpty() && c.lastMediaJson != null) body = "Photo"; if (body.isEmpty() && c.lastMediaJson != null) body = "Photo";
String who = "out".equals(c.lastDirection) ? "You: " : group && c.lastSender != null ? Contacts.firstName(ctx, c.lastSender) + ": " : ""; 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; boolean unread = c.unread > 0 || c.markedUnread;
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); preview.setTextColor(unread ? Ui.TEXT : Ui.MUTED);
badge.setVisibility(unread ? VISIBLE : GONE); badge.setVisibility(unread ? VISIBLE : GONE);
badge.setText(c.unread > 99 ? "99+" : c.unread > 0 ? String.valueOf(c.unread) : "•"); 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.setText(Config.get(ctx).dids.size() > 1 ? Ui.via(ctx, c.did) : "");
via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE); via.setVisibility(Config.get(ctx).dids.size() > 1 ? VISIBLE : GONE);
} }
@@ -19,6 +19,7 @@ final class Notifier {
private Notifier() {} private Notifier() {}
private static final String CHANNEL = "messages"; 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). // Only messages this recent notify (not a big catch-up after being offline).
private static final long RECENT = 6 * 60 * 60_000L; private static final long RECENT = 6 * 60 * 60_000L;
@@ -65,6 +66,44 @@ final class Notifier {
c.getSystemService(NotificationManager.class).cancel((did + contact).hashCode()); 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) { private static Bundle conversation(String did, String contact) {
Bundle b = new Bundle(); Bundle b = new Bundle();
b.putString("did", did); b.putString("did", did);
@@ -28,13 +28,13 @@ import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec; 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 * 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 * there go out over the SIM here, and chat names and read/unread/archived
* stay in step without a cable. * stay in step without a cable.
* *
* Everything is AES-256-GCM sealed with the key the desktop handed over USB * 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 * 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 * 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. * battery pays for nothing new while nothing's going on.
@@ -141,7 +141,7 @@ final class Relay {
// ---- one sync ---- // ---- 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) { static void sync(Context c) {
Config cfg = Config.get(c); Config cfg = Config.get(c);
if (!configured(cfg)) return; if (!configured(cfg)) return;
@@ -241,11 +241,11 @@ final class Relay {
h.put("Authorization", "Bearer " + cfg.relayToken); h.put("Authorization", "Bearer " + cfg.relayToken);
h.put("Content-Type", "application/json"); h.put("Content-Type", "application/json");
Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000); 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 == 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("jai answered " + r.status); if (r.status != 200) throw new Exception("The relay server answered " + r.status);
JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8)); 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 (resultsPushed > 0) takeList(c, "results", resultsPushed);
if (wantsDone > 0) takeList(c, "wants", wantsDone); if (wantsDone > 0) takeList(c, "wants", wantsDone);
SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]); 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) { private static void result(Context c, String id, long msgId, String error) {
inflight(c, id, 0);
try { try {
JSONObject o = new JSONObject().put("t", "sent").put("id", id); JSONObject o = new JSONObject().put("t", "sent").put("id", id);
o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL); o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL);
@@ -394,6 +395,44 @@ final class Relay {
result(c, id, 0, "It was empty."); result(c, id, 0, "It was empty.");
return; 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); 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(); Context c = ctx.getApplicationContext();
Config cfg = Config.get(c); Config cfg = Config.get(c);
if (cfg.sandbox) { if (cfg.sandbox) {
@@ -81,12 +86,13 @@ final class Sender {
store.confirmPending(id, real); store.confirmPending(id, real);
Sync.changed(); Sync.changed();
if (done != null) done.done(real, null); if (done != null) done.done(real, null);
return; return real;
} }
if (cfg.isGv(did)) { if (cfg.isGv(did)) {
if (photos.isEmpty()) { 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 { } else {
long first = 0;
// Google Voice carries one photo per message: the text rides with the first. // Google Voice carries one photo per message: the text rides with the first.
for (int i = 0; i < photos.size(); i++) { for (int i = 0; i < photos.size(); i++) {
String body = i == 0 ? text : ""; String body = i == 0 ? text : "";
@@ -95,26 +101,27 @@ final class Sender {
one.add(p); one.add(p);
Store.Msg m = pending(did, contact, body, one); Store.Msg m = pending(did, contact, body, one);
m.ts += i; 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)) { if (Sim.isSim(did)) {
// A long text goes as several SMS parts; photos, voice notes and groups as one MMS. // A long text goes as several SMS parts; photos, voice notes and groups as one MMS.
boolean mms = !photos.isEmpty() || Phone.isGroup(contact); boolean mms = !photos.isEmpty() || Phone.isGroup(contact);
Store.Msg m = pending(did, contact, text, photos); Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms"; 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); if (done != null) done.done(id, err);
Relay.soon(c); // the desktop hears about it on the next round 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; boolean mms = !photos.isEmpty() || Phone.charCount(text) > Phone.SMS_TEXT_LIMIT;
Store.Msg m = pending(did, contact, text, photos); Store.Msg m = pending(did, contact, text, photos);
if (mms) m.kind = "mms"; if (mms) m.kind = "mms";
enqueue(c, m, () -> { return enqueue(c, m, () -> {
VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass); VoipMs api = new VoipMs(cfg.voipUser, cfg.voipPass);
if (!mms) return api.sendSms(did, contact, text); if (!mms) return api.sendSms(did, contact, text);
List<String> media = new ArrayList<>(); List<String> media = new ArrayList<>();
@@ -140,7 +147,11 @@ final class Sender {
return m; 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); Store store = Store.get(c);
long tempId = store.insertPending(m); long tempId = store.insertPending(m);
Sync.changed(); Sync.changed();
@@ -149,7 +160,28 @@ final class Sender {
String error = deliver(c, store, tempId, attempt, gv, id); String error = deliver(c, store, tempId, attempt, gv, id);
Sync.changed(); Sync.changed();
if (done != null) done.done(id[0], error); 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. */ /** 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)) { if (Relay.configured(cfg)) {
section("Relay (jai)"); section("Relay server");
kv("Desktop link", Relay.status(c)); 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" 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."); + " 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; private static final long MATCH_AFTER = 15 * 60_000L;
static synchronized Store get(Context c) { 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; return instance;
} }
@@ -222,6 +226,32 @@ final class Store {
db.execSQL("UPDATE messages SET status = 'failed', error = ? WHERE id = ?", new Object[] {error, tempId}); 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. */ /** Sent messages that turned up in a poll replace our pending/failed copies. */
void reconcileSent(List<Msg> added) { void reconcileSent(List<Msg> added) {
List<Msg> sorted = new ArrayList<>(added); List<Msg> sorted = new ArrayList<>(added);
@@ -308,6 +338,7 @@ final class Store {
String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name; String did, contact, lastBody, lastDirection, lastSender, lastMediaJson, name;
long lastTs; long lastTs;
int unread; int unread;
int failed; // your texts here that didn't send
boolean archived, markedUnread; 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 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'" + " (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)))," + " 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 =" + " 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)" + " (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" + " 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.archived = c.getInt(8) != 0;
v.markedUnread = c.getInt(9) != 0; v.markedUnread = c.getInt(9) != 0;
v.name = c.getString(10); v.name = c.getString(10);
v.failed = c.getInt(11);
if (archived == null || v.archived == archived) out.add(v); if (archived == null || v.archived == archived) out.add(v);
} }
} }
@@ -1,11 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?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 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> <network-security-config>
<base-config cleartextTrafficPermitted="false" /> <base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="false">100.69.139.40</domain>
<domain includeSubdomains="false">127.0.0.1</domain>
</domain-config>
</network-security-config> </network-security-config>
+2 -2
View File
@@ -26,8 +26,8 @@ import sys
import zipfile import zipfile
from pathlib import Path from pathlib import Path
VERSION_NAME = "0.7.7" VERSION_NAME = "0.7.9"
VERSION_CODE = 15 VERSION_CODE = 17
PACKAGE = "me.teafry.voipmessages" PACKAGE = "me.teafry.voipmessages"
DEV_PACKAGE = PACKAGE + ".dev" DEV_PACKAGE = PACKAGE + ".dev"
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.7.1", "version": "0.9.5",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "voipms-desktop", "name": "voipms-desktop",
"version": "0.7.1", "version": "0.9.5",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3" "better-sqlite3": "^13.0.3"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "voipms-desktop", "name": "voipms-desktop",
"productName": "bubble", "productName": "bubble",
"version": "0.9.4", "version": "0.9.9",
"description": "Signal-style desktop SMS client for voip.ms", "description": "Signal-style desktop SMS client for voip.ms",
"author": "trav <trav@teafry.me>", "author": "trav <trav@teafry.me>",
"private": true, "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
+4 -3
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env python3 #!/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 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 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). 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 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". 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 import argparse
+6 -3
View File
@@ -1,4 +1,7 @@
#!/bin/bash #!/bin/bash
# The one real command line for bubble-relay on jai (~/startup.sh and scripts/deploy-jai.sh both run this). # The one real command line for the relay server (scripts/deploy-relay.sh runs
cd /home/jai/Documents/bubble-server/app || exit 1 # it; run it at boot too). relay.env next to it, written by the deploy, says
exec python3 bubble_relay.py --host 100.69.139.40 --port 8080 --data /home/jai/Documents/bubble-server/data # 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 type { Conversation, Direction, MediaRef, Message, MessageKind, MessageStatus, SearchHit } from '@shared/types'
import { SNIPPET_END, SNIPPET_START } from '@shared/types' import { SNIPPET_END, SNIPPET_START } from '@shared/types'
import { fixVoipDst } from './voipms' import { fixVoipDst } from './voipms'
import { SIM_DID } from '@shared/phone'
const SCHEMA_VERSION = 12 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) 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 // 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 // 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. // 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, 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' (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, 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, r.archived_at IS NOT NULL AS archived,
COALESCE(r.marked_unread, 0) AS markedUnread, COALESCE(r.marked_unread, 0) AS markedUnread,
r.name AS name 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 { clearGvSession, exportCookies, gvTransport, hasGvSession, importCookies, parseCookies, signInWindow } from './gvoice/session'
import { gvMessageId, GvSyncEngine } from './gvoice/sync' import { gvMessageId, GvSyncEngine } from './gvoice/sync'
import { WaaSigner } from './gvoice/waa' import { WaaSigner } from './gvoice/waa'
import { clearNotifications, notifyNew } from './notify' import { clearNotifications, closeAllNotifications, notifyNew, notifyUnsent, sweepNotifications } from './notify'
import * as rabbit from './rabbit' import * as rabbit from './rabbit'
import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay' import { checkUrl, clearRelayConfig, loadRelayConfig, newKey, RelayEngine, saveRelayConfig, SIM_DID } from './relay'
@@ -49,7 +49,7 @@ let dids: Did[] = []
let gv: GVoice | undefined let gv: GVoice | undefined
let gvSync: GvSyncEngine | undefined let gvSync: GvSyncEngine | undefined
let waa: WaaSigner | 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 let relay: RelayEngine | undefined
const send = (channel: string, ...args: unknown[]): void => { 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 }) 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 { function openFromNotification(key: { did: string; contact: string }): void {
if (!win || win.isDestroyed()) return if (!win || win.isDestroyed()) return
if (win.isMinimized()) win.restore() 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 const gvNumber = (): string | undefined => db.get('gv_number') || undefined
// Every number we can text from: voip.ms's DIDs, then Google Voice's, then // 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[] { function allDids(): Did[] {
const n = gvNumber() const n = gvNumber()
const out: Did[] = n ? [...dids, { did: n, description: 'Google Voice', smsEnabled: true, provider: 'gvoice' }] : [...dids] 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 if (!cfg) return
relay = new RelayEngine(db, media, cfg, settings.pollSeconds) relay = new RelayEngine(db, media, cfg, settings.pollSeconds)
relay.on('messages', onNewMessages) relay.on('messages', onNewMessages)
relay.on('changed', () => send('conversationsChanged')) relay.on('changed', readStateChanged)
relay.on('status', () => send('relayStatus', relay?.status())) relay.on('status', () => send('relayStatus', relay?.status()))
relay.on('unsent', (m: Message) => alertUnsent([m]))
relay.start() relay.start()
} }
// A text over the Rabbit's SIM: pending here until the Rabbit's next check // A text over the Rabbit's SIM: pending here until the Rabbit's next check
// sends it and says how it went (relay.ts). // sends it and says how it went (relay.ts).
function relaySend(contact: string, text: string, refs: MediaRef[]): void { 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 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 } : {}) }) 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) 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 = new GvSyncEngine(db, gv, { did, pollSeconds: settings.pollSeconds, backfillFloor: settings.backfillFloor })
gvSync.on('messages', onNewMessages) gvSync.on('messages', onNewMessages)
gvSync.on('status', () => send('syncStatus', syncStatus())) gvSync.on('status', () => send('syncStatus', syncStatus()))
gvSync.on('readChanged', () => send('conversationsChanged')) gvSync.on('readChanged', readStateChanged)
gvSync.start() 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> { async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>): Promise<void> {
const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync const engine = providerOf(m.did) === 'gvoice' ? gvSync : sync
const tempId = db.insertPending(m) const tempId = db.insertPending(m)
sending.add(tempId)
send('conversationsChanged') send('conversationsChanged')
try { try {
await enqueue(`${m.did}:${m.contact}`, () => await enqueue(`${m.did}:${m.contact}`, () =>
@@ -425,11 +434,49 @@ async function deliver(m: Omit<NewMessage, 'id'>, attempt: () => Promise<number>
}) })
) )
} finally { } finally {
sending.delete(tempId)
const after = db.getMessage(tempId)
if (after?.status === 'failed') alertUnsent([after])
send('conversationsChanged') send('conversationsChanged')
engine?.burst() 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> => { const voipAttempt = (call: (api: VoipMs) => Promise<number>) => (): Promise<number> => {
if (!api) throw new VoipMsError('not_signed_in') if (!api) throw new VoipMsError('not_signed_in')
return call(api) return call(api)
@@ -682,8 +729,8 @@ function registerIpc(): void {
signal: AbortSignal.timeout(15_000) signal: AbortSignal.timeout(15_000)
}).catch(() => undefined) }).catch(() => undefined)
if (!res) throw new Error(`Couldn't reach ${origin}. Is tailscale up?`) 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.status === 401) throw new Error('The relay server turned down that token.')
if (!res.ok) throw new Error(`jai answered ${res.status}.`) if (!res.ok) throw new Error(`The relay server answered ${res.status}.`)
// Keep the key across reconnects so the Rabbit's copy stays good. // Keep the key across reconnects so the Rabbit's copy stays good.
saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() }) saveRelayConfig({ url: origin, token: tok, key: loadRelayConfig()?.key ?? newKey() })
startRelay() startRelay()
@@ -782,6 +829,10 @@ function createWindow(): void {
// from firing, leaving a windowless process holding the single-instance lock. // 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) 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(ev as 'resize', sendWindowState)
win.on('close', (e) => {
if (!okToLeave()) e.preventDefault()
})
win.on('focus', () => win?.flashFrame(false))
win.on('closed', () => { win.on('closed', () => {
win = undefined win = undefined
app.quit() app.quit()
@@ -801,6 +852,7 @@ app.whenReady().then(async () => {
moveToBubbleData() moveToBubbleData()
settings = loadSettings() settings = loadSettings()
db = new MessageDb(path.join(getDataDir(), 'messages.db')) 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) if (SANDBOX) seedDemo(db)
dids = JSON.parse(db.get('dids') ?? '[]') as Did[] dids = JSON.parse(db.get('dids') ?? '[]') as Did[]
media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => { media = new MediaStore(path.join(getDataDir(), 'media'), db, (url, at) => {
@@ -829,6 +881,9 @@ app.whenReady().then(async () => {
if (gvNumber() && (await hasGvSession())) startGvSync() if (gvNumber() && (await hasGvSession())) startGvSync()
startRelay() startRelay()
// Once contacts can name the chat.
if (orphans.length) setTimeout(() => alertUnsent(orphans), 3000)
void dailySnapshot() void dailySnapshot()
setInterval(() => void dailySnapshot(), 60 * 60 * 1000) setInterval(() => void dailySnapshot(), 60 * 60 * 1000)
}) })
@@ -837,7 +892,9 @@ let quitting = false
app.on('before-quit', (e) => { app.on('before-quit', (e) => {
if (quitting || !db) return if (quitting || !db) return
e.preventDefault() e.preventDefault()
if (!okToLeave()) return
quitting = true quitting = true
closeAllNotifications()
sync?.stop() sync?.stop()
stopGv() stopGv()
relay?.stop() relay?.stop()
+47 -1
View File
@@ -4,6 +4,7 @@ import { Notification } from 'electron'
import { formatNumber, groupMembers, isGroup } from '@shared/phone' import { formatNumber, groupMembers, isGroup } from '@shared/phone'
import type { ContactDirectory } from './contacts' import type { ContactDirectory } from './contacts'
import type { MessageDb, NewMessage } from './db' import type { MessageDb, NewMessage } from './db'
import type { Message } from '@shared/types'
import { reactionPreview } from '@shared/reactions' import { reactionPreview } from '@shared/reactions'
import { editPreview } from '@shared/edits' 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. // reading the conversation in the app can take them back out of the list.
const live = new Map<string, Set<Notification>>() 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}` const convKey = (did: string, contact: string): string => `${did}\n${contact}`
// The conversation's been read: its notifications are stale. // 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() 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) 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 { 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(', ') .join(', ')
} }
function preview(m: NewMessage): string { function preview(m: Pick<NewMessage, 'body' | 'media'>): string {
const reaction = reactionPreview(m.body) const reaction = reactionPreview(m.body)
if (reaction) return reaction if (reaction) return reaction
const edit = editPreview(m.body) const edit = editPreview(m.body)
@@ -82,3 +104,27 @@ export function notifyNew(msgs: NewMessage[], { db, contacts, onClick }: NotifyD
n.show() 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 gvoice: { number: string; cookies: Record<string, string> } | null
dids: Array<{ did: string; description: string }> dids: Array<{ did: string; description: string }>
defaultDid?: 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 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/ // 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. // 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 // 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 // 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. // anything. Server: server/bubble_relay.py. Android side: Relay.java.
// //
// What travels (inside the seal; `t` is the kind): // 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' import type { MediaStore } from './media'
export { SIM_DID } from '@shared/phone' export { SIM_DID } from '@shared/phone'
export const DEFAULT_URL = 'http://100.69.139.40:8080'
export interface RelayConfig { export interface RelayConfig {
url: string url: string
@@ -228,10 +227,10 @@ export class RelayEngine extends EventEmitter {
body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }), body: JSON.stringify({ device: 'desktop', since, push: push.map((r) => r.blob) }),
signal: AbortSignal.timeout(120_000) signal: AbortSignal.timeout(120_000)
}) })
if (res.status === 401) throw new Error('jai turned down the token. Check it in Settings → jai.') 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(`jai answered ${res.status}`) if (!res.ok) throw new Error(`The relay server answered ${res.status}`)
const body = (await res.json()) as { cursor: number; events: string[]; more: boolean } 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) 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) for (const blob of body.events) this.handle(unseal(this.key, 'rabbit', blob) as Incoming | undefined)
this.db.set('relay_cursor', String(body.cursor)) this.db.set('relay_cursor', String(body.cursor))
@@ -240,8 +239,8 @@ export class RelayEngine extends EventEmitter {
this.lastSync = Date.now() this.lastSync = Date.now()
this.error = undefined this.error = undefined
} catch (e) { } catch (e) {
// Can't reach jai: an ordinary, quiet outcome; try again next round. // Can't reach the relay server: an ordinary, quiet outcome; try again next round.
this.error = (e as Error).name === 'TimeoutError' ? "jai didn't answer" : (e as Error).message this.error = (e as Error).name === 'TimeoutError' ? "The relay server didn't answer" : (e as Error).message
} }
this.emit('status', this.status()) this.emit('status', this.status())
} }
@@ -298,7 +297,11 @@ export class RelayEngine extends EventEmitter {
if (temp === undefined || temp === null) return if (temp === undefined || temp === null) return
const tempId = Number(temp) const tempId = Number(temp)
if (isInt(p.msgId)) this.db.confirmPending(tempId, p.msgId) 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.db.db.prepare('DELETE FROM kv WHERE key = ?').run(key)
this.emit('changed', 'sent') 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 { chatsWith, convName, dayLabel, sameDay, senderName, senderShortName } from '../format'
import { Avatar } from './Avatar' import { Avatar } from './Avatar'
import { Composer, type ComposerHandle } from './Composer' 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 { conversationMedia, Lightbox } from './Lightbox'
import { MessageBubble } from './MessageBubble' import { MessageBubble } from './MessageBubble'
import { DEFAULT_QUICK_REACTIONS, reactionText, sameEmoji, type Reaction } from '@shared/reactions' 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) }] 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 indexOf = useCallback((id: number) => rows.findIndex((r) => r.kind === 'msg' && r.m.id === id), [rows])
const flash = useCallback((id: number) => { const flash = useCallback((id: number) => {
@@ -177,6 +193,10 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
(id: number) => { (id: number) => {
const index = indexOf(id) const index = indexOf(id)
if (index < 0) return 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' }) virtuoso.current?.scrollToIndex({ index, align: 'center' })
flash(id) flash(id)
}, },
@@ -389,6 +409,7 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
reactions={folded.reactions.get(r.m.id)} reactions={folded.reactions.get(r.m.id)}
onShowReactions={showReactions} onShowReactions={showReactions}
onMenu={showMsgMenu} onMenu={showMsgMenu}
onEditFailed={editFailed}
versions={folded.versions.get(r.m.id)} versions={folded.versions.get(r.m.id)}
onShowEdits={showEdits} onShowEdits={showEdits}
/> />
@@ -398,6 +419,16 @@ export function ChatView({ conv, contact, contactMap, conversations, onOpen, nam
)} )}
</div> </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} /> <Composer ref={composer} conv={conv} isNew={isNew} smsDids={smsDids} gvNumber={gvNumber} onChangeDid={onChangeDid} />
{dragging && <div className="drop-hint">Drop to attach</div>} {dragging && <div className="drop-hint">Drop to attach</div>}
{lightbox && ( {lightbox && (
+10 -1
View File
@@ -17,6 +17,8 @@ const attachmentDrafts = new Map<string, Attachment[]>()
export interface ComposerHandle { export interface ComposerHandle {
addFiles: (files: File[]) => void 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 { interface Props {
@@ -118,7 +120,14 @@ export function Composer({ conv, isNew, smsDids, gvNumber, onChangeDid, ref }: P
textarea.current?.focus() 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 => { const remove = (a: Attachment): void => {
URL.revokeObjectURL(a.previewUrl) URL.revokeObjectURL(a.previewUrl)
@@ -117,7 +117,15 @@ const ConversationRow = memo(function ConversationRow({
<span className="row-time">{shortTime(conv.lastTs)}</span> <span className="row-time">{shortTime(conv.lastTs)}</span>
</div> </div>
<div className="row-bottom"> <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 ? ( {conv.unread > 0 ? (
<span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span> <span className="badge">{conv.unread > 99 ? '99+' : conv.unread}</span>
) : ( ) : (
+20 -4
View File
@@ -88,9 +88,13 @@ interface Props {
onOpenMedia: (id: number, index: number) => void onOpenMedia: (id: number, index: number) => void
onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void onMediaMenu: (id: number, index: number, e: React.MouseEvent) => void
onMediaLoad: () => 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 media = m.media ?? []
const cls = [ const cls = [
'msg', 'msg',
@@ -137,6 +141,11 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
{m.status === 'pending' && ( {m.status === 'pending' && (
<span className="status" title="Sending…"> <span className="status" title="Sending…">
<ClockIcon /> <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>
)} )}
</span> </span>
@@ -152,10 +161,17 @@ export const MessageBubble = memo(function MessageBubble({ m, sender, onSenderMe
</button> </button>
)} )}
{m.status === 'failed' && ( {m.status === 'failed' && (
<div className="failed-row"> <div className="failed-row" role="alert">
<AlertIcon /> Not sent{m.error ? `: ${m.error}` : ''} · <span className="failed-why">
<button onClick={() => void window.api.retryFailed(m.id).catch(() => undefined)}>Retry</button>· <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> <button onClick={() => void window.api.deleteFailed(m.id)}>Delete</button>
</span>
</div> </div>
)} )}
</div> </div>
@@ -225,7 +225,7 @@ export function SettingsDialog({ state, sync, onClose, onChanged }: Props) {
), ),
Contacts: <ContactsSection value={s.contactBook} onChange={(contactBook) => change({ ...s, contactBook })} />, Contacts: <ContactsSection value={s.contactBook} onChange={(contactBook) => change({ ...s, contactBook })} />,
Rabbit: <RabbitSection onChanged={onChanged} />, Rabbit: <RabbitSection onChanged={onChanged} />,
jai: <RelaySection onChanged={onChanged} />, 'Relay server': <RelaySection onChanged={onChanged} />,
Storage: ( Storage: (
<section className="group"> <section className="group">
<h3>Storage &amp; backups</h3> <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 }) { function RelaySection({ onChanged }: { onChanged: () => void }) {
const [st, setSt] = useState<RelayStatus>() const [st, setSt] = useState<RelayStatus>()
const [url, setUrl] = useState('http://100.69.139.40:8080') const [url, setUrl] = useState('')
const [token, setToken] = useState('') const [token, setToken] = useState('')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
@@ -550,10 +550,10 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
: undefined : undefined
return ( return (
<section className="group"> <section className="group">
<h3>Rabbit relay</h3> <h3>Relay server</h3>
<p className="muted small"> <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 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 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. (Settings there: how often), so it can take a while.
</p> </p>
@@ -583,7 +583,7 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
<> <>
<label className="field"> <label className="field">
Address 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>
<label className="field"> <label className="field">
Token Token
@@ -591,12 +591,12 @@ function RelaySection({ onChanged }: { onChanged: () => void }) {
type="password" type="password"
value={token} value={token}
onChange={(e) => setToken(e.target.value)} onChange={(e) => setToken(e.target.value)}
placeholder="from scripts/deploy-jai.sh --token" placeholder="from scripts/deploy-relay.sh --token"
autoComplete="off" autoComplete="off"
/> />
</label> </label>
<div className="btn-row"> <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 Connect
</button> </button>
</div> </div>
+143 -18
View File
@@ -527,9 +527,6 @@ mark {
.msg.out:not(.g-end) .bubble { .msg.out:not(.g-end) .bubble {
border-bottom-right-radius: 4px; border-bottom-right-radius: 4px;
} }
.msg.failed .bubble {
opacity: 0.6;
}
.bubble a { .bubble a {
color: inherit; color: inherit;
text-decoration: underline; text-decoration: underline;
@@ -548,21 +545,85 @@ mark {
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: #1b1b1b; 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 { .failed-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end;
flex-wrap: wrap; flex-wrap: wrap;
gap: 4px; gap: 6px 10px;
font-size: 12px; 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); 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 { .failed-row button {
border: 0; border: 1px solid var(--danger);
border-radius: 6px;
background: none; background: none;
color: var(--danger); color: var(--danger);
text-decoration: underline; font: inherit;
padding: 0 2px; 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 ---------- */ /* ---------- composer ---------- */
@@ -2290,9 +2351,6 @@ mark {
.msg.out:not(.g-end) .bubble { .msg.out:not(.g-end) .bubble {
border-bottom-right-radius: 4px; border-bottom-right-radius: 4px;
} }
.msg.failed .bubble {
opacity: 0.6;
}
.bubble a { .bubble a {
color: inherit; color: inherit;
text-decoration: underline; text-decoration: underline;
@@ -2311,21 +2369,80 @@ mark {
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
color: #1b1b1b; 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 { .failed-row {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: flex-end;
flex-wrap: wrap; flex-wrap: wrap;
gap: 4px; gap: 6px 10px;
font-size: 12px; 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); 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 { .failed-row button {
border: 0; border: 1px solid var(--danger);
border-radius: 6px;
background: none; background: none;
color: var(--danger); color: var(--danger);
text-decoration: underline; font: inherit;
padding: 0 2px; 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 ---------- */ /* ---------- composer ---------- */
@@ -3428,6 +3545,14 @@ select {
background: var(--highlight-text); background: var(--highlight-text);
color: var(--highlight); 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 { .sync-footer {
border-top: 0; border-top: 0;
padding-top: 0; padding-top: 0;
+1 -1
View File
@@ -8,7 +8,7 @@ export function normalizeNumber(raw: string): string {
return digits 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. // from that isn't a phone number here.
export const SIM_DID = 'sim' 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 lastSender?: string // sender of the last message, in group chats
name?: string // a name you gave the conversation (local only) name?: string // a name you gave the conversation (local only)
unread: number 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) markedUnread: boolean // manually marked unread (shown as a dot)
archived: boolean archived: boolean
} }
+14
View File
@@ -203,6 +203,20 @@ describe('MessageDb', () => {
expect(db.getMessage(t)?.error).toBe('nope') 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', () => { describe('reconcileSent', () => {
const MIN = 60_000 const MIN = 60_000
const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts }) const pending = (body: string, ts: number): number => db.insertPending({ did: '5550001111', contact: 'a', direction: 'out', body, ts })
+1 -1
View File
@@ -1,7 +1,7 @@
// The relay against the dev app on a plugged-in Rabbit (DEVICE=1 npm test -- // 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 // 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). // 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 { execFileSync, spawn, type ChildProcess } from 'node:child_process'
import fs from 'node:fs' import fs from 'node:fs'
import net from 'node:net' import net from 'node:net'
+2 -2
View File
@@ -73,7 +73,7 @@ describe('relay', () => {
}) })
it('only sends the token to tailscale or https', () => { 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('http://example.com')).toThrow()
expect(checkUrl('https://example.com')).toBe('https://example.com') expect(checkUrl('https://example.com')).toBe('https://example.com')
}) })
@@ -143,7 +143,7 @@ describe('relay', () => {
const ref = await media.resolve(oldMms, 0) const ref = await media.resolve(oldMms, 0)
expect(fs.readFileSync(media.filePath(ref!.file!)).toString()).toBe('fake png') 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([]) expect(await rabbit(key)).toEqual([])
engine.stop() engine.stop()
db.close() db.close()