Skip to content
Closed
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
9 changes: 8 additions & 1 deletion crates/chatd/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ fn call_error(err: CallError) -> Response {
fn response_detail(response: &Response) -> String {
match response {
Response::Error { detail, .. } => detail.clone(),
_ => "That didn't work. Try again.".to_owned(),
_ => "Couldn't place that call. Try again.".to_owned(),
}
}

Expand Down Expand Up @@ -3571,6 +3571,13 @@ mod tests {
use crate::store::{ConversationRow, PersonRow, Store};
use protocol::{AccountKey, ConversationKind, Key, Link, MediaFile, MediaKind, Message, Network, Outgoing};

#[test]
fn a_missing_error_names_the_call() {
let words = super::response_detail(&protocol::Response::Ok);
assert!(words.starts_with("Couldn't place that call"), "{words}");
assert!(!words.contains("That didn't work"), "{words}");
}

#[test]
fn a_pending_message_names_the_cached_self_sender_before_any_ack() {
assert_eq!(super::prove_pending_message_identity(), Ok(()));
Expand Down
177 changes: 164 additions & 13 deletions crates/tinyclient/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,33 +91,164 @@ pub fn failure_class(err: &io::Error) -> &'static str {
}

/// What a failed request says to the user, in place of the system's error text (C14).
/// Logs `action failed` with `op` and [`failure_class`], never the error's display.
/// A fallback names `op` and a short ref. The log line with that ref has the real error.
pub fn trouble_words(op: &'static str, err: &io::Error) -> String {
tracing::warn!(op, class = failure_class(err), "action failed");
if is_gone(err) {
tracing::warn!(op, class = failure_class(err), "action failed");
"tinyclient's background service isn't running. It is being started again; try again in a moment.".to_owned()
} else if is_slow(err) {
tracing::warn!(op, class = failure_class(err), "action failed");
"That took too long. Try again.".to_owned()
} else if is_other_version(err) {
tracing::warn!(op, class = failure_class(err), "action failed");
OTHER_ANSWER.to_owned()
} else {
"That didn't work. Try again.".to_owned()
with_ref(op, failure_class(err), &err.to_string(), &format!("Couldn't {}. Try again.", action_phrase(op)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Major: This reverses the function's own removed rule ("never the error's display"): with_ref logs cause = %cause into the operator log and the debug ring under a field name (cause) that is not on log_policy's DENY list, and protocol::redact strips credentials but not message text. ask()'s errors come from protocol::read_frame, which maps a failed serde_json decode of a whole Response frame into the io error, and a serde Display can embed payload snippets (invalid type: string "..."), so text from a decode-failed frame can land in logs and exported debug bundles. Log the error's kind, not its display; the ref plus failure_class is enough for support.

Suggested change
with_ref(op, failure_class(err), &err.to_string(), &format!("Couldn't {}. Try again.", action_phrase(op)))
with_ref(op, failure_class(err), &format!("{:?}", err.kind()), &format!("Couldn't {}. Try again.", action_phrase(op)))

}
}

/// What a refusal from chatd says to the user, for the codes that carry no words of their own.
/// Never names chatd, a Rust value or a command (C14).
pub fn refusal_words(code: ErrorCode, detail: &str) -> String {
/// `action` is required, so a fallback can name what was tried. Never names chatd, a Rust
/// value or a command (C14). A server's own words are shown as sent, unless they are the
/// bare fallback.
pub fn refusal_words(action: &'static str, code: ErrorCode, detail: &str) -> String {
match code {
ErrorCode::TooLarge => "That was too much to load at once. Try a smaller part.".to_owned(),
ErrorCode::Unsupported if detail.is_empty() => {
"Parts of tinyclient are different versions. Quit and reopen tinyclient.".to_owned()
}
ErrorCode::Offline if !detail.is_empty() => detail.to_owned(),
ErrorCode::Offline => "Not connected.".to_owned(),
ErrorCode::Internal => "Something went wrong inside tinyclient. Try again.".to_owned(),
_ if !detail.is_empty() => detail.to_owned(),
_ => "That didn't work. Try again.".to_owned(),
ErrorCode::Internal => with_ref(
action,
"internal",
"internal",
&format!("Couldn't {}. Something went wrong inside tinyclient. Try again.", action_phrase(action)),
),
_ if !detail.is_empty() && !is_bare(detail) => detail.to_owned(),
_ => with_ref(action, "refused", code_name(code), &format!("Couldn't {}. Try again.", action_phrase(action))),
}
}

/// The lab's error-text driver. A build without it opens the window and stays up.
pub fn prove_error_text() -> Result<(), &'static str> {
let words = trouble_words("send", &io::Error::other("blocked"));
if words.contains("That didn't work") || !words.contains("Couldn't send that") || !words.contains("(ref ") {
return Err("a failure still has no action");
}
let refused = refusal_words("pin that message", ErrorCode::NotFound, "");
if !refused.starts_with("Couldn't pin that message") || !refused.contains("(ref ") || refused.contains("That didn't work") {
return Err("a refusal still has no action");
}
let bare = refusal_words("pin that message", ErrorCode::Refused, "That didn't work. Try again.");
if !bare.starts_with("Couldn't pin that message") || bare.contains("That didn't work") {
return Err("the bare sentence is still shown");
}
if !fallback_notes().contains("send") {
return Err("diagnostics omit the ref");
}
Ok(())
}

/// Recent fallbacks for Copy diagnostics: the ref, the action, and how many times.
/// The real error stays in the log.
pub fn fallback_notes() -> String {
let rows = fallbacks().lock().unwrap_or_else(|err| err.into_inner());
if rows.is_empty() {
return String::new();
}
let mut text = String::from("recent failures:\n");
for row in rows.iter() {
text.push_str(&format!("ref {} {} ({})\n", row.quote, row.action, row.hits));
}
text
}

struct Fallback {
quote: String,
action: &'static str,
hits: u32,
}

fn fallbacks() -> &'static std::sync::Mutex<Vec<Fallback>> {
static ROWS: std::sync::OnceLock<std::sync::Mutex<Vec<Fallback>>> = std::sync::OnceLock::new();
ROWS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}

/// Shows `sentence` and appends `(ref XXXX)`. Logs `cause` with the same ref, and counts the hit.
fn with_ref(action: &'static str, class: &str, cause: &str, sentence: &str) -> String {
let quote = quote_code(action, class);
let hits = note_fallback(action, &quote);
let cause = one_line(cause);
tracing::warn!(action, quote = %quote, hits, cause = %cause, "fallback");
format!("{sentence} (ref {quote}).")
}

fn note_fallback(action: &'static str, quote: &str) -> u32 {
let mut rows = fallbacks().lock().unwrap_or_else(|err| err.into_inner());
if let Some(row) = rows.iter_mut().find(|row| row.quote == quote) {
row.hits = row.hits.saturating_add(1);
return row.hits;
}
if rows.len() >= 8 {
rows.remove(0);
}
rows.push(Fallback { quote: quote.to_owned(), action, hits: 1 });
1
}

fn quote_code(action: &str, class: &str) -> String {
let mut hash = 0x811c_9dc5u32;
for byte in action.bytes().chain(class.bytes()) {
hash ^= u32::from(byte);
hash = hash.wrapping_mul(0x0100_0193);
}
format!("{:04X}", (hash >> 16) as u16)
}

fn one_line(cause: &str) -> String {
cause.chars().map(|ch| if ch == '\n' || ch == '\r' { ' ' } else { ch }).take(180).collect()
}

fn is_bare(detail: &str) -> bool {
matches!(
detail.trim(),
"That didn't work. Try again." | "That didn't work. Try again" | "That didn't work." | "That didn't work"
| "That didn't work. Check it and try again." | "That didn't work. Check it and try again"
)
}

fn action_phrase(action: &str) -> &str {
match action {
"send" => "send that",
"inbox" => "refresh the list",
"tiny" => "do that on this server",
"load" => "open that conversation",
"people" => "load people",
"call" => "change the call",
"page" => "load that page",
"save" => "save that",
"play" => "play that",
"search" => "search",
"sign-in" => "sign in",
other => other,
}
}

fn code_name(code: ErrorCode) -> &'static str {
match code {
ErrorCode::Offline => "offline",
ErrorCode::NotFound => "not found",
ErrorCode::CallActive => "call active",
ErrorCode::NoCall => "no call",
ErrorCode::Media => "media",
ErrorCode::SignIn => "sign in",
ErrorCode::SignInUnreachable => "sign in unreachable",
ErrorCode::SignInBlocked => "sign in blocked",
ErrorCode::Unsupported => "unsupported",
ErrorCode::Refused => "refused",
ErrorCode::TooLarge => "too large",
ErrorCode::Internal => "internal",
}
}

Expand Down Expand Up @@ -147,14 +278,14 @@ mod tests {
#[test]
fn refusals_read_as_words_and_never_name_the_service() {
for code in [ErrorCode::TooLarge, ErrorCode::Unsupported, ErrorCode::Internal, ErrorCode::NotFound] {
let words = refusal_words(code, "");
let words = refusal_words("pin that message", code, "");
assert!(!words.contains("chatd") && !words.contains("Unsupported") && words.ends_with('.'), "{words}");
}
assert!(refusal_words(ErrorCode::Unsupported, "").contains("different versions"));
assert_eq!(refusal_words(ErrorCode::Refused, "Slow mode is on."), "Slow mode is on.");
assert_eq!(refusal_words(ErrorCode::Offline, ""), "Not connected.");
assert!(refusal_words("pin that message", ErrorCode::Unsupported, "").contains("different versions"));
assert_eq!(refusal_words("pin that message", ErrorCode::Refused, "Slow mode is on."), "Slow mode is on.");
assert_eq!(refusal_words("pin that message", ErrorCode::Offline, ""), "Not connected.");
assert_eq!(
refusal_words(ErrorCode::Offline, "Discord is offline. Files need a connection."),
refusal_words("pin that message", ErrorCode::Offline, "Discord is offline. Files need a connection."),
"Discord is offline. Files need a connection."
);
assert!(is_gone(&io::Error::from(io::ErrorKind::ConnectionRefused)));
Expand All @@ -165,6 +296,26 @@ mod tests {
assert!(is_slow(&io::Error::from(io::ErrorKind::WouldBlock)) && !is_gone(&io::Error::from(io::ErrorKind::TimedOut)));
}

#[test]
fn a_fallback_names_the_action_and_a_ref() {
let err = io::Error::other("os error 5");
let words = trouble_words("send", &err);
assert!(words.contains("Couldn't send that"), "{words}");
assert!(words.contains("(ref "), "{words}");
assert!(!words.contains("That didn't work"), "{words}");
assert!(!words.contains("os error"), "{words}");
let refused = refusal_words("pin that message", ErrorCode::NotFound, "");
assert!(refused.starts_with("Couldn't pin that message"), "{refused}");
assert!(refused.contains("(ref "), "{refused}");
assert!(!refused.contains("That didn't work"), "{refused}");
let bare = refusal_words("pin that message", ErrorCode::Refused, "That didn't work. Try again.");
assert!(bare.starts_with("Couldn't pin that message"), "{bare}");
assert!(!bare.contains("That didn't work"), "{bare}");
let notes = fallback_notes();
assert!(notes.contains("send"), "{notes}");
assert!(notes.contains("pin that message"), "{notes}");
}

#[test]
fn failure_class_maps_io_kinds() {
assert_eq!(failure_class(&io::Error::new(io::ErrorKind::TimedOut, "x")), "timeout");
Expand Down
1 change: 1 addition & 0 deletions crates/tinyclient/src/gui/app/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,7 @@ impl Shell {
for account in self.snapshot.iter().flat_map(|s| &s.accounts) {
text.push_str(&format!("{}: {:?}{}\n", account.key.network.label(), account.link, if account.reconnecting { " (reconnecting)" } else { "" }));
}
text.push_str(&crate::client::fallback_notes());
protocol::redact(&text)
}

Expand Down
2 changes: 1 addition & 1 deletion crates/tinyclient/src/gui/conversation/side.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ fn asked_words(code: protocol::ErrorCode, detail: &str) -> String {
} else if let Some(network) = detail.strip_suffix(" is not signed in") {
format!("{network} isn't signed in.")
} else {
crate::client::refusal_words(code, detail)
crate::client::refusal_words("search", code, detail)
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/tinyclient/src/gui/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn sign_in_words(network: Network, code: ErrorCode, detail: &str) -> Option<
ErrorCode::SignInBlocked => Some(format!(
"Your organization doesn't allow this app. {name} stays in the {name} app for this account."
)),
_ => Some(crate::client::refusal_words(code, detail)),
_ => Some(crate::client::refusal_words("sign in", code, detail)),
}
}

Expand Down
8 changes: 8 additions & 0 deletions crates/tinyclient/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ fn main() -> ExitCode {
}
return ExitCode::SUCCESS;
}
// The lab's error-text driver. A build without this opens the window below and stays up.
if std::env::var("TINYCLIENT_PROVE").ok().as_deref() == Some("error-text") {
if let Err(err) = client::prove_error_text() {
eprintln!("error-text: {err}");
return ExitCode::from(1);
}
return ExitCode::SUCCESS;
}
// The lab's no-console driver. A build without this opens the window below and stays up.
if std::env::var("TINYCLIENT_PROVE").ok().as_deref() == Some("no-console") {
let swap = update::windows_swap_args(std::path::Path::new("apply.ps1"));
Expand Down
9 changes: 9 additions & 0 deletions e2e/scenarios/error-text/drive.linux.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# error-text 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/error-text/drive.macos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# error-text on macOS. 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
83 changes: 83 additions & 0 deletions e2e/scenarios/error-text/drive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""A failure names the action and a short ref.

Starts this build's tinyclient with TINYCLIENT_PROVE=error-text. That build exits 0 only
when a fallback names the action, carries a ref, and drops the bare try-again sentence.
A build from before the fix ignores the variable and opens the window, so this driver fails there.

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

import os
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", "")

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 = "tinyclient.exe" if sys.platform == "win32" else "tinyclient"
if sys.platform == "darwin" and app_dir.endswith(".app"):
return os.path.join(app_dir, "Contents", "MacOS", "tinyclient")
return os.path.join(app_dir, name)


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("tinyclient is in E2E_APP_DIR", False)
return 1

data = os.path.join(OUT, "data")
os.makedirs(data, exist_ok=True)
env = os.environ.copy()
env["TINYCLIENT_DIR"] = data
env["TINYCLIENT_PROVE"] = "error-text"
env["TINYCLIENT_LOG_LEVEL"] = "info"
kwargs = {"cwd": data, "env": env, "stdin": subprocess.DEVNULL}
if sys.platform == "win32":
kwargs["creationflags"] = 0x08000000
with open(os.path.join(OUT, "app.out.log"), "w", encoding="utf-8") as out, open(os.path.join(OUT, "app.err.log"), "w", encoding="utf-8") as err:
kwargs["stdout"] = out
kwargs["stderr"] = err
proc = subprocess.Popen([binary], **kwargs)
try:
code = proc.wait(timeout=45)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
code = None
step("a failure names the action and a ref", code == 0)
return 1 if FAILED else 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading