Measure uasync CPU load and display it in desktop and Android GUIs

Sample thread CPU usage without waking idle loops, expose a one-second moving average, and refresh compact GUI indicators at 3 Hz while visible on Android. Add load and bridge regression coverage, streaming notes, and task list cleanup.
This commit is contained in:
evgeny committed 2026-10-10 12:31:13 +02:00
1 parent bcfe7ca4c1
commit 71d19013c0
25 files changed
+692 -587

No files matched your search

@@ -358,11 +358,14 @@ class MainActivity : AppCompatActivity() {
val channels by vm.channels.collectAsState()
val dmConversations by vm.dmConversations.collectAsState()
val stuck by vm.isStuck.collectAsState()
val cpuLoad by vm.cpuLoad.collectAsState()
ChannelListScreen(
channels = channels,
dmConversations = dmConversations,
connected = connected,
isStuck = stuck,
cpuLoad = cpuLoad,
onCpuLoadVisible = vm::setCpuLoadVisible,
onSelectChannel = { ch -> vm.selectChannel(ch); screen = Screen.Chat },
onSelectDm = { dm -> vm.openDm(dm.convId, dm.peerNodeId, dm.peerName); screen = Screen.Dm },
onCreateChannel = { name -> vm.createChannel(name, "channel_1") },
@@ -84,6 +84,7 @@ object NativeLib {
fun requestInviteLink(channelId: String, targetNodeId: Long, requestId: Long) { nativeRequestInviteLink(channelId, targetNodeId, requestId) }
fun ping() { nativePing() }
fun requestCpuLoad(): Boolean = nativeRequestCpuLoad()
fun isResponsive(): Boolean = nativeIsResponsive()
/* ── App foreground/background (Android lifecycle) ── */
@@ -253,6 +254,7 @@ object NativeLib {
private external fun nativeInit(dbPath: String, controlPort: Int, config: Any, logCb: Any): Boolean
private external fun nativeStart(configText: String): Boolean
private external fun nativeStop()
private external fun nativeRequestCpuLoad(): Boolean
private external fun nativeSetEventCallback(cb: Any)
private external fun nativeDestroy()
private external fun nativeSendMessage(channelId: String, text: ByteArray, replyTo: ByteArray, requestId: Long): Boolean
@@ -0,0 +1,39 @@
package com.utun.chat.ui.components
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.drawscope.clipRect
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
/* Градиент привязан ко всей ширине: низкая нагрузка зелёная, полная доходит до красного. */
@Composable
fun CpuLoadIndicator(percent: Int, modifier: Modifier = Modifier) {
val value = percent.coerceIn(0, 100)
Box(modifier.size(60.dp, 24.dp).semantics { contentDescription = "CPU $value%" }, contentAlignment = Alignment.Center) {
Canvas(Modifier.matchParentSize()) {
val shape = Path().apply { addRoundRect(RoundRect(0f, 0f, size.width, size.height, CornerRadius(5.dp.toPx()))) }
clipPath(shape) {
drawRect(Color(0xFFE4E9E6))
clipRect(right = size.width * value / 100f) {
drawRect(Brush.horizontalGradient(listOf(Color(0xFF66BB6A), Color(0xFFFFCA28), Color(0xFFEF5350)), endX = size.width))
}
}
}
Text("$value%", color = Color(0xFF172019), fontSize = 12.sp, fontWeight = FontWeight.Bold, maxLines = 1)
}
}
@@ -18,6 +18,8 @@ import androidx.compose.material.icons.filled.Build
import androidx.compose.material3.*
import androidx.compose.runtime.*
import com.utun.chat.ui.components.PeerStatusDot
import com.utun.chat.ui.components.CpuLoadIndicator
import androidx.lifecycle.compose.LifecycleResumeEffect
import com.utun.chat.ui.components.GroupAvatar
import com.utun.chat.ui.components.UserAvatar
import com.utun.chat.ui.components.GroupPropertiesDialog
@@ -43,6 +45,8 @@ fun ChannelListScreen(
dmConversations: List<DmConversation> = emptyList(),
connected: Boolean,
isStuck: Boolean = false,
cpuLoad: Int = 0,
onCpuLoadVisible: (Boolean) -> Unit = {},
onSelectChannel: (Channel) -> Unit,
onSelectDm: (DmConversation) -> Unit = {},
onCreateChannel: (String) -> Unit,
@@ -53,6 +57,10 @@ fun ChannelListScreen(
onLogs: () -> Unit,
onRefresh: () -> Unit = {}
) {
LifecycleResumeEffect(Unit) {
onCpuLoadVisible(true)
onPauseOrDispose { onCpuLoadVisible(false) }
}
var showCreateDialog by remember { mutableStateOf(false) }
var menuChannelId by remember { mutableStateOf<String?>(null) }
var optionsChannel by remember { mutableStateOf<Channel?>(null) }
@@ -81,6 +89,7 @@ fun ChannelListScreen(
},
floatingActionButton = {
Row(verticalAlignment = Alignment.CenterVertically) {
CpuLoadIndicator(cpuLoad, Modifier.padding(end = 12.dp))
Text(
text = "v${BuildConfig.VERSION_NAME}",
modifier = Modifier.padding(end = 16.dp),
@@ -250,6 +250,13 @@ class ChatViewModel : ViewModel() {
private val _isStuck = MutableStateFlow(false)
val isStuck: StateFlow<Boolean> = _isStuck
private val _cpuLoad = MutableStateFlow(0)
val cpuLoad: StateFlow<Int> = _cpuLoad
private val _cpuLoadVisible = MutableStateFlow(false)
private var cpuLoadPending = false
fun setCpuLoadVisible(visible: Boolean) { _cpuLoadVisible.value = visible }
private val _nodeStatuses = MutableStateFlow<Map<Long, NodeStatus>>(emptyMap())
val nodeStatuses: StateFlow<Map<Long, NodeStatus>> = _nodeStatuses
@@ -324,6 +331,21 @@ class ChatViewModel : ViewModel() {
}
init {
viewModelScope.launch {
_cpuLoadVisible.collectLatest { visible ->
if (!visible) return@collectLatest
LogManager.addLog("DEBUG", "CPU", "GUI polling started: period=333ms")
try {
while (isActive) {
if (!NativeLib.isReady()) { cpuLoadPending = false; _cpuLoad.value = 0 }
else if (!cpuLoadPending) cpuLoadPending = NativeLib.requestCpuLoad()
delay(333)
}
} finally {
LogManager.addLog("DEBUG", "CPU", "GUI polling stopped")
}
}
}
viewModelScope.launch {
AppEventHandler.events.collect { (type, data) -> handleEvent(type, data) }
}
@@ -386,11 +408,21 @@ class ChatViewModel : ViewModel() {
private fun handleEvent(type: Int, data: ByteArray?) {
if (type == 13) {
cpuLoadPending = false; _cpuLoad.value = 0
dmPresenceRefreshJob?.cancel()
_dmCallAvailable.value = false
_dmConversations.value = _dmConversations.value.map { it.copy(online = false) }
} else if (type in listOf(4, 5, 12, 16, 17, 24, 25, 31, 33)) refreshDmCallRoute()
when (type) {
57 -> { /* CPU_LOAD: valid:1, average_percent:1. */
cpuLoadPending = false
if (data == null || data.size != 2 || data[0].toInt() !in 0..1 || data[1].toInt() !in 0..100) {
LogManager.addLog("ERROR", "CPU", "Invalid CPU load response: size=${data?.size}")
_cpuLoad.value = 0
return
}
if (_cpuLoadVisible.value) _cpuLoad.value = if (data[0].toInt() == 1) data[1].toInt() else 0
}
56 -> { /* MSG_SUBMITTED: request_id:8LE, success. */
if (data == null || data.size != 9) { LogManager.addLog("ERROR", "Reply", "invalid submission result"); return }
val id = java.nio.ByteBuffer.wrap(data).order(java.nio.ByteOrder.LITTLE_ENDIAN).long
@@ -2161,6 +2161,19 @@ JNIEXPORT void JNICALL Java_com_utun_chat_data_NativeLib_nativePing(
utun_bridge_ping();
}
/* GUI запрашивает готовый снимок асинхронно, CPU-часы читает только поток ядра. */
JNIEXPORT jboolean JNICALL Java_com_utun_chat_data_NativeLib_nativeRequestCpuLoad(JNIEnv* env, jobject thiz) {
(void)env; (void)thiz;
struct UASYNC* ua = instance_lite_get_uasync();
struct UTUN_INSTANCE* inst = instance_lite_get_instance();
if (!ua || !inst || !instance_lite_is_running()) return JNI_FALSE;
struct posted_task* task = u_calloc(1, sizeof(*task));
if (!task) { DEBUG_ERROR(DEBUG_CATEGORY_SYS, "CPU load request allocation failed"); return JNI_FALSE; }
task->callback = chat_core_collect_cpu_load_trampoline; task->arg = inst;
uasync_post_reserved(ua, task);
return JNI_TRUE;
}
JNIEXPORT void JNICALL Java_com_utun_chat_data_NativeLib_nativeConnectChannel(
JNIEnv* env, jobject thiz, jstring channelId) {
(void)thiz;
+40 -1
View File
@@ -24,6 +24,38 @@ extern "C" {
#include "dm/dm_core.h"
}
/* Секундное среднее CPU: фиксированный градиент, заполнение по проценту. */
class CpuLoadIndicator : public QWidget {
public:
explicit CpuLoadIndicator(QWidget* parent) : QWidget(parent) {
setObjectName(QStringLiteral("cpuLoadIndicator"));
setFixedSize(60, 24);
setAccessibleName(QStringLiteral("CPU"));
}
void setValue(int percent) {
percent = qBound(0, percent, 100);
if (m_percent == percent) return;
m_percent = percent; update();
}
protected:
void paintEvent(QPaintEvent*) override {
QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing);
QPainterPath path; path.addRoundedRect(QRectF(rect()), 5, 5);
painter.setClipPath(path);
painter.fillRect(rect(), QColor("#E4E9E6"));
QLinearGradient gradient(0, 0, width(), 0);
gradient.setColorAt(0, QColor("#66BB6A"));
gradient.setColorAt(0.5, QColor("#FFCA28"));
gradient.setColorAt(1, QColor("#EF5350"));
painter.fillRect(QRectF(0, 0, width() * m_percent / 100.0, height()), gradient);
painter.setPen(QColor("#172019"));
QFont f = font(); f.setBold(true); painter.setFont(f);
painter.drawText(rect(), Qt::AlignCenter, QString::number(m_percent) + '%');
}
private:
int m_percent = 0;
};
/* Пустое место и заголовки секций не сбрасывают выбор канала. */
class ChannelListView : public QListView {
public:
@@ -106,7 +138,12 @@ ChannelList::ChannelList(DbManager* db, QWidget *parent)
auto *header = new QLabel(QCoreApplication::translate("ChatGui", "Channels"), this);
header->setAlignment(Qt::AlignCenter);
header->setStyleSheet("font-weight: bold; padding: 8px; background: palette(window);");
layout->addWidget(header);
auto* headerRow = new QHBoxLayout;
headerRow->setContentsMargins(0, 0, 8, 0);
headerRow->addWidget(header, 1);
m_cpuLoad = new CpuLoadIndicator(this);
headerRow->addWidget(m_cpuLoad);
layout->addLayout(headerRow);
m_listView->setModel(m_model);
m_listView->setItemDelegate(new ChannelDelegate(this));
@@ -266,6 +303,8 @@ void ChannelList::onDmCallRoute(const uint8_t* data, int len) {
}
}
void ChannelList::setCpuLoad(int percent) { m_cpuLoad->setValue(percent); }
void ChannelList::loadChannels() {
refreshDmPresence();
QString selectedCid;
+3
View File
@@ -12,6 +12,7 @@
class DbManager;
class QLabel;
class CpuLoadIndicator;
class ChannelList : public QWidget {
Q_OBJECT
@@ -25,6 +26,7 @@ public:
void selectChannel(const QString& channelId);
void setChannelPeersOnline(const QString& channelId, int count);
void setAutoConnectActive(bool active);
void setCpuLoad(int percent);
void setChannelUnreadCount(const QString& channelId, int count);
int getChannelUnreadCount(const QString& channelId) const;
@@ -49,4 +51,5 @@ private:
bool m_autoConnectActive = false;
QHash<QString, bool> m_dmOnline;
QTimer* m_dmPresenceTimer;
CpuLoadIndicator* m_cpuLoad;
};
+22
View File
@@ -171,6 +171,18 @@ MainWindow::MainWindow(QWidget *parent, DbManager* db, const QString& cfgPath,
setupConnects();
}
connect(m_autoPlayTimer, &QTimer::timeout, this, &MainWindow::autoPlayTimerTick);
m_cpuLoadTimer = new QTimer(this);
m_cpuLoadTimer->setTimerType(Qt::PreciseTimer);
connect(m_cpuLoadTimer, &QTimer::timeout, this, [this] {
auto* inst = gui_bridge_get_inst();
if (!m_node || !m_node->isRunning() || !inst || !gui_bridge_is_uasync_ready()) {
m_cpuLoadPending = false; m_channelList->setCpuLoad(0); return;
}
if (m_cpuLoadPending) return;
m_cpuLoadPending = gui_bridge_request_cpu_load() != 0;
});
m_cpuLoadTimer->start(333);
DEBUG_DEBUG(DEBUG_CATEGORY_SYS, "desktop CPU indicator polling started: period=333ms");
#ifndef _WIN32
std::signal(SIGINT, unixSignalHandler);
@@ -183,6 +195,9 @@ MainWindow::MainWindow(QWidget *parent, DbManager* db, const QString& cfgPath,
MainWindow::~MainWindow() {
s_mainWindow = nullptr;
m_cpuLoadTimer->stop();
gui_bridge_set_cpu_load_cb(nullptr);
DEBUG_DEBUG(DEBUG_CATEGORY_SYS, "desktop CPU indicator polling stopped");
if (m_messageNotification) m_messageNotification->dismiss("shutdown");
m_messageNotification.reset();
delete AvatarManager::instance();
@@ -407,6 +422,11 @@ void MainWindow::setupSoundFromConfig() {
void MainWindow::setupBridgeCallbacks() {
s_mainWindow = this;
gui_bridge_set_cpu_load_cb([](int percent) {
if (!s_mainWindow) return;
s_mainWindow->m_cpuLoadPending = false;
s_mainWindow->m_channelList->setCpuLoad(percent);
});
gui_bridge_set_member_files_response_cb([](const uint8_t* data, int length) {
DEBUG_DEBUG(DEBUG_CATEGORY_DEBUG, "member_files: GUI response route bytes=%d browser=%d",
length, (int)(s_mainWindow && s_mainWindow->m_fileBrowser));
@@ -554,6 +574,8 @@ void MainWindow::setupBridgeCallbacks() {
gui_bridge_set_network_changed_cb([](int type) {
if (!s_mainWindow) return;
if (type == 13) {
s_mainWindow->m_cpuLoadPending = false;
s_mainWindow->m_channelList->setCpuLoad(0);
s_mainWindow->m_accountList->model()->setRadioState(0, false, false);
s_mainWindow->m_messageList->clearDmCallRoute();
s_mainWindow->m_channelList->clearDmPresence();
+2
View File
@@ -129,6 +129,8 @@ private:
QQueue<AutoPlayItem> m_autoPlayQueue;
QTimer* m_autoPlayTimer = nullptr;
QTimer* m_cpuLoadTimer = nullptr;
bool m_cpuLoadPending = false;
QTimer* m_shutdownTimer = nullptr;
QSet<int64_t> m_autoPlayDownloading; /* msgIds with download in progress */
+30 -1
View File
@@ -1,8 +1,10 @@
/* Формат канального события: live/history сохраняются при передаче в GUI, битые события отбрасываются. */
#include "../transport/gui_bridge.h"
#include "../../../lib/debug_config.h"
#include "../../../src/chat/chat_event.h"
#include <QtTest>
#include <cstring>
#include <thread>
struct ReceivedMessage {
QString channel;
@@ -11,6 +13,13 @@ struct ReceivedMessage {
bool guiThread;
};
static QList<ReceivedMessage> received;
static QList<int> cpuLoads;
static bool cpuOnGuiThread = true;
static void cpu_received(int percent) {
cpuLoads.append(percent);
cpuOnGuiThread &= QThread::currentThread() == qApp->thread();
}
static void message_received(const char* channel, int length, uint64_t author, int initial_sync) {
received.append({QString::fromUtf8(channel, length), author, initial_sync != 0, QThread::currentThread() == qApp->thread()});
@@ -39,7 +48,7 @@ private slots:
gui_bridge_init();
gui_bridge_set_msg_received_cb(message_received);
}
void cleanupTestCase() { gui_bridge_set_msg_received_cb(nullptr); }
void cleanupTestCase() { gui_bridge_set_msg_received_cb(nullptr); gui_bridge_set_cpu_load_cb(nullptr); }
void init() { received.clear(); }
void liveAndHistory() {
@@ -69,6 +78,26 @@ private slots:
QTest::qWait(100);
QVERIFY(received.isEmpty());
}
void cpuLoadDeliveredToGuiThread() {
cpuLoads.clear(); cpuOnGuiThread = true;
gui_bridge_set_cpu_load_cb(cpu_received);
std::thread worker([] {
const uint8_t samples[][2] = {{1, 0}, {1, 50}, {1, 100}, {0, 90}, {1, 101}};
for (const auto& sample : samples) gui_bridge_post(CHAT_EVT_CPU_LOAD, sample, sizeof(sample));
gui_bridge_post(CHAT_EVT_CPU_LOAD, nullptr, 0);
});
worker.join();
QVERIFY(cpuLoads.isEmpty()); // Worker не вызывает UI напрямую.
QTRY_COMPARE(cpuLoads.size(), 6);
QCOMPARE(cpuLoads, QList<int>({0, 50, 100, 0, 0, 0}));
QVERIFY(cpuOnGuiThread);
gui_bridge_set_cpu_load_cb(nullptr);
const uint8_t sample[] = {1, 75};
gui_bridge_post(CHAT_EVT_CPU_LOAD, sample, sizeof(sample));
QCoreApplication::processEvents();
QCOMPARE(cpuLoads.size(), 6);
}
};
QTEST_MAIN(MessageEventTest)
+5
View File
@@ -121,6 +121,11 @@ void gui_bridge_set_db_ready_cb(gui_db_ready_fn cb);
typedef void (*gui_status_refresh_fn)(const char* text, int len);
void gui_bridge_set_status_refresh_cb(gui_status_refresh_fn cb);
/* Секундное среднее CPU uasync, 0..100; callback выполняется в GUI-потоке. */
typedef void (*gui_cpu_load_fn)(int percent);
void gui_bridge_set_cpu_load_cb(gui_cpu_load_fn cb);
int gui_bridge_request_cpu_load(void); // 1 = запрос поставлен в очередь; 0 = ядро недоступно/ошибка
/* Callback для завершения загрузки медиа-аттача */
typedef void (*gui_attachment_downloaded_fn)(const char* ch_id, int ch_id_len, int64_t msg_id);
void gui_bridge_set_attachment_downloaded_cb(gui_attachment_downloaded_fn cb);
@@ -14,6 +14,7 @@ extern "C" {
#include "../../../src/routing_layer/topo_group.h"
#include "../../../src/member_files/protocol.h"
#include "../../../src/chat/chat_member.h"
#include "../../../src/chat/chat_core.h"
}
/* ── Внутренний объект-приёмник в GUI-потоке ── */
@@ -37,6 +38,7 @@ static gui_auto_connect_status_fn g_auto_connect_status_cb = nullptr;
static gui_channel_peers_online_fn g_channel_peers_online_cb = nullptr;
static gui_db_ready_fn g_db_ready_cb = nullptr;
static gui_status_refresh_fn g_status_refresh_cb = nullptr;
static gui_cpu_load_fn g_cpu_load_cb = nullptr;
static gui_attachment_downloaded_fn g_attachment_downloaded_cb = nullptr;
static gui_download_progress_fn g_download_progress_cb = nullptr;
static gui_nodeinfo_update_fn g_nodeinfo_update_cb = nullptr;
@@ -89,6 +91,12 @@ void GuiBridgeReceiver::processPost(int eventType, QByteArray data) {
eventType == 16 || eventType == 17 || eventType == 24 || eventType == 25 || eventType == 31 || eventType == 33))
g_network_changed_cb(eventType);
switch (eventType) {
case CHAT_EVT_CPU_LOAD:
if (dlen != 2 || d[0] > 1 || d[1] > 100) {
DEBUG_WARN(DEBUG_CATEGORY_SYS, "invalid CPU load response bytes=%d", dlen);
if (g_cpu_load_cb) g_cpu_load_cb(0);
} else if (g_cpu_load_cb) g_cpu_load_cb(d[0] ? d[1] : 0);
break;
case CHAT_EVT_MSG_SUBMITTED:
if (dlen != 9 || d[8] > 1) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT, "invalid submission result bytes=%d", dlen); break; }
if (g_msg_submitted_cb) g_msg_submitted_cb(d, dlen);
@@ -497,6 +505,19 @@ void gui_bridge_set_status_refresh_cb(gui_status_refresh_fn cb) {
g_status_refresh_cb = cb;
}
void gui_bridge_set_cpu_load_cb(gui_cpu_load_fn cb) {
g_cpu_load_cb = cb;
}
int gui_bridge_request_cpu_load(void) {
if (!g_ua || !g_inst) return 0;
auto* task = (struct posted_task*)u_calloc(1, sizeof(struct posted_task));
if (!task) { DEBUG_ERROR(DEBUG_CATEGORY_SYS, "CPU load request allocation failed"); return 0; }
task->callback = chat_core_collect_cpu_load_trampoline; task->arg = g_inst;
uasync_post_reserved(g_ua, task);
return 1;
}
void gui_bridge_set_attachment_downloaded_cb(gui_attachment_downloaded_fn cb) {
g_attachment_downloaded_cb = cb;
}