Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Show SculptForge on Discord: never from agent/offscreen runs, the SF icon by URL, the latest change always sent (5 per 20 s), back within seconds after Discord restarts, no inherited socket

islandmede26b8ee0e3a7
diff --git a/changes/fix-discord-presence.md b/changes/fix-discord-presence.md
new file mode 100644
index 00000000..46914c22
--- /dev/null
+++ b/changes/fix-discord-presence.md
@@ -0,0 +1,31 @@
+---
+fixed: **Show SculptForge on Discord** stays up to date. Changes made in quick succession (opening files, typing the
+ challenge) used to be dropped by Discord after the fifth in 20 seconds. Now the latest always arrives.
+ After Discord restarts, your status is back within seconds instead of a minute.
+fixed: Discord no longer shows SculptForge while it isn't running. Runs by scripts and test tools (benchmarks,
+ offscreen checks) never show it, whatever the preferences say. On Linux, a process SculptForge starts (an AI
+ worker) can no longer keep the connection, and the status, open after SculptForge quits.
+changed: **Show SculptForge on Discord** shows the new SF icon.
+testers:
+ - Windows / macOS / Linux with the Discord desktop app: Edit > Preferences > Integrations > Show SculptForge on
+ Discord on. Your profile shows "Playing SculptForge" with the orange SF icon and the elapsed time.
+ - With Show the file name on, open three files one after another quickly: within about 4 seconds Discord shows
+ the last one.
+ - Quit Discord and start it again while SculptForge runs: the status comes back within about 10 seconds.
+ - Quit SculptForge, or end it from the Task Manager / kill it: the status disappears.
+---
+Reviewer notes:
+- Tony 11-05: "doesn't update anymore, it shows while I don't have SculptForge running, and it needs the new icon".
+- Agent runs: discord::agentRun (SDL_APP_ID=sculptforge-agent, SDL_VIDEO_DRIVER=offscreen or the offscreen driver,
+ SF_NO_DISCORD). These come on top of supportCardTestMode (benchmarks, UI tests, scripts, renders, demos, CI).
+ Agents run the app with Tony's prefs, where presence is on.
+- Icon: large_image is https://sculptforge.app/press/sculptforge-icon-1024.png. Discord's docs allow an external URL
+ in large_image (via the media proxy). type 0 (Playing) is set explicitly. The portal's "logo" asset was a
+ placeholder cube. Not checked against a live Discord client (agents must not touch Tony's Discord).
+- Rate limit: one SET_ACTIVITY every 4 s at most, always the latest; a clear never waits. Reconnect back-off is 2 s,
+ doubling to 60 s.
+- SOCK_CLOEXEC on the socket (Linux). Windows pipe handles were already not inheritable.
+- macOS has no SOCK_CLOEXEC, so a fork in the instant between socket() and fcntl() could still leak the socket
+ there.
+- Tests: test_discord_presence covers the JSON shape, agentRun, reconnect after Discord restarts plus a later
+ change, bursts sending the latest, and SIGKILL closing the connection with a child still alive.
diff --git a/docs/guide/discord.md b/docs/guide/discord.md
index 6437ba58..44a9d4ae 100644
--- a/docs/guide/discord.md
+++ b/docs/guide/discord.md
@@ -16,13 +16,14 @@ Two extras, both off until you check them:
- **Show the file name** adds the name of the file you have open, for example `kraken.sfproj`. Only the name, never
the folder it's in.
-Uncheck **Show SculptForge on Discord** and your status is cleared at once. Quitting SculptForge clears it too.
+Uncheck **Show SculptForge on Discord** and your status is cleared at once. Quitting SculptForge clears it too, and
+so does a crash. If you quit and restart Discord, your status comes back within a few seconds.
## What is sent, and where
| Sent | When |
|---|---|
-| The SculptForge icon and name | while it's on |
+| The SculptForge icon (Discord loads it from sculptforge.app) and name | while it's on |
| The time you started (Discord shows the elapsed time) | while it's on |
| "Monthly challenge: *theme*" | only with **Show the monthly challenge** |
| The file's name (not its folder) | only with **Show the file name** |
diff --git a/src/app/App.h b/src/app/App.h
index a63c1f29..2b6026f3 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -523,6 +523,7 @@ private:
char discordChallengeBuf_[64 * 4 + 1] = {}; // the theme field (64 code points of UTF-8)
bool discordPresenceAvailable() const; // an application ID is compiled in
void updateDiscordPresence(); // every frame: sends only when what's shown changes
+ bool discordAgentRun() const; // agent or offscreen run: never (discord::agentRun)
void drawIntegrationsPrefs(); // Preferences > Integrations
bool welcomeAfterCard_ = false; // the first-run welcome waits until the card closes
// What's New (WhatsNewPopup.cpp): the newest version's feature cards from docs/guide/whats-new.md, once after an
diff --git a/src/app/PanelIntegrations.cpp b/src/app/PanelIntegrations.cpp
index 81a3572c..532ad593 100644
--- a/src/app/PanelIntegrations.cpp
+++ b/src/app/PanelIntegrations.cpp
@@ -4,15 +4,17 @@
// Preferences > Integrations > Show SculptForge on Discord (off by default; core/DiscordPresence.h): the icon, the
// name SculptForge and the elapsed time, and on request the monthly challenge's theme and the file's name. Only
// to the Discord app on this computer; it shows it to the user's friends. Tests, scripts, renders and CI never
-// connect (supportCardTestMode).
+// connect (supportCardTestMode), nor do runs by agents (discord::agentRun).
#include "app/App.h"
#include "app/Ui.h"
#include "core/NetworkPolicy.h"
+#include <SDL3/SDL_video.h>
#include <imgui.h>
#include <chrono>
#include <cstdio>
+#include <cstdlib>
namespace sf {
@@ -21,8 +23,15 @@ void App::DiscordClientDelete::operator()(discord::Client* c) const { delete c;
// Never in studio mode (core/NetworkPolicy.h): no Discord presence in a studio build.
bool App::discordPresenceAvailable() const { return net::localIpcAllowed() && discord::appIdConfigured(discord::kDiscordAppId); }
+bool App::discordAgentRun() const {
+ static const bool agent = discord::agentRun([](const char* n) { return std::getenv(n); }, SDL_GetCurrentVideoDriver());
+ return agent;
+}
+
void App::updateDiscordPresence() {
- if (!discordPresenceAvailable() || supportCardTestMode()) return;
+ // Scripted and agent runs (benchmarks, offscreen checks, the Windows PC's runs) use the user's preferences too:
+ // they never show up on the user's Discord.
+ if (!discordPresenceAvailable() || supportCardTestMode() || discordAgentRun()) return;
if (!discordPrefs_.enabled && !discordClient_) return; // never switched on: no thread, no connection
if (!discordClient_) discordClient_.reset(new discord::Client(discord::kDiscordAppId));
if (discordStart_ == 0)
diff --git a/src/core/DiscordPresence.cpp b/src/core/DiscordPresence.cpp
index b27f09b2..9a6256bc 100644
--- a/src/core/DiscordPresence.cpp
+++ b/src/core/DiscordPresence.cpp
@@ -243,7 +243,13 @@ public:
addr.sun_family = AF_UNIX;
std::memcpy(addr.sun_path, path.c_str(), path.size() + 1);
++g_connectAttempts;
+#ifdef SOCK_CLOEXEC
+ // Atomic close-on-exec: a process started meanwhile (an AI worker) never inherits the connection and
+ // keeps SculptForge on Discord after SculptForge quits.
+ const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+#else
const int fd = socket(AF_UNIX, SOCK_STREAM, 0);
+#endif
if (fd < 0) return false;
fcntl(fd, F_SETFD, FD_CLOEXEC);
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
@@ -394,6 +400,7 @@ std::string setActivityJson(int64_t pid, const Activity* a, uint64_t nonce) {
args.set("pid", double(pid));
if (a && a->show) {
Json activity = Json::object();
+ activity.set("type", 0); // Playing: "Playing SculptForge"
const std::string state = activityState(*a);
if (!state.empty()) activity.set("state", state);
if (a->start > 0) {
@@ -402,7 +409,7 @@ std::string setActivityJson(int64_t pid, const Activity* a, uint64_t nonce) {
activity.set("timestamps", std::move(timestamps));
}
Json assets = Json::object();
- assets.set("large_image", "logo");
+ assets.set("large_image", kLargeImageUrl);
assets.set("large_text", "SculptForge");
activity.set("assets", std::move(assets));
args.set("activity", std::move(activity));
@@ -475,6 +482,13 @@ bool socketOwnedBy(const std::string& path, unsigned uid) {
uint64_t connectAttempts() { return g_connectAttempts.load(); }
+bool agentRun(const std::function<const char*(const char*)>& getenv, const char* videoDriver) {
+ const auto is = [](const char* v, const char* want) { return v && std::strcmp(v, want) == 0; };
+ const char* noDiscord = getenv("SF_NO_DISCORD");
+ return is(getenv("SDL_APP_ID"), "sculptforge-agent") || is(getenv("SDL_VIDEO_DRIVER"), "offscreen") ||
+ is(videoDriver, "offscreen") || (noDiscord && *noDiscord && !is(noDiscord, "0"));
+}
+
Client::Client(std::string appId) : appId_(std::move(appId)) {}
Client::~Client() {
@@ -487,10 +501,11 @@ Client::~Client() {
if (thread_.joinable()) thread_.join();
}
-void Client::setTimingForTests(int backoffMs, int connectTimeoutMs) {
+void Client::setTimingForTests(int backoffMs, int connectTimeoutMs, int minGapMs) {
std::lock_guard lock(mutex_);
backoffMs_ = backoffMs;
connectTimeoutMs_ = connectTimeoutMs;
+ minGapMs_ = minGapMs;
}
void Client::set(const Activity& a) {
@@ -510,7 +525,8 @@ void Client::run() {
Activity sent; // what Discord shows (show = false: nothing)
bool sentValid = false; // sent is known (reset on every new connection)
uint64_t nonce = 0;
- Clock::time_point retryAt{};
+ Clock::time_point retryAt{}, nextSendAt{};
+ int failures = 0; // in a row: the back-off doubles from 2 s to backoffMs
FrameReader reader;
constexpr size_t kDrainCap = 256 * 1024; // per wake-up: a flood can't keep the thread reading
constexpr int kWriteTimeoutMs = 2000;
@@ -520,7 +536,8 @@ void Client::run() {
connected_ = false;
sentValid = false;
reader = FrameReader();
- retryAt = Clock::now() + std::chrono::milliseconds(backoffMs);
+ const int64_t waitMs = std::min<int64_t>(backoffMs, int64_t(2000) << std::min(failures++, 6));
+ retryAt = Clock::now() + std::chrono::milliseconds(waitMs);
};
// Drains replies; false (and closed) on a malformed frame, CLOSE, or a closed connection.
const auto drain = [&](int waitMs) {
@@ -538,7 +555,7 @@ void Client::run() {
const bool stopping = stop_;
const Activity want = desired_;
dirty_ = false;
- const int backoffMs = backoffMs_, connectTimeoutMs = connectTimeoutMs_;
+ const int backoffMs = backoffMs_, connectTimeoutMs = connectTimeoutMs_, minGapMs = minGapMs_;
lock.unlock();
if (stopping) {
@@ -565,14 +582,17 @@ void Client::run() {
if (r == FrameReader::Result::Bad || msLeft(deadline) == 0) break;
}
}
- if (ok) connected_ = true;
+ if (ok) connected_ = true, failures = 0;
else drop(backoffMs);
}
- if (conn.isOpen() && (!sentValid || !(sent == want))) {
+ // A change to what's shown waits for its gap (Discord drops the 6th in 20 s); clearing never waits.
+ const bool due = !want.show || Clock::now() >= nextSendAt;
+ if (conn.isOpen() && (!sentValid || !(sent == want)) && due) {
if (conn.write(encodeFrame(OpFrame, setActivityJson(processId(), &want, ++nonce)), kWriteTimeoutMs)) {
sent = want;
sentValid = true;
++sent_;
+ nextSendAt = Clock::now() + std::chrono::milliseconds(minGapMs);
} else {
drop(backoffMs);
}
@@ -587,7 +607,8 @@ void Client::run() {
lock.lock();
if (stop_ || dirty_) continue;
- if (conn.isOpen()) cv_.wait_for(lock, std::chrono::seconds(5)); // wake up to drain now and then
+ if (conn.isOpen() && (!sentValid || !(sent == desired_))) cv_.wait_until(lock, nextSendAt); // the latest, once due
+ else if (conn.isOpen()) cv_.wait_for(lock, std::chrono::seconds(5)); // wake up to drain now and then
else if (desired_.show) cv_.wait_until(lock, retryAt);
else cv_.wait(lock);
}
diff --git a/src/core/DiscordPresence.h b/src/core/DiscordPresence.h
index e5dd14e1..8632efc0 100644
--- a/src/core/DiscordPresence.h
+++ b/src/core/DiscordPresence.h
@@ -7,7 +7,8 @@
// no network socket, nothing listens. Outbound only: HANDSHAKE, then SET_ACTIVITY (an empty one clears it on
// disable and quit). Whatever Discord sends back is read only to drain the connection, never interpreted: frames
// are bounds-checked (8-byte header, 64 KiB cap) and anything malformed closes it. It runs on its own thread
-// (5 s connect timeout, 60 s back-off after a failure) and starts no thread or connection until it's switched on.
+// (5 s connect timeout, a back-off from 2 s to 60 s after a failure, one activity every 4 s at most) and starts no
+// thread or connection until it's switched on. Scripted and agent runs never start it (agentRun).
//
// Sent: the icon, the name SculptForge (the application's name; details stay empty), the elapsed time, and
// optionally "Monthly challenge: <theme>" and the file name (never a path). Every string is sanitised first.
@@ -26,9 +27,17 @@
namespace sf::discord {
-// The SculptForge application on Discord's developer portal (a public ID, not a secret; its Rich Presence asset
-// "logo" is the icon). "0" hides the feature and never connects.
+// The SculptForge application on Discord's developer portal (a public ID, not a secret). "0" hides the feature and
+// never connects.
inline constexpr const char* kDiscordAppId = "1567737303210926130";
+// The icon: the SF mark on the site (Discord fetches an external image through its media proxy; the portal's
+// "logo" asset was a placeholder cube).
+inline constexpr const char* kLargeImageUrl = "https://sculptforge.app/press/sculptforge-icon-1024.png";
+
+// A run made by a script or an agent, never the user at the window: SDL_APP_ID=sculptforge-agent,
+// SDL_VIDEO_DRIVER=offscreen (or videoDriver "offscreen") or SF_NO_DISCORD set. It never shows anything on the
+// user's Discord, whatever the preferences say. getenv is a parameter for the tests.
+bool agentRun(const std::function<const char*(const char*)>& getenv, const char* videoDriver);
// A real application ID: 1-20 digits, not "0".
bool appIdConfigured(std::string_view id);
@@ -99,8 +108,9 @@ public:
bool connected() const { return connected_.load(); }
uint64_t activitiesSent() const { return sent_.load(); }
- // Tests: the back-off after a failure and the connect timeout (milliseconds).
- void setTimingForTests(int backoffMs, int connectTimeoutMs);
+ // Tests: the longest back-off after a failure, the connect timeout and the gap between two activities
+ // (milliseconds).
+ void setTimingForTests(int backoffMs, int connectTimeoutMs, int minGapMs = 0);
private:
void run();
@@ -114,7 +124,9 @@ private:
std::atomic<bool> abort_{false};
std::atomic<bool> connected_{false};
std::atomic<uint64_t> sent_{0};
- int backoffMs_ = 60000, connectTimeoutMs_ = 5000;
+ // Back-off: 2 s after a connection is lost (Discord restarting), doubling to 60 s while it stays away. Discord
+ // takes at most 5 activities in 20 s and drops the rest: one every 4 s at most, always the latest.
+ int backoffMs_ = 60000, connectTimeoutMs_ = 5000, minGapMs_ = 4000;
};
} // namespace sf::discord
diff --git a/tests/test_discord_presence.cpp b/tests/test_discord_presence.cpp
index b997d96b..9e6f370d 100644
--- a/tests/test_discord_presence.cpp
+++ b/tests/test_discord_presence.cpp
@@ -4,7 +4,8 @@
// Show SculptForge on Discord (core/DiscordPresence.h): what is sent (the name only, the optional challenge and
// file name, never a path), sanitising, the frame reader's bounds (malformed frames, oversized lengths, fuzz),
// the socket ownership check (wrong owner, symlink), off = zero connections, and a whole session against a fake
-// Discord on a Unix socket (handshake, activity, clear; a malformed reply closes the connection).
+// Discord on a Unix socket (handshake, activity, clear; a malformed reply closes the connection; Discord restarting;
+// bursts; a killed process), and agent runs never showing.
#include "TestHarness.h"
#include "core/DiscordPresence.h"
@@ -14,12 +15,15 @@
#include <cstring>
#include <random>
#include <thread>
+#include <vector>
#if !defined(_WIN32)
#include <cstdlib>
#include <sys/socket.h>
#include <sys/stat.h>
+#include <csignal>
#include <sys/un.h>
+#include <sys/wait.h>
#include <unistd.h>
#endif
@@ -78,11 +82,13 @@ TEST(discord_activity_sends_the_name_only) {
CHECK(act.isObject());
CHECK(!act.has("details")); // Discord shows the application's name: SculptForge
CHECK(!act.has("state"));
- CHECK(act["assets"]["large_image"].asString() == "logo");
+ // The SF mark by URL (Discord's RPC docs: an external https image in large_image, through its media proxy).
+ CHECK(act["assets"]["large_image"].asString() == "https://sculptforge.app/press/sculptforge-icon-1024.png");
CHECK(act["assets"]["large_text"].asString() == "SculptForge");
- CHECK(act["timestamps"]["start"].asNumber() == 1793750400.0);
+ CHECK(act["timestamps"]["start"].asNumber() == 1793750400.0); // seconds, as in the docs' SET_ACTIVITY example
+ CHECK(act["type"].asNumber() == 0.0); // Playing (SET_ACTIVITY takes 0, 2, 3 or 5)
// Nothing else: no buttons, party, secrets (join / spectate) or small image.
- for (const auto& m : act.members()) CHECK(m.first == "assets" || m.first == "timestamps");
+ for (const auto& m : act.members()) CHECK(m.first == "assets" || m.first == "timestamps" || m.first == "type");
for (const auto& m : act["assets"].members()) CHECK(m.first == "large_image" || m.first == "large_text");
}
@@ -233,6 +239,27 @@ TEST(discord_off_never_connects) {
CHECK(connectAttempts() == before);
}
+TEST(discord_agent_runs_never_show) {
+ const auto env = [](std::initializer_list<std::pair<const char*, const char*>> vars) {
+ std::vector<std::pair<std::string, std::string>> v;
+ for (const auto& p : vars) v.emplace_back(p.first, p.second);
+ return [v](const char* n) -> const char* {
+ for (const auto& p : v)
+ if (p.first == n) return p.second.c_str();
+ return nullptr;
+ };
+ };
+ CHECK(!agentRun(env({}), "x11"));
+ CHECK(!agentRun(env({{"SDL_APP_ID", "sculptforge"}}), "wayland"));
+ CHECK(!agentRun(env({{"SDL_APP_ID", "sculptforge"}}), nullptr));
+ CHECK(agentRun(env({{"SDL_APP_ID", "sculptforge-agent"}}), "x11"));
+ CHECK(agentRun(env({{"SDL_VIDEO_DRIVER", "offscreen"}}), nullptr));
+ CHECK(agentRun(env({}), "offscreen")); // the driver SDL picked
+ CHECK(agentRun(env({{"SF_NO_DISCORD", "1"}}), "windows"));
+ CHECK(!agentRun(env({{"SF_NO_DISCORD", "0"}}), "windows"));
+ CHECK(!agentRun(env({{"SF_NO_DISCORD", ""}}), "windows"));
+}
+
#if !defined(_WIN32)
namespace {
@@ -305,6 +332,26 @@ struct EnvVar {
}
};
+// Discord's side of one connection: the handshake, READY, then the first activity. -1 on failure.
+int acceptSession(int listener, std::string& activity) {
+ const int c = acceptWithTimeout(listener);
+ uint32_t op = 0;
+ std::string hs;
+ const std::string ready = encodeFrame(OpFrame, "{\"cmd\":\"DISPATCH\",\"evt\":\"READY\"}");
+ if (c < 0 || !readFrame(c, op, hs) || op != OpHandshake || send(c, ready.data(), ready.size(), 0) != ssize_t(ready.size()) ||
+ !readFrame(c, op, activity) || op != OpFrame) {
+ if (c >= 0) close(c);
+ return -1;
+ }
+ return c;
+}
+
+std::string stateOf(const std::string& frame) {
+ Json j;
+ std::string err;
+ return Json::parseStrict(frame, j, err) ? j["args"]["activity"]["state"].asString() : std::string("?");
+}
+
} // namespace
TEST(discord_socket_owner_check) {
@@ -413,4 +460,120 @@ TEST(discord_malformed_reply_closes) {
CHECK(closedByClient);
CHECK(accepted == 2);
}
+// Discord quits and starts again while SculptForge runs: the client finds it again within seconds (2 s, not the
+// 60 s back-off), sends what's shown again, and later changes still go out (Tony 11-05: "it doesn't update anymore").
+TEST(discord_reconnects_after_discord_restarts) {
+ TempSocketDir t;
+ const std::string path = t.dir + "/discord-ipc-0";
+ int listener = listenAt(path);
+ CHECK(listener >= 0);
+ if (listener < 0) return;
+ EnvVar xdg("XDG_RUNTIME_DIR", t.dir);
+
+ Client client("1234567890");
+ client.setTimingForTests(60000, 1000, 0);
+ Activity a;
+ a.show = true;
+ a.fileName = "kraken.sfproj";
+ client.set(a);
+ std::string first;
+ int c = acceptSession(listener, first);
+ CHECK(c >= 0 && stateOf(first) == "kraken.sfproj");
+ // Discord quits: its socket goes away.
+ if (c >= 0) close(c);
+ close(listener);
+ unlink(path.c_str());
+ for (int i = 0; i < 700 && client.connected(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ CHECK(!client.connected()); // noticed at the next drain (every 5 s)
+ // It starts again.
+ listener = listenAt(path);
+ CHECK(listener >= 0);
+ const auto t0 = std::chrono::steady_clock::now();
+ std::string again;
+ c = acceptSession(listener, again);
+ const double waited = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ CHECK(c >= 0 && stateOf(again) == "kraken.sfproj"); // shown again without any change
+ CHECK(waited < 4.5);
+ // A change after the reconnect goes out.
+ a.fileName = "dragon.sfproj";
+ client.set(a);
+ uint32_t op = 0;
+ std::string changed;
+ CHECK(c >= 0 && readFrame(c, op, changed) && stateOf(changed) == "dragon.sfproj");
+ if (c >= 0) close(c);
+ close(listener);
+}
+
+// Discord takes 5 activities in 20 s and drops the rest: changes in a burst come out spaced, and the last one
+// (what the window shows now) is always sent.
+TEST(discord_bursts_send_the_latest) {
+ TempSocketDir t;
+ const int listener = listenAt(t.dir + "/discord-ipc-0");
+ CHECK(listener >= 0);
+ if (listener < 0) return;
+ EnvVar xdg("XDG_RUNTIME_DIR", t.dir);
+ Client client("1234567890");
+ client.setTimingForTests(60000, 1000, 400);
+ Activity a;
+ a.show = true;
+ a.fileName = "a0.sfproj";
+ client.set(a);
+ std::string frame;
+ const int c = acceptSession(listener, frame);
+ CHECK(c >= 0 && stateOf(frame) == "a0.sfproj");
+ if (c < 0) return;
+ for (int i = 1; i <= 8; ++i) {
+ a.fileName = "a" + std::to_string(i) + ".sfproj";
+ client.set(a);
+ std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ }
+ std::vector<std::string> got;
+ uint32_t op = 0;
+ while (got.empty() || got.back() != "a8.sfproj") {
+ if (!readFrame(c, op, frame)) break;
+ got.push_back(stateOf(frame));
+ }
+ CHECK(!got.empty() && got.back() == "a8.sfproj");
+ CHECK(got.size() <= 2); // not 8
+ close(c);
+ close(listener);
+}
+
+// Quit, a crash or a kill: the connection closes with the process (Discord then clears what it showed), even
+// with a child process still running that was started after the connection (close-on-exec).
+TEST(discord_killed_process_closes_the_connection) {
+ TempSocketDir t;
+ const int listener = listenAt(t.dir + "/discord-ipc-0");
+ CHECK(listener >= 0);
+ if (listener < 0) return;
+ EnvVar xdg("XDG_RUNTIME_DIR", t.dir);
+ const pid_t pid = fork();
+ if (pid == 0) {
+ Client* client = new Client("1234567890"); // never destroyed: the kill ends it
+ Activity a;
+ a.show = true;
+ client->set(a);
+ for (int i = 0; i < 300 && client->activitiesSent() < 1; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ if (fork() == 0) { // a worker started after the connection, outliving this process
+ execl("/bin/sleep", "sleep", "3", static_cast<char*>(nullptr));
+ _exit(127);
+ }
+ kill(getpid(), SIGKILL);
+ _exit(1);
+ }
+ std::string activity;
+ const int c = acceptSession(listener, activity);
+ CHECK(c >= 0);
+ int status = 0;
+ waitpid(pid, &status, 0);
+ CHECK(WIFSIGNALED(status));
+ if (c >= 0) {
+ timeval tv{1, 0}; // well before the worker's 3 s are up
+ setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ char b;
+ CHECK(recv(c, &b, 1, 0) == 0); // EOF: closed
+ close(c);
+ }
+ close(listener);
+}
#endif