Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion crates/chatd/src/adapters/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,9 @@ pub(crate) fn capability_ceiling() -> Capabilities {
voice_notes: true,
// Deleting a chat removes it on the phone, so it is the confirmed "Delete chat", not a close.
clear_history: true,
delete: true,
// An SMS cannot be unsent: the phone deletes a text on this side only, and `Delete` for
// everyone is refused. So `delete` stays off. With it on, the window offered "Delete for
// everyone" on our own texts and said they leave for both sides.
delete_for_me: true,
reactions: true,
// An RCS chat carries the quote. The shell offers Reply there only.
Expand Down
17 changes: 16 additions & 1 deletion crates/chatd/src/adapters/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ fn message_rows() -> Vec<(String, Vec<String>)> {
row("Quote reply", quote),
row("Threads", |network| flag(ceiling(network).threads)),
row("Edit own message", |network| flag(ceiling(network).edit)),
row("Delete own message", |network| flag(ceiling(network).delete)),
// A network that deletes on this side alone (Messages) still deletes an own message.
row("Delete own message", |network| {
let caps = ceiling(network);
flag(caps.delete || caps.delete_for_me)
}),
row("Pins", |network| flag(ceiling(network).pins)),
row("Search this conversation", |network| flag(ceiling(network).search)),
row("Search everywhere", |network| flag(ceiling(network).search_global)),
Expand Down Expand Up @@ -268,6 +272,17 @@ mod tests {
assert_eq!(cells(row)[7], "N");
}

#[test]
fn a_network_that_deletes_only_for_me_still_lists_deleting_its_own_messages() {
// An SMS cannot be unsent, so Messages reports `delete_for_me` alone. The window follows
// that and offers "Delete for me", which does remove an own text from this side.
let messages = super::super::messages::capability_ceiling();
assert!(!messages.delete && messages.delete_for_me);
let table = markdown();
let row = table.lines().find(|line| line.starts_with("| Delete own message |")).expect("delete own message row");
assert_eq!(cells(row)[6], "N");
}

fn cells(row: &str) -> Vec<&str> {
row.trim_matches('|').split('|').map(str::trim).filter(|cell| !cell.is_empty()).collect()
}
Expand Down
33 changes: 33 additions & 0 deletions crates/chatd/tests/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,39 @@ fn a_text_deleted_on_the_phone_leaves_and_delete_reaches_the_phone() {
});
}

#[test]
fn a_messages_account_deletes_for_me_alone() {
let world = World::linked();
world.connected();
let (accounts, _) = world.status();
let mine = accounts.iter().find(|status| status.key == account()).expect("Messages account");
// An SMS cannot be unsent. With `delete` set as well, the window offered "Delete for
// everyone" on our own texts and said they leave for both sides.
assert!(!mine.can.delete && mine.can.delete_for_me, "{:?}", mine.can);

// The phone is asked for that scope only. For everyone the delete is refused in words,
// the text stays and the phone hears nothing of it.
world.steer("incoming grace hi");
let text = world.arrived(GRACE, "hi");
match world.ask(Request::Delete {
conversation: key(GRACE),
message_id: text.id.clone(),
scope: protocol::DeleteScope::Everyone,
}) {
Response::Error { detail, .. } => assert!(detail.contains("only delete messages for you"), "{detail}"),
other => panic!("a text was unsent: {other:?}"),
}
assert!(
world.messages(GRACE).iter().any(|item| item.id == text.id),
"a refused delete removed the text"
);
assert!(
world.calls().iter().all(|call| !call.starts_with("delete ")),
"the phone was asked to unsend a text: {:?}",
world.calls()
);
}

#[test]
fn three_texts_count_as_three_and_a_chat_read_on_the_phone_clears() {
let world = World::linked();
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/messages-delete-for-me/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# messages-delete-for-me on Linux. The lab runs this with bash while ffmpeg films the display.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
9 changes: 9 additions & 0 deletions e2e/scenarios/messages-delete-for-me/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# messages-delete-for-me on macOS. The lab runs this with bash while the display is filmed.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
if command -v python3 >/dev/null 2>&1; then
exec python3 "$HERE/drive.py"
fi
echo "python3 is not on PATH" >&2
exit 1
269 changes: 269 additions & 0 deletions e2e/scenarios/messages-delete-for-me/drive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""A Google Messages account offers "Delete for me" alone, and the phone is asked for that delete.

Starts this build's chatd with the scripted Messages phone (TINYCLIENT_MESSAGES_FAKE), steers it
over its control file the way tests/messages.rs does, and speaks chatd's real socket. The window's
message menu follows what the account says it may do, so that is read from chatd's status:
delete for me, and not delete, which made the menu offer "Delete for everyone" on our own texts.
A delete for me reaches the phone and the text leaves the store. A delete for everyone is refused
in words, the text stays and the phone hears nothing of it. A build from before the fix reports
delete as well, so this driver fails there.

Env from the lab: E2E_OUT, E2E_T0, E2E_APP_DIR.
"""

import json
import os
import socket
import struct
import subprocess
import sys
import time

OUT = os.environ.get("E2E_OUT", "")
T0 = float(os.environ.get("E2E_T0") or time.time())
APP = os.environ.get("E2E_APP_DIR", "")

ME = "phone-ada"
GRACE = "phone-grace"
SESSION = json.dumps({"account": ME, "name": "Ada Quill"})
OWN = "e2e-own-1"
THEIRS = "Are we still on for Tuesday?"
REFUSED = "only delete messages for you"

FAILED = False
STEPS = ""


def now():
return time.time() - T0


def step(words, ok):
global FAILED
if not ok:
FAILED = True
line = '{"t": %s, "step": "%s", "ok": %s}' % (round(now(), 1), words.replace('"', "'"), "true" if ok else "false")
print(("[ok] " if ok else "[FAILED] ") + words, flush=True)
if STEPS:
with open(STEPS, "a", encoding="utf-8") as handle:
handle.write(line + "\n")


def app_bin(app_dir):
name = "chatd.exe" if sys.platform == "win32" else "chatd"
if sys.platform == "darwin" and app_dir.endswith(".app"):
return os.path.join(app_dir, "Contents", "MacOS", "chatd")
return os.path.join(app_dir, name)


def connect(sock_path):
"""chatd's socket: a file on Unix, the matching named pipe on Windows."""
if sys.platform == "win32":
return open("\\\\.\\pipe\\" + sock_path, "r+b", buffering=0)
stream = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
stream.settimeout(5)
stream.connect(sock_path)
return stream


def write_all(stream, data):
view = memoryview(data)
while view:
written = stream.write(view)
if not written:
raise RuntimeError("chatd's socket took nothing")
view = view[written:]


class Chat:
def __init__(self, sock_path):
self.stream = connect(sock_path)

def ask(self, request):
body = json.dumps(request, separators=(",", ":")).encode()
write_all(self.stream, struct.pack("!I", len(body)) + body)
head = b""
while len(head) < 4:
got = self.stream.read(4 - len(head))
if not got:
raise RuntimeError("chatd closed its socket")
head += got
length = struct.unpack("!I", head)[0]
if length > 1024 * 1024:
raise RuntimeError("answer exceeds the protocol size limit")
chunks = b""
while len(chunks) < length:
got = self.stream.read(length - len(chunks))
if not got:
raise RuntimeError("chatd closed its socket mid-frame")
chunks += got
return json.loads(chunks)

def close(self):
try:
self.stream.close()
except OSError:
pass


def main():
global STEPS
if not OUT or not APP:
print("E2E_OUT and E2E_APP_DIR are required", file=sys.stderr)
return 1
os.makedirs(OUT, exist_ok=True)
STEPS = os.path.join(OUT, "steps.jsonl")
open(STEPS, "w", encoding="utf-8").close()
binary = app_bin(APP)
if not os.path.isfile(binary):
step("chatd is in E2E_APP_DIR", False)
return 1

data = os.path.join(OUT, "data")
os.makedirs(data, exist_ok=True)
sock_path = os.path.join(data, "chat.sock")
control = os.path.join(data, "messages.ctl")
open(control, "a", encoding="utf-8").close()
env = os.environ.copy()
env["TINYCLIENT_DIR"] = data
env["TINYCLIENT_MESSAGES_FAKE"] = "1"
env["TINYCLIENT_SESSION_MESSAGES"] = SESSION
env.pop("TINYCLIENT_SESSION_DISCORD", None)
env.pop("TINYCLIENT_SESSION_SLACK", None)
env.pop("TINYCLIENT_SESSION_TELEGRAM", None)
env.pop("TINYCLIENT_SESSION_TEAMS", None)
env.pop("TINYCLIENT_SESSION_SIGNAL", None)
kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL}
if sys.platform == "win32":
kwargs["creationflags"] = 0x08000000
with open(os.path.join(OUT, "chatd.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "chatd.err.log"), "w", encoding="utf-8") as err:
kwargs["stdout"] = out
kwargs["stderr"] = err
proc = subprocess.Popen([binary], **kwargs)
chat = None
try:
deadline = time.time() + 15
while chat is None:
if proc.poll() is not None:
step("chatd stays up for the driver", False)
return 1
if time.time() > deadline:
step("chatd opens its socket", False)
return 1
try:
chat = Chat(sock_path)
except OSError:
time.sleep(0.1)
drive(chat, control, data)
finally:
if chat:
chat.close()
proc.kill()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
return 1 if FAILED else 0


def key(id):
return {"network": "messages", "account": ME, "id": id}


def wait(what, chat, look, seconds=20):
deadline = time.time() + seconds
while time.time() < deadline:
found = look()
if found is not None:
step(what, True)
return found
time.sleep(0.2)
step(what, False)
return None


def steer(control, line):
with open(control, "a", encoding="utf-8") as handle:
handle.write(line + "\n")


def ask(chat, request):
try:
return chat.ask(request)
except Exception:
return None


def conversation(chat, id):
answer = ask(chat, {"op": "conversation", "conversation": key(id)})
return (answer or {}).get("conversation")


def messages(chat, id):
answer = ask(chat, {"op": "messages", "conversation": key(id), "page": "newest", "limit": 100})
return (answer or {}).get("messages", [])


def calls(data):
"""What the scripted phone was asked, one line each."""
try:
with open(os.path.join(data, "messages.calls"), encoding="utf-8") as handle:
return handle.read().splitlines()
except OSError:
return []


def account(chat):
"""The Messages account's row of chatd's status."""
answer = ask(chat, {"op": "status"}) or {}
return next((row for row in answer.get("accounts", []) if row.get("key", {}).get("network") == "messages"), None)


def stored(chat, id):
return next((m for m in messages(chat, GRACE) if m.get("id") == id), None)


def sent(chat, id):
row = stored(chat, id)
return row if row is not None and row.get("state", "sent") == "sent" else None


def drive(chat, control, data):
status = wait("chatd answers its status", chat, lambda: ask(chat, {"op": "status"}))
if status is None:
return
wait("Messages is connected", chat, lambda: ((account(chat) or {}).get("link") == "connected" or None))
wait("Grace's chat is known", chat, lambda: conversation(chat, GRACE) and True)

# The window's message menu follows this. An SMS cannot be unsent, so the account deletes
# for me alone: with delete set as well, the menu offered Delete for everyone on our texts.
can = wait("the account says what it may do", chat, lambda: ((account(chat) or {}).get("can") or None))
if can is not None:
step("the account deletes for me only, never for everyone", can.get("delete_for_me") is True and can.get("delete") is not True)

# Our own text. The answer to a send is only the pending row, so it is read back from the store.
answer = ask(chat, {"op": "send", "conversation": key(GRACE), "client_id": OWN, "text": "See you at seven."})
step("our text is taken for sending", (answer or {}).get("op") == "sent")
row = wait("our text is in the store as sent", chat, lambda: sent(chat, OWN))
if row is not None:
step("the stored text is ours", row.get("outgoing") is True)
answer = ask(chat, {"op": "delete", "conversation": key(GRACE), "message_id": OWN, "scope": "me"})
step("delete for me is answered", (answer or {}).get("op") == "ok")
wait("the phone is asked to delete it for me", chat, lambda: (("delete " + OWN) in calls(data) or None))
step("our text left the store", stored(chat, OWN) is None)

# Delete for everyone: the phone cannot unsend a text, so the delete is refused in words,
# the text stays and the phone is asked for nothing.
steer(control, "incoming grace " + THEIRS)
theirs = wait("Grace's text is in the store", chat, lambda: next((m for m in messages(chat, GRACE) if m.get("text") == THEIRS), None))
if theirs is not None:
asked = "delete " + theirs["id"]
answer = ask(chat, {"op": "delete", "conversation": key(GRACE), "message_id": theirs["id"], "scope": "everyone"}) or {}
step("delete for everyone is refused in words", answer.get("op") == "error" and REFUSED in answer.get("detail", ""))
step("the refused delete removed nothing", stored(chat, theirs["id"]) is not None)
step("the phone was not asked to unsend it", asked not in calls(data))


if __name__ == "__main__":
sys.exit(main())
17 changes: 17 additions & 0 deletions e2e/scenarios/messages-delete-for-me/drive.windows.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# messages-delete-for-me on Windows. The lab runs this in the console session it is already filming.
$ErrorActionPreference = 'Stop'
$drive = Join-Path $PSScriptRoot 'drive.py'
if (Get-Command py -ErrorAction SilentlyContinue) {
& py -3 $drive
exit $LASTEXITCODE
}
if (Get-Command python -ErrorAction SilentlyContinue) {
& python $drive
exit $LASTEXITCODE
}
if (Get-Command python3 -ErrorAction SilentlyContinue) {
& python3 $drive
exit $LASTEXITCODE
}
Write-Host 'python is not on PATH (tried py -3, python, python3)'
exit 1
Loading
Loading