From f406dd71a0517a95490990d9655596358f2379b9 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Tue, 17 Nov 2026 23:32:59 +0000
Subject: [PATCH 01/20] core, ui: validate short link type, show contact info
for long addresses and rejected contacts (#8184)
* tests: short link type, QR code capacity and contact statuses
* core: validate the type of short links
* android, desktop: show contact info for addresses above QR code capacity
* ui: show chats with rejected contact requests
* tests: short link types with group, channel and contact data
* core: validate short link type against link data
* tests: fix short link data test
* tests: group data in invitation link before its first use
* tests: connect via address in contact profile with group link
* core: connect via contact address only with address links
* core: parse short link data once, by link type
* core: types of short link data parser
* core: test short link types and contact rejection, record app fixtures
* android, desktop: test contact info, link alerts and rejected contacts
* ios: test invalid link alerts and rejected contacts in the chat list
* desktop: contact info tests find texts without app resources
* ui: core responses of invalid link plans and a rejected contact request
* desktop: contact info tests provide the app bar handler
* core: normalise file and message keys in app test fixtures
* core: normalise deletion times in app test fixtures
* desktop: test that a QR code above capacity is not shared on tap
* core: test relay link checks and known channel refresh from link data
---
.../SimpleX Unit Tests/NameAlertsTests.swift | 23 ++
apps/ios/SimpleXChat/ChatTypes.swift | 1 +
.../chat/simplex/common/model/ChatModel.kt | 3 +-
.../simplex/common/views/newchat/QRCode.kt | 19 +-
.../chat/simplex/app/ContactStatusTest.kt | 16 +
.../kotlin/chat/simplex/app/NameAlertsTest.kt | 29 ++
.../kotlin/chat/simplex/app/QRCodeTest.kt | 91 +++++
scripts/ci/README.md | 2 +-
src/Simplex/Chat/Library/Commands.hs | 56 ++-
src/Simplex/Chat/Library/Internal.hs | 30 +-
src/Simplex/Chat/Library/Subscriber.hs | 4 +-
src/Simplex/Chat/Protocol.hs | 17 +
tests/ChatTests/Groups.hs | 62 +++-
tests/ChatTests/Profiles.hs | 180 +++++++++-
tests/ChatTests/Utils.hs | 4 +-
.../api/connect/group-link-as-address.json | 30 ++
.../api/connect/group-link-as-channel.json | 30 ++
.../api/connect/request-rejected.json | 318 ++++++++++++++++++
18 files changed, 860 insertions(+), 55 deletions(-)
create mode 100644 apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/ContactStatusTest.kt
create mode 100644 apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/QRCodeTest.kt
create mode 100644 tests/fixtures/api/connect/group-link-as-address.json
create mode 100644 tests/fixtures/api/connect/group-link-as-channel.json
create mode 100644 tests/fixtures/api/connect/request-rejected.json
diff --git a/apps/ios/SimpleX Unit Tests/NameAlertsTests.swift b/apps/ios/SimpleX Unit Tests/NameAlertsTests.swift
index 6b3290c351..36b22f4016 100644
--- a/apps/ios/SimpleX Unit Tests/NameAlertsTests.swift
+++ b/apps/ios/SimpleX Unit Tests/NameAlertsTests.swift
@@ -221,6 +221,29 @@ final class NameAlertsTests: XCTestCase {
XCTAssertEqual(shownLocalChats, ["@3"])
}
+ @MainActor
+ func testGroupLinkAsAddress() async throws {
+ try recorded("connect/group-link-as-address")
+ connect("GROUP_LINK")
+ try await assertTexts(["Invalid connection link", "Please check that you used the correct link or ask your contact to send you another one.", "Ok"])
+ }
+
+ @MainActor
+ func testGroupLinkAsChannel() async throws {
+ try recorded("connect/group-link-as-channel")
+ connect("GROUP_LINK")
+ try await assertTexts(["Invalid connection link", "Please check that you used the correct link or ask your contact to send you another one.", "Ok"])
+ }
+
+ @MainActor
+ func testRejectedContactInChatList() async throws {
+ try recorded("connect/request-rejected")
+ ChatModel.shared.updateChats(try apiGetChats())
+ guard case let .direct(contact)? = ChatModel.shared.getContactChat(2)?.chatInfo else { return XCTFail("contact not decoded: \(ChatModel.shared.chats.map(\.id))") }
+ XCTAssertEqual(contact.contactStatus.rawValue, "rejected")
+ XCTAssertFalse(contact.active)
+ }
+
@MainActor
func testNameMovedEvent() async throws {
var contact = Contact.sampleData
diff --git a/apps/ios/SimpleXChat/ChatTypes.swift b/apps/ios/SimpleXChat/ChatTypes.swift
index 74d514922d..8d1e53b7a7 100644
--- a/apps/ios/SimpleXChat/ChatTypes.swift
+++ b/apps/ios/SimpleXChat/ChatTypes.swift
@@ -2760,6 +2760,7 @@ public enum ContactStatus: String, Decodable, Hashable {
case active = "active"
case deleted = "deleted"
case deletedByUser = "deletedByUser"
+ case rejected = "rejected"
}
public struct ContactRef: Decodable, Equatable, Hashable {
diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt
index 403af4185a..959c4315e0 100644
--- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt
+++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt
@@ -2105,7 +2105,8 @@ enum class ConnectionMode {
enum class ContactStatus {
@SerialName("active") Active,
@SerialName("deleted") Deleted,
- @SerialName("deletedByUser") DeletedByUser;
+ @SerialName("deletedByUser") DeletedByUser,
+ @SerialName("rejected") Rejected;
}
@Serializable
diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/QRCode.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/QRCode.kt
index 07dbb6aaea..eef8f963ab 100644
--- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/QRCode.kt
+++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/newchat/QRCode.kt
@@ -77,9 +77,9 @@ fun QRCode(
val errorLevel = if (small) QrCode.ErrorLevel.M else QrCode.ErrorLevel.L
val fixedQRCode = LocalFixedQRCode.current
val qr = remember(connReq, tintColor, withLogo) {
- (fixedQRCode ?: qrCodeBitmap(connReq, 1024, errorLevel)).replaceColor(Color.Black.toArgb(), tintColor.toArgb())
- .let { if (withLogo) it.addLogo(logoSize) else it }
- }
+ (fixedQRCode ?: qrCodeBitmap(connReq, 1024, errorLevel))?.replaceColor(Color.Black.toArgb(), tintColor.toArgb())
+ ?.let { if (withLogo) it.addLogo(logoSize) else it }
+ } ?: return
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Image(
bitmap = qr,
@@ -92,8 +92,8 @@ fun QRCode(
.then(modifier)
.clickable {
scope.launch {
- val image = qrCodeBitmap(connReq, 1024, errorLevel).replaceColor(Color.Black.toArgb(), tintColor.toArgb())
- .let { if (withLogo) it.addLogo(logoSize) else it }
+ val image = qrCodeBitmap(connReq, 1024, errorLevel)?.replaceColor(Color.Black.toArgb(), tintColor.toArgb())
+ ?.let { if (withLogo) it.addLogo(logoSize) else it } ?: return@launch
val file = saveTempImageUncompressed(image, true)
if (file != null) {
shareFile("", CryptoFile.plain(file.absolutePath))
@@ -105,8 +105,13 @@ fun QRCode(
}
}
-fun qrCodeBitmap(content: String, size: Int = 1024, errorLevel: QrCode.ErrorLevel): ImageBitmap {
- val qrCode = QrCodeEncoder().addAutomatic(content).setError(errorLevel).fixate()
+fun qrCodeBitmap(content: String, size: Int = 1024, errorLevel: QrCode.ErrorLevel): ImageBitmap? {
+ val qrCode = try {
+ QrCodeEncoder().addAutomatic(content).setError(errorLevel).fixate()
+ } catch (e: Exception) {
+ Log.e(TAG, "qrCodeBitmap error: ${e.message}")
+ return null
+ }
/** See [QrCodeGeneratorImage.initialize] and [FiducialImageEngine.configure] for size calculation */
val numModules = QrCode.totalModules(qrCode.version)
// Hide border on light themes to make it fit to the same place as camera in QRCodeScanner.
diff --git a/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/ContactStatusTest.kt b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/ContactStatusTest.kt
new file mode 100644
index 0000000000..d1ba98ac1f
--- /dev/null
+++ b/apps/multiplatform/common/src/commonTest/kotlin/chat/simplex/app/ContactStatusTest.kt
@@ -0,0 +1,16 @@
+package chat.simplex.app
+
+import chat.simplex.common.model.ContactStatus
+import chat.simplex.common.model.json
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+class ContactStatusTest {
+ @Test
+ fun testContactStatusesOfCore() {
+ listOf("active", "deleted", "deletedByUser", "rejected").forEach { status ->
+ val decoded = json.decodeFromString(ContactStatus.serializer(), "\"$status\"")
+ assertEquals("\"$status\"", json.encodeToString(ContactStatus.serializer(), decoded))
+ }
+ }
+}
diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/NameAlertsTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/NameAlertsTest.kt
index 486a65495f..1467582a78 100644
--- a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/NameAlertsTest.kt
+++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/NameAlertsTest.kt
@@ -246,6 +246,18 @@ class NameAlertsTest {
assertLocalChats("@3")
}
+ @Test
+ fun groupLinkAsAddress() = recordedAlerts("connect/group-link-as-address") {
+ connect("GROUP_LINK")
+ assertTexts("Invalid connection link", "Please check that you used the correct link or ask your contact to send you another one.", "OK")
+ }
+
+ @Test
+ fun groupLinkAsChannel() = recordedAlerts("connect/group-link-as-channel") {
+ connect("GROUP_LINK")
+ assertTexts("Invalid connection link", "Please check that you used the correct link or ask your contact to send you another one.", "OK")
+ }
+
@Test
fun connectByNameRowShowsLocalChats() = recorded("names/plan-known") {
val searchText = mutableStateOf(TextFieldValue("alice"))
@@ -298,6 +310,23 @@ class NameAlertsTest {
onNodeWithText("Connect to team.simplex").assertExists()
}
+ @Test
+ fun rejectedContactInChatList() = recorded("connect/request-rejected") {
+ ChatModel.chatRunning.value = true
+ runBlocking {
+ val chats = ChatController.apiGetChats(null)
+ withContext(Dispatchers.Main) { ChatModel.chatsContext.updateChats(chats) }
+ }
+ setContent {
+ CompositionLocalProvider(LocalAppBarHandler provides rememberAppBarHandler()) {
+ ChatListView(ChatModel, MutableStateFlow(AnimatedViewState.GONE), {}, false)
+ }
+ }
+ assertEquals(listOf("@2"), chatIds())
+ assertFalse((chatInfo("@2") as ChatInfo.Direct).contact.active)
+ waitUntil(timeoutMillis = 5_000) { onAllNodesWithText("alice").fetchSemanticsNodes().isNotEmpty() }
+ }
+
@Test
fun verifiedNameIsCopied() = simplexName(DomainVerification.Verified) { verifications, copied ->
onNodeWithText(SIMPLEX_NAME).performClick()
diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/QRCodeTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/QRCodeTest.kt
new file mode 100644
index 0000000000..d5d55abf97
--- /dev/null
+++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/QRCodeTest.kt
@@ -0,0 +1,91 @@
+package chat.simplex.app
+
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.test.ComposeUiTest
+import androidx.compose.ui.test.ExperimentalTestApi
+import androidx.compose.ui.test.assertCountEquals
+import androidx.compose.ui.test.onAllNodesWithContentDescription
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.runComposeUiTest
+import boofcv.alg.fiducial.qrcode.QrCode
+import chat.simplex.common.model.*
+import chat.simplex.common.views.chat.ChatInfoView
+import chat.simplex.common.views.helpers.LocalAppBarHandler
+import chat.simplex.common.views.helpers.rememberAppBarHandler
+import chat.simplex.common.views.newchat.LocalFixedQRCode
+import chat.simplex.common.views.newchat.SimpleXLinkQRCode
+import chat.simplex.common.views.newchat.qrCodeBitmap
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+
+@OptIn(ExperimentalTestApi::class)
+class QRCodeTest {
+ private val link = "https://simplex.chat/contact#/?v=2-7&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2FWHV0YU1sYlU7NqiEHkHDB6gxO1ofTync%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAWbebOqVYuBXaiqHcXYjEHCpYi6VzDlu6CVaijDTmsQU%253D"
+
+ @AfterTest
+ fun tearDown() {
+ ChatModel.chatsContext.chats.value.clear()
+ ChatModel.currentUser.value = null
+ }
+
+ @Test
+ fun testQRCodeBitmapOfLinkWithinCapacity() {
+ assertNotNull(qrCodeBitmap(link, errorLevel = QrCode.ErrorLevel.L))
+ assertNotNull(qrCodeBitmap(link, errorLevel = QrCode.ErrorLevel.M))
+ }
+
+ @Test
+ fun testNoQRCodeBitmapOfLinkAboveCapacity() {
+ assertNull(qrCodeBitmap("$link&data=${"a".repeat(3000)}", errorLevel = QrCode.ErrorLevel.L))
+ assertNull(qrCodeBitmap("$link&data=${"a".repeat(2400)}", errorLevel = QrCode.ErrorLevel.M))
+ }
+
+ @Test
+ fun testContactInfoShowsQRCodeOfAddress() = contactInfo(link) {
+ onNodeWithText(ADDRESS_FOOTER).assertExists()
+ onAllNodesWithContentDescription("QR Code").assertCountEquals(1)
+ }
+
+ @Test
+ fun testContactInfoWithoutQRCodeOfAddressAboveCapacity() = contactInfo("$link&data=${"a".repeat(3000)}") {
+ onNodeWithText(ADDRESS_FOOTER).assertExists()
+ onAllNodesWithContentDescription("QR Code").assertCountEquals(0)
+ }
+
+ @Test
+ fun testNoShareOfQRCodeAboveCapacity() = runComposeUiTest {
+ var shared = false
+ setContent {
+ CompositionLocalProvider(LocalFixedQRCode provides qrCodeBitmap(link, errorLevel = QrCode.ErrorLevel.L)) {
+ SimpleXLinkQRCode("$link&data=${"a".repeat(3000)}", onShare = { shared = true })
+ }
+ }
+ onNodeWithContentDescription("QR Code").performClick()
+ waitForIdle()
+ assertFalse(shared)
+ }
+
+ private fun contactInfo(address: String, test: ComposeUiTest.() -> Unit) = runComposeUiTest {
+ val contact = Contact.sampleData.copy(profile = LocalProfile.sampleData.copy(contactLink = address))
+ ChatModel.currentUser.value = User.sampleData
+ runBlocking { withContext(Dispatchers.Main) { ChatModel.chatsContext.updateChat(null, ChatInfo.Direct(contact)) } }
+ setContent {
+ CompositionLocalProvider(LocalAppBarHandler provides rememberAppBarHandler()) {
+ ChatInfoView(ChatModel.chatsContext, ChatModel, contact, connectionStats = null, customUserProfile = null, localAlias = "", connectionCode = null, close = {}, onSearchClicked = {})
+ }
+ }
+ test()
+ }
+
+ private companion object {
+ const val ADDRESS_FOOTER = "You can share this address with your contacts to let them connect with alice."
+ }
+}
diff --git a/scripts/ci/README.md b/scripts/ci/README.md
index cffdfec2a2..31b0e234b1 100644
--- a/scripts/ci/README.md
+++ b/scripts/ci/README.md
@@ -45,7 +45,7 @@ The reduced build runs one Linux job, build-linux (ubuntu-22.04 x86_64), for eve
- caches (the steps "Restore ... from cache");
- `cabal build -j --enable-tests --ghc-options=-O0` (step "Build CLI");
- simplex-chat-test with the selected tests (step "Run tests"), each attempt limited to 35 minutes by `timeout`; an attempt that reaches the limit fails, and "Attempt timed out." is printed.
-- App test fixtures: core tests write the core's responses and events that the app tests use to tests/fixtures/api (`/names tests/` to tests/fixtures/api/names, `/contact via address/` to tests/fixtures/api/connect, `/updated item event has the previous item/`, `/should send updated item with mentions added and removed by edit/` and `/mark call invitation missed when the caller ends the call/` to tests/fixtures/api/updates), and fail when a recording differs from the committed file; the rewritten files are committed, and the kotlin and ios scopes run for them.
+- App test fixtures: core tests write the core's responses and events that the app tests use to tests/fixtures/api (`/names tests/` to tests/fixtures/api/names; `/contact via address/`, `/should validate link type/` and `/reject contact and notify the sender/` to tests/fixtures/api/connect; `/updated item event has the previous item/`, `/should send updated item with mentions added and removed by edit/` and `/mark call invitation missed when the caller ends the call/` to tests/fixtures/api/updates), and fail when a recording differs from the committed file; the rewritten files are committed, and the kotlin and ios scopes run for them.
- Local:
```sh
cp scripts/cabal.project.local.linux cabal.project.local
diff --git a/src/Simplex/Chat/Library/Commands.hs b/src/Simplex/Chat/Library/Commands.hs
index 66c8f2b3c4..d12b9b4cba 100644
--- a/src/Simplex/Chat/Library/Commands.hs
+++ b/src/Simplex/Chat/Library/Commands.hs
@@ -1741,11 +1741,9 @@ processChatCommand cxt nm = \case
r <- tryAllErrors $ getShortLinkConnReq nm user address
case r of
Left e -> failAt RTSGetLink e
- Right (FixedLinkData {rootKey}, cData, cReq) -> do
- relayProfile_ <- liftIO $ decodeLinkUserData cData
- case relayProfile_ of
- Nothing -> failAt RTSDecodeLink (ChatError $ CERelayTestError "no relay address link data")
- Just RelayAddressLinkData {relayProfile} -> do
+ Right (FixedLinkData {rootKey}, _, cReq, sLinkData_) ->
+ case sLinkData_ of
+ Just (SLDRelayAddress RelayAddressLinkData {relayProfile}) -> do
let failWithProfile step e =
pure $ CRChatRelayTestResult user (Just relayProfile) (Just $ RelayTestFailure step e)
lift (withAgent' (`connRequestAgentVersion` cReq)) >>= \case
@@ -1774,6 +1772,7 @@ processChatCommand cxt nm = \case
Right Nothing -> failWithProfile RTSWaitResponse (ChatError $ CERelayTestError "timeout")
Right (Just Nothing) -> pure $ CRChatRelayTestResult user (Just relayProfile) Nothing
Right (Just (Just failure)) -> pure $ CRChatRelayTestResult user (Just relayProfile) (Just failure)
+ _ -> failAt RTSDecodeLink (ChatError $ CERelayTestError "no relay address link data")
TestChatRelay address -> withUser $ \User {userId} ->
processChatCommand cxt nm $ APITestChatRelay userId address
APIAllowRelayGroup groupId -> withUser $ \user -> do
@@ -1986,10 +1985,9 @@ processChatCommand cxt nm = \case
gInfo@GroupInfo {groupProfile = p} <- withFastStore $ \db -> getGroupInfo db cxt user groupId
case p of
GroupProfile {publicGroup = Just PublicGroupProfile {groupLink = sLnk, publicGroupId}} | useRelays' gInfo -> do
- (FixedLinkData {linkEntityId}, cData@(ContactLinkData _ UserContactData {relays = currentRelayLinks}), _) <- getShortLinkConnReq' nm user sLnk
+ (FixedLinkData {linkEntityId}, ContactLinkData _ UserContactData {relays = currentRelayLinks}, _, sLinkData_) <- getShortLinkConnReq' nm user sLnk
unless ((B64UrlByteString <$> linkEntityId) == Just publicGroupId) $ throwChatError CEInvalidConnReq
- groupSLinkData_ <- liftIO $ decodeLinkUserData cData
- gInfo' <- case groupSLinkData_ of
+ gInfo' <- case shortLinkGroupData =<< sLinkData_ of
Just sLinkData -> (\(g, _, _) -> g) <$> updateGroupFromLinkData user gInfo sLinkData Nothing
_ -> pure gInfo
when (memberRole' (membership gInfo) /= GROwner && memberCurrent (membership gInfo)) $
@@ -2352,8 +2350,8 @@ processChatCommand cxt nm = \case
sLnk <- case connShortLink' connLinkToConnect of
Just sl -> pure sl
Nothing -> throwChatError $ CEException "failed to retrieve relays: no short link"
- (FixedLinkData {linkEntityId, rootKey}, cData@(ContactLinkData _ UserContactData {owners, relays}), mainCReq@(CRContactUri crData e2e)) <- getShortLinkConnReq nm user sLnk
- groupSLinkData_ <- liftIO $ decodeLinkUserData cData
+ (FixedLinkData {linkEntityId, rootKey}, ContactLinkData _ UserContactData {owners, relays}, mainCReq@(CRContactUri crData e2e), sLinkData_) <- getShortLinkConnReq nm user sLnk
+ let groupSLinkData_ = shortLinkGroupData =<< sLinkData_
-- Validate link entity ID matches group profile's publicGroupId (relay groups must have both)
case groupSLinkData_ of
Just sLinkData@GroupShortLinkData {groupProfile = GroupProfile {publicGroup = Just PublicGroupProfile {publicGroupId}}}
@@ -2490,9 +2488,10 @@ processChatCommand cxt nm = \case
when (isJust groupDirectInv) $ throwCmdError "contact is a member contact request"
ccLink <- case contactLink of
Just (CLFull cReq) -> pure $ CCLink cReq Nothing
- Just (CLShort sLnk) -> do
- (_, _, cReq) <- getShortLinkConnReq nm user sLnk
+ Just (CLShort sLnk@(CSLContact _ CCTContact _ _)) -> do
+ (_, _, cReq, _) <- getShortLinkConnReq nm user sLnk
pure $ CCLink cReq $ Just sLnk
+ Just (CLShort _) -> throwChatError CEInvalidConnReq
Nothing -> throwCmdError "no address in contact profile"
connectContactViaAddress user incognito ct ccLink `catchAllErrors` \e -> do
-- get updated contact, in case connection was started - in UI it would lock ability to change incognito choice
@@ -4045,10 +4044,9 @@ processChatCommand cxt nm = \case
-- Save relayLink to re-use relay member record on retry (check by relayLink)
relayMember <- withFastStore $ \db -> getCreateRelayForMember db cxt gVar user gInfo relayLink
r <- tryAllErrors $ do
- (FixedLinkData {rootKey = relayKey, linkEntityId}, cData, cReq) <- getShortLinkConnReq nm user relayLink
- relayLinkData_ <- liftIO $ decodeLinkUserData cData
- relayMemberId <- case (relayLinkData_, linkEntityId) of
- (Just RelayShortLinkData {relayProfile = p}, Just entityId) -> do
+ (FixedLinkData {rootKey = relayKey, linkEntityId}, _, cReq, sLinkData_) <- getShortLinkConnReq nm user relayLink
+ relayMemberId <- case (sLinkData_, linkEntityId) of
+ (Just (SLDRelayLink RelayShortLinkData {relayProfile = p}), Just entityId) -> do
withFastStore $ \db -> updateRelayMemberData db cxt user relayMember (MemberId entityId) (MemberKey relayKey) p
pure $ MemberId entityId
_ -> throwChatError $ CEException "relay link: no relay link data or entity id"
@@ -4453,7 +4451,7 @@ processChatCommand cxt nm = \case
where
addRelay :: UserChatRelay -> CM (UserChatRelay, Either ChatError GroupRelay)
addRelay relay@UserChatRelay {address} = fmap (relay,) . tryAllErrors $ do
- (_, _, cReq) <- getShortLinkConnReq nm user address
+ (_, _, cReq, _) <- getShortLinkConnReq nm user address
lift (withAgent' (`connRequestAgentVersion` cReq)) >>= \case
Nothing -> throwChatError CEInvalidConnReq
Just _ -> do
@@ -4555,8 +4553,8 @@ processChatCommand cxt nm = \case
knownLinkPlans l' >>= \case
Just (createdLink, p) -> pure (createdLink, Nothing, Nothing, p)
Nothing -> do
- (FixedLinkData {rootKey}, cData, cReq) <- getShortLinkConnReq nm user l'
- contactSLinkData_ <- mapM (linkDataBadge $ linkPresHeader l') =<< liftIO (decodeLinkUserData cData)
+ (FixedLinkData {rootKey}, _, cReq, sLinkData_) <- getShortLinkConnReq nm user l'
+ contactSLinkData_ <- mapM (linkDataBadge $ linkPresHeader l') $ shortLinkContactData =<< sLinkData_
let ov = verifyLinkOwner rootKey [] l sig_
invitationReqAndPlan cReq (Just l') contactSLinkData_ ov
where
@@ -4611,9 +4609,9 @@ processChatCommand cxt nm = \case
resolveSLink >>= contactLinkPlan Nothing
where
contactLinkPlan knownChat_ l' = do
- (FixedLinkData {rootKey}, cData, cReq) <- getShortLinkConnReq nm user l'
+ (FixedLinkData {rootKey}, cData, cReq, sLinkData_) <- getShortLinkConnReq nm user l'
let presHeader = linkPresHeader l'
- contactSLinkData_ <- mapM (linkDataBadge presHeader) =<< liftIO (decodeLinkUserData cData)
+ contactSLinkData_ <- mapM (linkDataBadge presHeader) $ shortLinkContactData =<< sLinkData_
let linkProfile_ = (\ContactShortLinkData {profile} -> profile) <$> contactSLinkData_
linkDomain_ = linkProfile_ >>= \Profile {contactDomain} -> claimDomain <$> contactDomain
planDomain = case nl of CTName ni -> Just (nameDomain ni); _ -> Nothing
@@ -4680,9 +4678,9 @@ processChatCommand cxt nm = \case
resolveSLink >>= groupLinkPlan Nothing
where
groupLinkPlan knownChat_ l' = do
- (fd, cData@(ContactLinkData _ UserContactData {direct, owners, relays}), cReq) <- getShortLinkConnReq' nm user l'
- groupSLinkData_ <- liftIO $ decodeLinkUserData cData
- let planDomain = case nl of CTName ni -> Just (nameDomain ni); _ -> Nothing
+ (fd, ContactLinkData _ UserContactData {direct, owners, relays}, cReq, sLinkData_) <- getShortLinkConnReq' nm user l'
+ let groupSLinkData_ = shortLinkGroupData =<< sLinkData_
+ planDomain = case nl of CTName ni -> Just (nameDomain ni); _ -> Nothing
nc_ = NCMoved <$> knownChat_
knownMoved moved = NCMoved . movedChat moved <$> knownChat_
plan <- if
@@ -4726,8 +4724,8 @@ processChatCommand cxt nm = \case
Nothing -> (gPlan =<<) <$> getGroupToConnect db cxt user nl'
resolveKnownGroup g = do
l' <- resolveSLink
- (FixedLinkData {rootKey = rk}, cData@(ContactLinkData _ UserContactData {owners}), cReq) <- getShortLinkConnReq' nm user l'
- groupSLinkData_ <- liftIO $ decodeLinkUserData cData
+ (FixedLinkData {rootKey = rk}, ContactLinkData _ UserContactData {owners}, cReq, sLinkData_) <- getShortLinkConnReq' nm user l'
+ let groupSLinkData_ = shortLinkGroupData =<< sLinkData_
let ov = verifyLinkOwner rk owners l' sig_
glOwners = map (\OwnerAuth {ownerId, ownerKey} -> GroupLinkOwner {memberId = MemberId ownerId, memberKey = ownerKey}) owners
(g', updated, _) <- case groupSLinkData_ of
@@ -5348,7 +5346,7 @@ verifyEntityDomain user nm nameType SimplexDomainClaim {domain = StrJSON domain,
where
verifyDomainProof :: SimplexDomainProof -> ShortLinkContact -> CM Bool
verifyDomainProof SimplexDomainProof {linkOwnerId, presHeader, signature} sLnk@(CSLContact _ ct srv key) = do
- (FixedLinkData {rootKey}, ContactLinkData _ UserContactData {owners}, _) <- getShortLinkConnReq nm user sLnk
+ (FixedLinkData {rootKey}, ContactLinkData _ UserContactData {owners}, _, _) <- getShortLinkConnReq nm user sLnk
let ownerKey_ = case linkOwnerId of
Nothing -> Just rootKey
Just (StrJSON oid) -> ownerKey <$> find (\OwnerAuth {ownerId} -> ownerId == oid) owners
@@ -6502,7 +6500,7 @@ sendServiceRequestBytes nm user sendTarget requestTimeout signKey request = do
case firstNameLink CCTContact (nrSimplexContact nr) of
Just sLnk -> resolveShortLink sLnk
Nothing -> throwChatError $ CESimplexDomainNotReady d SDENoValidLink
- resolveShortLink sLnk = (\(_, _, cReq) -> cReq) <$> getShortLinkConnReq nm user sLnk
+ resolveShortLink sLnk = (\(_, _, cReq, _) -> cReq) <$> getShortLinkConnReq nm user sLnk
assertDirectAllowed :: User -> MsgDirection -> Contact -> CMEventTag e -> CM ()
assertDirectAllowed user dir ct event =
@@ -6697,7 +6695,7 @@ runRelayGroupLinkChecks user = do
forM_ relayGroups $ \g@(GIK gInfo@GroupInfo {groupProfile = gp} _) -> flip catchAllErrors eToView $ do
case publicGroup gp of
Just PublicGroupProfile {groupLink = sLnk} -> do
- (_, ContactLinkData _ UserContactData {relays = relayLinks}, _) <-
+ (_, ContactLinkData _ UserContactData {relays = relayLinks}, _, _) <-
getShortLinkConnReq' NRMBackground user sLnk
gLink_ <- withStore' $ \db -> runExceptT $ getGroupLink db user gInfo
case gLink_ of
diff --git a/src/Simplex/Chat/Library/Internal.hs b/src/Simplex/Chat/Library/Internal.hs
index 17ca822ddb..a734a8c617 100644
--- a/src/Simplex/Chat/Library/Internal.hs
+++ b/src/Simplex/Chat/Library/Internal.hs
@@ -28,6 +28,7 @@ import Control.Monad.IO.Unlift
import Control.Monad.Reader
import Crypto.Random (ChaChaDRG)
import qualified Data.Aeson as J
+import qualified Data.Aeson.Types as JT
import Data.Bifunctor (first)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
@@ -1721,14 +1722,35 @@ groupLinkData (GIK gInfo@GroupInfo {groupProfile, groupSummary = GroupSummary {p
restoreShortLink' :: ConnShortLink m -> CM (ConnShortLink m)
restoreShortLink' l = (`restoreShortLink` l) <$> asks (shortLinkPresetServers . config)
-getShortLinkConnReq' :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m)
+getShortLinkConnReq' :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m, Maybe ShortLinkData)
getShortLinkConnReq' nm user l = do
l' <- restoreShortLink' l
- withAgent $ \a -> getConnShortLink a nm (aUserId user) l'
+ (fd, cData, cReq) <- withAgent $ \a -> getConnShortLink a nm (aUserId user) l'
+ linkData <- liftIO $ decodeLinkUserData cData
+ case JT.parseMaybe (shortLinkDataP l) (fromMaybe J.Null linkData) of
+ Just sLinkData_ -> pure (fd, cData, cReq, sLinkData_)
+ Nothing -> throwChatError CEInvalidConnReq
-getShortLinkConnReq :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m)
+shortLinkDataP :: ConnShortLink m -> J.Value -> JT.Parser (Maybe ShortLinkData)
+shortLinkDataP l v = case l of
+ CSLInvitation {} -> optionalData $ contact <|> group notChannel
+ CSLContact _ ct _ _ -> case ct of
+ CCTContact -> optionalData $ contact <|> relayAddress
+ CCTGroup -> optionalData $ group notChannel <|> relayLink
+ CCTChannel -> Just <$> group isJust
+ CCTRelay -> optionalData $ relayAddress <|> contact
+ where
+ optionalData :: JT.Parser ShortLinkData -> JT.Parser (Maybe ShortLinkData)
+ optionalData p = if v == J.Null then pure Nothing else Just <$> p
+ contact = SLDContact <$> J.parseJSON v
+ relayLink = SLDRelayLink <$> J.parseJSON v
+ relayAddress = SLDRelayAddress <$> J.parseJSON v
+ group ok = SLDGroup <$> mfilter (\GroupShortLinkData {groupProfile = GroupProfile {publicGroup}} -> ok publicGroup) (J.parseJSON v)
+ notChannel = maybe True (\PublicGroupProfile {groupType} -> groupType /= GTChannel)
+
+getShortLinkConnReq :: NetworkRequestMode -> User -> ConnShortLink m -> CM (FixedLinkData m, ConnLinkData m, ConnectionRequestUri m, Maybe ShortLinkData)
getShortLinkConnReq nm user l = do
- r@(_, cData, _) <- getShortLinkConnReq' nm user l
+ r@(_, cData, _, _) <- getShortLinkConnReq' nm user l
case cData of
ContactLinkData _ UserContactData {direct, relays}
| not direct && null relays -> throwChatError CEUnsupportedConnReq
diff --git a/src/Simplex/Chat/Library/Subscriber.hs b/src/Simplex/Chat/Library/Subscriber.hs
index 7cea9f4a8c..39d0971c7e 100644
--- a/src/Simplex/Chat/Library/Subscriber.hs
+++ b/src/Simplex/Chat/Library/Subscriber.hs
@@ -4615,8 +4615,8 @@ runRelayRequestWorker a Worker {doWork} = do
memberPrivKey' <- case gks of
GKRelayRequest {memberPrivKey} -> pure memberPrivKey
_ -> throwChatError $ CEException "getLinkDataCreateRelayLink: group is not a relay request"
- (FixedLinkData {linkEntityId, rootKey}, cData@(ContactLinkData _ UserContactData {owners}), _) <- getShortLinkConnReq' NRMBackground user reqGroupLink
- liftIO (decodeLinkUserData cData) >>= \case
+ (FixedLinkData {linkEntityId, rootKey}, ContactLinkData _ UserContactData {owners}, _, sLinkData_) <- getShortLinkConnReq' NRMBackground user reqGroupLink
+ case shortLinkGroupData =<< sLinkData_ of
Nothing -> throwChatError $ CEException "getLinkDataCreateRelayLink: no group link data"
Just GroupShortLinkData {groupProfile = gp@GroupProfile {publicGroup}} -> do
pg <- case (linkEntityId, publicGroup) of
diff --git a/src/Simplex/Chat/Protocol.hs b/src/Simplex/Chat/Protocol.hs
index 62b00bb46f..9848b497c4 100644
--- a/src/Simplex/Chat/Protocol.hs
+++ b/src/Simplex/Chat/Protocol.hs
@@ -1665,3 +1665,20 @@ data RelayAddressLinkData = RelayAddressLinkData {relayProfile :: RelayProfile}
$(JQ.deriveJSON defaultJSON ''RelayAddressLinkData)
+data ShortLinkData
+ = SLDContact ContactShortLinkData
+ | SLDGroup GroupShortLinkData
+ | SLDRelayLink RelayShortLinkData
+ | SLDRelayAddress RelayAddressLinkData
+ deriving (Show)
+
+shortLinkContactData :: ShortLinkData -> Maybe ContactShortLinkData
+shortLinkContactData = \case
+ SLDContact d -> Just d
+ _ -> Nothing
+
+shortLinkGroupData :: ShortLinkData -> Maybe GroupShortLinkData
+shortLinkGroupData = \case
+ SLDGroup d -> Just d
+ _ -> Nothing
+
diff --git a/tests/ChatTests/Groups.hs b/tests/ChatTests/Groups.hs
index 34a56e9d86..526a9b6e93 100644
--- a/tests/ChatTests/Groups.hs
+++ b/tests/ChatTests/Groups.hs
@@ -14,7 +14,7 @@ module ChatTests.Groups where
import ChatClient
import ChatTests.DBUtils
-import ChatTests.Profiles (addTestBadge, futureDate, issueTestBadge, testBadgeKeys)
+import ChatTests.Profiles (addTestBadge, futureDate, invalidLink, issueTestBadge, setLinkType, setTestGroupLinkData, testBadgeKeys)
import ChatTests.Utils
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (concurrently_)
@@ -46,7 +46,7 @@ import Simplex.Chat.Types.Shared (GroupMemberRole (..), GroupAcceptance (..))
import Simplex.Chat.Types.UITheme (ChatLayout (..))
import Simplex.Messaging.Agent (createConnection, joinConnection, prepareConnectionToJoin, sendMessages, vrValue)
import Simplex.Messaging.Agent.Env.SQLite
-import Simplex.Messaging.Agent.Protocol (CreatedConnLink (..), SConnectionMode (..))
+import Simplex.Messaging.Agent.Protocol (CreatedConnLink (..), SConnectionMode (..), UserLinkData (..))
import Simplex.Messaging.Agent.RetryInterval
import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Agent.Store.DB (Binary (..), BoolInt (..))
@@ -324,7 +324,10 @@ chatGroupTests = do
it "should preserve owner key in link data after profile update" testChannelOwnerKeyAfterLinkUpdate
it "should keep channel profile from link data when joining" testChannelJoinKeepsLinkProfile
it "should apply channel profile from link data when joining" testChannelJoinAppliesLinkProfile
+ it "should apply channel profile from link data to known channel in plan" testChannelPlanAppliesLinkProfile
it "should check entity ID of channel link on refresh" testChannelLinkDataOtherChannel
+ it "should validate type of channel link" testChannelLinkAsOtherTypes
+ it "relay link checks should skip invalid channel link data" testRelayLinkChecksInvalidData
it "should update channel preferences (signed)" testChannelUpdatePrefsSigned
it "should change member role (signed)" testChannelChangeRoleSigned
it "should block member for all (signed)" testChannelBlockMemberSigned
@@ -3759,7 +3762,7 @@ sendMemberJoinRequest cc groupLink =
gLink :: ShortLinkContact <- either fail pure $ strDecode (B.pack groupLink)
(memberKey, _) <- atomically . C.generateKeyPair =<< C.newRandom
let joinGroup = do
- (_, _, cReq) <- getShortLinkConnReq NRMInteractive user gLink
+ (_, _, cReq, _) <- getShortLinkConnReq NRMInteractive user gLink
(connId, _) <- withAgent $ \a -> prepareConnectionToJoin a (aUserId user) True cReq PQSupportOff
dm <- encodeConnInfo $ XMember bobProfile (MemberId "member") (MemberKey memberKey) Nothing
withAgent $ \a -> joinConnection a NRMInteractive (aUserId user) connId True cReq dm PQSupportOff SMSubscribe
@@ -10903,6 +10906,57 @@ testChannelLinkDataOtherChannel ps =
cath <## "Please ask your contact to check /version and update if needed."
cath <## "To update run: curl -o- https://raw.githubusercontent.com/simplex-chat/simplex-chat/master/install.sh | bash"
+testChannelLinkAsOtherTypes :: HasCallStack => TestParams -> IO ()
+testChannelLinkAsOtherTypes ps =
+ withNewTestChat ps "alice" aliceProfile $ \alice ->
+ withNewTestChatOpts ps relayTestOpts "bob" bobProfile $ \bob ->
+ withNewTestChat ps "cath" cathProfile $ \cath -> do
+ (shortLink, _) <- prepareChannel1Relay "team" alice bob
+ cath ##> ("/_connect plan 1 " <> shortLink)
+ cath <## "group link: ok to connect via relays"
+ _ <- getTermLine cath
+ forM_ ["/g#", "/a#"] $ \linkType -> do
+ cath ##> ("/_connect plan 1 " <> setLinkType "/c#" linkType shortLink)
+ invalidLink cath
+ cath ##> ("/relay test " <> setLinkType "/c#" "/r#" shortLink)
+ cath <## "relay test failed at RTSGetLink, error: ChatError {errorType = CEInvalidConnReq}"
+
+testChannelPlanAppliesLinkProfile :: HasCallStack => TestParams -> IO ()
+testChannelPlanAppliesLinkProfile ps =
+ withNewTestChat ps "alice" aliceProfile $ \alice ->
+ withNewTestChatOpts ps relayTestOpts "bob" bobProfile $ \bob ->
+ withNewTestChat ps "cath" cathProfile $ \cath -> do
+ (shortLink, fullLink) <- prepareChannel1Relay "team" alice bob
+ memberJoinChannel "team" [bob] [alice] shortLink fullLink cath
+ withCCTransaction cath $ \db ->
+ DB.execute_ db "UPDATE group_profiles SET short_descr = 'local copy'"
+ cath ##> ("/_connect plan 1 " <> shortLink <> " resolve=allGroups")
+ cath <## "group link: known group #team"
+ cath <## "use #team to send messages"
+ withCCTransaction cath (\db -> DB.query_ db "SELECT short_descr FROM group_profiles" :: IO [Only (Maybe T.Text)])
+ `shouldReturn` [Only Nothing]
+
+testRelayLinkChecksInvalidData :: HasCallStack => TestParams -> IO ()
+testRelayLinkChecksInvalidData ps =
+ withNewTestChat ps "alice" aliceProfile $ \alice ->
+ withNewTestChatCfgOpts ps testCfg {relayChecksInterval = 3} relayTestOpts "bob" bobProfile $ \bob -> do
+ _ <- prepareChannel1Relay "team" alice bob
+ relayOwnStatus bob "active"
+ setTestGroupLinkData alice $ UserLinkData ""
+ invalidLink bob
+ relayOwnStatus bob "active"
+ bob ##> "/_stop"
+ bob <## "chat stopped"
+ where
+ relayOwnStatus :: HasCallStack => TestCC -> T.Text -> IO ()
+ relayOwnStatus cc status = go (100 :: Int)
+ where
+ go n = do
+ [Only s] <- withCCTransaction cc $ \db -> DB.query_ db "SELECT relay_own_status FROM groups" :: IO [Only T.Text]
+ if s == status || n == 0
+ then s `shouldBe` status
+ else threadDelay 100000 >> go (n - 1)
+
testChannelUpdatePrefsSigned :: HasCallStack => TestParams -> IO ()
testChannelUpdatePrefsSigned ps =
withNewTestChat ps "alice" aliceProfile $ \alice ->
@@ -12267,7 +12321,7 @@ sendUnsignedRelayInv cc relayAddress =
fromMemberKey = Just $ MemberKey memberKey
}
joinRelay = do
- (_, _, cReq) <- getShortLinkConnReq NRMInteractive user relayLink
+ (_, _, cReq, _) <- getShortLinkConnReq NRMInteractive user relayLink
(connId, _) <- withAgent $ \a -> prepareConnectionToJoin a (aUserId user) True cReq PQSupportOff
dm <- encodeConnInfo $ XGrpRelayInv inv
withAgent $ \a -> joinConnection a NRMInteractive (aUserId user) connId True cReq dm PQSupportOff SMSubscribe
diff --git a/tests/ChatTests/Profiles.hs b/tests/ChatTests/Profiles.hs
index dff29295bf..e54ccac18e 100644
--- a/tests/ChatTests/Profiles.hs
+++ b/tests/ChatTests/Profiles.hs
@@ -19,6 +19,7 @@ import Control.Concurrent.Async (concurrently, concurrently_)
import Control.Monad
import Control.Monad.Except
import Control.Monad.Reader (runReaderT)
+import qualified Data.Aeson as J
import qualified Data.Attoparsec.ByteString.Char8 as A
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
@@ -26,14 +27,15 @@ import Data.Time.Clock (UTCTime, addUTCTime, getCurrentTime, nominalDay)
import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds)
import Data.Time.Format (defaultTimeLocale, formatTime)
import qualified Data.Map.Strict as M
+import ProtocolTests (testGroupProfile)
import Simplex.Chat.Badges (BadgeCredential, BadgeInfo (..), BadgeProof, BadgePurchase (..), BadgeRequest (..), BadgeStatus (..), BadgeType (..), LocalBadge (..), ProofPresHeader (..), badgeProof, generateMasterKey, issueBadge, verifyPayment)
import Simplex.Chat.Controller (CM, ChatConfig (..), ChatController (ChatController, smpAgent), ChatHooks (..), defaultChatHooks, storeCxt, withAgent)
import Simplex.Chat.Library.Internal (encodeConnInfo, encodeShortLinkData, getShortLinkConnReq, groupMemberKey, redactedMemberProfile, sendDirectContactMessage, sendGroupMessage')
import Simplex.Chat.Options (ChatOpts (..), CoreChatOpts (..))
-import Simplex.Chat.Protocol (ChatBinding (..), ChatMsgEvent (XContact, XInfo, XOk), ContactShortLinkData (ContactShortLinkData), LinkOwnerSig, MsgChatLink (..), MsgContent (..), encodeChatBinding)
+import Simplex.Chat.Protocol (ChatBinding (..), ChatMsgEvent (XContact, XInfo, XOk), ContactShortLinkData (ContactShortLinkData), GroupShortLinkData (GroupShortLinkData), LinkOwnerSig, MsgChatLink (..), MsgContent (..), encodeChatBinding)
import Simplex.Chat.Store.Groups (getGroupMembers)
import Simplex.Chat.Store.Shared (createContact, getGroupInfoKeys)
-import Simplex.Chat.Types (AgentConnId (..), ChatPeerType (..), ConnStatus (..), GroupId, GroupInfo (..), GroupInfoKeys (..), GroupMember (..), ImageData (..), Profile (..), GroupRejectionReason (..), ShortLinkContact, User (..), aUserId, fromLocalProfile, profileFromName, userProfileDirect, pattern VersionChat)
+import Simplex.Chat.Types (AgentConnId (..), B64UrlByteString (..), ChatPeerType (..), ConnStatus (..), GroupId, GroupInfo (..), GroupInfoKeys (..), GroupMember (..), GroupProfile (publicGroup), GroupType (..), ImageData (..), Profile (..), PublicGroupProfile (PublicGroupProfile), GroupRejectionReason (..), ShortLinkContact, User (..), aUserId, fromLocalProfile, profileFromName, userProfileDirect, pattern VersionChat)
import qualified Simplex.Messaging.Crypto as C
import Simplex.Messaging.Crypto.BBS (BBSPublicKey, BBSSecretKey, bbsKeyGen)
import Simplex.Messaging.Crypto.Ratchet (pattern PQSupportOff)
@@ -41,7 +43,7 @@ import Simplex.Chat.Types.Shared (GroupMemberRole (..))
import Simplex.Chat.Types.UITheme
import Simplex.Messaging.Agent (joinConnection, prepareConnectionToJoin, setConnShortLink)
import Simplex.Messaging.Agent.Env.SQLite
-import Simplex.Messaging.Agent.Protocol (SConnectionMode (..), UserConnLinkData (..))
+import Simplex.Messaging.Agent.Protocol (SConnectionMode (..), UserConnLinkData (..), UserContactData (..), UserLinkData (..))
import Simplex.Messaging.Agent.RetryInterval
import qualified Simplex.Messaging.Agent.Store.DB as DB
import Simplex.Messaging.Client (pattern NRMInteractive)
@@ -116,6 +118,7 @@ chatProfileTests = do
it "duplicate contact request from connected contact" testDuplicateContactRequestConnected
it "contact requests with invalid or unsupported messages" testContactRequestsInvalidMessages
it "reject contact and delete contact link" testRejectContactAndDeleteUserContact
+ it "reject contact and notify the sender" testRejectContactNotifySender
it "keep connection requests when contact link deleted" testKeepConnectionRequests
it "connected contact works when contact link deleted" testContactLinkDeletedConnectedContactWorks
it "auto-reply message" testAutoReplyMessage
@@ -182,6 +185,17 @@ chatProfileTests = do
it "should connect via contact address" testShortLinkContactAddress
it "should share contact address via chat" testShareAddressViaChat
it "should join group" testShortLinkJoinGroup
+ describe "should validate link type" $ do
+ it "group link as address" $ testGroupLinkAsType "/a#" "connect/group-link-as-address"
+ it "group link as channel" $ testGroupLinkAsType "/c#" "connect/group-link-as-channel"
+ it "group link as relay address" testGroupLinkAsRelay
+ it "relay address as address, address as relay address" testRelayAddressLinkTypes
+ it "address as group link and channel" testAddressAsGroupLink
+ it "group link as address in contact profile" testGroupLinkInContactProfile
+ it "contact data in group link" testContactDataInGroupLink
+ it "channel data in invitation" testChannelDataInInvitation
+ it "invitation, address and group link with their data" testLinksWithTheirData
+ it "invitation and channel link without data" testLinksWithoutData
describe "short links with attached data" shortLinkTests
describe "client services" $ do
it "should create user as a service, disable and re-enable" testClientService
@@ -1167,13 +1181,22 @@ sendTestMemberProof cc groupId proof =
runExceptT (sendGroupMessage' user g members (XInfo p (Just $ groupMemberKey gks))) `runReaderT` chatController cc
>>= either (fail . show) (\_ -> pure ())
-setTestInvLinkData :: TestCC -> ContactShortLinkData -> IO ()
+setTestInvLinkData :: J.ToJSON a => TestCC -> a -> IO ()
setTestInvLinkData cc linkData = do
[Only (AgentConnId connId)] <- withCCTransaction cc $ \db -> DB.query_ db "SELECT agent_conn_id FROM connections"
let ChatController {smpAgent} = chatController cc
runExceptT (setConnShortLink smpAgent NRMInteractive connId SCMInvitation (UserInvLinkData $ encodeShortLinkData linkData) Nothing False Nothing)
>>= either (fail . show) (\_ -> pure ())
+setTestGroupLinkData :: TestCC -> UserLinkData -> IO ()
+setTestGroupLinkData cc linkData = do
+ [Only (AgentConnId connId)] <- withCCTransaction cc $ \db ->
+ DB.query_ db "SELECT c.agent_conn_id FROM connections c JOIN user_contact_links l ON l.user_contact_link_id = c.user_contact_link_id WHERE l.group_id IS NOT NULL"
+ let ChatController {smpAgent} = chatController cc
+ contactData = UserContactData {direct = True, owners = [], relays = [], userData = linkData, ratchetKeys = Nothing}
+ runExceptT (setConnShortLink smpAgent NRMInteractive connId SCMContact (UserContactLinkData contactData) Nothing False Nothing)
+ >>= either (fail . show) (\_ -> pure ())
+
testUpdateProfileImage :: HasCallStack => TestParams -> IO ()
testUpdateProfileImage =
testChat2 aliceProfile bobProfile $
@@ -1871,7 +1894,7 @@ sendAddressRequest cc address encodeInfo =
withCCUser cc $ \user -> do
sLink <- either fail pure $ strDecode @ShortLinkContact (B.pack address)
let sendRequest = do
- (_, _, cReq) <- getShortLinkConnReq NRMInteractive user sLink
+ (_, _, cReq, _) <- getShortLinkConnReq NRMInteractive user sLink
(connId, _) <- withAgent $ \a -> prepareConnectionToJoin a (aUserId user) True cReq PQSupportOff
connInfo <- encodeInfo
withAgent $ \a -> joinConnection a NRMInteractive (aUserId user) connId True cReq connInfo PQSupportOff SMSubscribe
@@ -1903,6 +1926,26 @@ testRejectContactAndDeleteUserContact = testChat3 aliceProfile bobProfile cathPr
cath ##> ("/c " <> cLink)
cath <## "error: connection authorization failed - this could happen if connection was deleted, secured with different credentials, or due to a bug - please re-create the connection"
+testRejectContactNotifySender :: HasCallStack => TestParams -> IO ()
+testRejectContactNotifySender =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ alice ##> "/ad pq_ratchet=on"
+ (shortLink, fullLink) <- getContactLinks alice True
+ bob ##> ("/_connect plan 1 " <> shortLink)
+ bob <## "contact address: ok to connect"
+ contactSLinkData <- getTermLine bob
+ bob ##> ("/_prepare contact 1 " <> fullLink <> " " <> shortLink <> " " <> contactSLinkData)
+ bob <## "alice: contact is prepared"
+ bob ##> "/_connect contact @2"
+ bob <## "alice: connection started"
+ alice <## "bob (Bob) wants to connect to you!"
+ alice <## "to accept: /ac bob"
+ alice <## "to reject: /rc bob (the sender will NOT be notified)"
+ alice ##> "/rc bob notify"
+ alice <## "bob: contact request rejected"
+ bob <## "alice: contact request rejected"
+ apiFixture "connect/request-rejected" bob [] FixtureRequests {frMarkdown = [""], frUris = [], frCommands = ["/_get chats 1 pcc=on"]}
+
testKeepConnectionRequests :: HasCallStack => TestParams -> IO ()
testKeepConnectionRequests = testChat3 aliceProfile bobProfile cathProfile $
\alice bob cath -> do
@@ -4268,6 +4311,133 @@ testShortLinkJoinGroup =
cc <## "#team: you joined the group"
]
+testGroupLinkAsType :: HasCallStack => T.Text -> String -> TestParams -> IO ()
+testGroupLinkAsType linkType fixture =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ link <- setLinkType "/g#" linkType <$> createGroupWithLink alice
+ bob ##> ("/_connect plan 1 " <> link)
+ invalidLink bob
+ apiFixture fixture bob [(link, "GROUP_LINK")] FixtureRequests {frMarkdown = [link], frUris = [], frCommands = ["/_connect plan 1 " <> link]}
+ bob ##> ("/c " <> link)
+ invalidLink bob
+
+testGroupLinkAsRelay :: HasCallStack => TestParams -> IO ()
+testGroupLinkAsRelay =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ link <- setLinkType "/g#" "/r#" <$> createGroupWithLink alice
+ bob ##> ("/relay test " <> link)
+ bob <## "relay test failed at RTSGetLink, error: ChatError {errorType = CEInvalidConnReq}"
+
+testRelayAddressLinkTypes :: HasCallStack => TestParams -> IO ()
+testRelayAddressLinkTypes ps =
+ withNewTestChat ps "alice" aliceProfile $ \alice ->
+ withNewTestChatOpts ps relayTestOpts "bob" bobProfile $ \bob ->
+ withNewTestChat ps "cath" cathProfile $ \cath -> do
+ bob ##> "/ad"
+ (relayAddress, _) <- getContactLinks bob True
+ cath ##> "/ad"
+ (address, _) <- getContactLinks cath True
+ alice ##> ("/relay test " <> setLinkType "/r#" "/a#" relayAddress)
+ alice <## "relay test passed, profile: bob (Bob)"
+ alice ##> ("/relay test " <> setLinkType "/a#" "/r#" address)
+ alice <##. "relay test failed at RTSDecodeLink, error: "
+
+testAddressAsGroupLink :: HasCallStack => TestParams -> IO ()
+testAddressAsGroupLink =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ alice ##> "/ad"
+ (address, _) <- getContactLinks alice True
+ forM_ ["/g#", "/c#"] $ \linkType -> do
+ let link = setLinkType "/a#" linkType address
+ bob ##> ("/_connect plan 1 " <> link)
+ invalidLink bob
+ bob ##> ("/c " <> link)
+ invalidLink bob
+
+testGroupLinkInContactProfile :: HasCallStack => TestParams -> IO ()
+testGroupLinkInContactProfile =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ link <- createGroupWithLink alice
+ void $ withCCUser bob $ \user -> withCCTransaction bob $ \db ->
+ runExceptT $ createContact db (storeCxt $ chatController bob) user aliceProfile {contactLink = either error Just $ strDecode $ B.pack link}
+ bob ##> "/_connect contact 1 2"
+ invalidLink bob
+
+testContactDataInGroupLink :: HasCallStack => TestParams -> IO ()
+testContactDataInGroupLink =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ link <- createGroupWithLink alice
+ setTestGroupLinkData alice $ encodeShortLinkData $ ContactShortLinkData aliceProfile Nothing False Nothing Nothing
+ bob ##> ("/_connect plan 1 " <> link)
+ invalidLink bob
+
+testChannelDataInInvitation :: HasCallStack => TestParams -> IO ()
+testChannelDataInInvitation =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ alice ##> "/_connect 1"
+ (link, _) <- getInvitations alice
+ setTestInvLinkData alice $ GroupShortLinkData testGroupProfile {publicGroup = Just channel} Nothing
+ bob ##> ("/_connect plan 1 " <> link)
+ invalidLink bob
+ where
+ channel = PublicGroupProfile GTChannel channelLink (B64UrlByteString "channel") Nothing
+ channelLink = either error id $ strDecode "https://localhost/c#Pz9qz7ZVljMofoRxiDDpL_w2DZSazK8IgafxqnWKv6Y"
+
+testLinksWithTheirData :: HasCallStack => TestParams -> IO ()
+testLinksWithTheirData =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ alice ##> "/_connect 1"
+ (invitation, _) <- getInvitations alice
+ setTestInvLinkData alice $ GroupShortLinkData testGroupProfile Nothing
+ bob ##> ("/_connect plan 1 " <> invitation)
+ bob <## "invitation link: ok to connect"
+ _ <- getTermLine bob
+ alice ##> "/ad"
+ (address, _) <- getContactLinks alice True
+ bob ##> ("/_connect plan 1 " <> address)
+ bob <## "contact address: ok to connect"
+ _ <- getTermLine bob
+ link <- createGroupWithLink alice
+ bob ##> ("/_connect plan 1 " <> link)
+ bob <## "group link: ok to connect directly"
+ _ <- getTermLine bob
+ setTestGroupLinkData alice $ UserLinkData ""
+ bob ##> ("/_connect plan 1 " <> link)
+ bob <## "group link: ok to connect directly"
+ void $ getTermLine bob
+
+testLinksWithoutData :: HasCallStack => TestParams -> IO ()
+testLinksWithoutData =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ alice ##> "/_connect 1"
+ (invitation, _) <- getInvitations alice
+ setTestInvLinkData alice J.Null
+ bob ##> ("/_connect plan 1 " <> invitation)
+ bob <## "invitation link: ok to connect"
+ _ <- getTermLine bob
+ link <- createGroupWithLink alice
+ setTestGroupLinkData alice $ UserLinkData ""
+ bob ##> ("/_connect plan 1 " <> setLinkType "/g#" "/c#" link)
+ invalidLink bob
+
+createGroupWithLink :: HasCallStack => TestCC -> IO String
+createGroupWithLink cc = do
+ cc ##> "/g team"
+ cc <## "group #team is created"
+ cc <## "to add members use /a team or /create link #team"
+ cc ##> "/create link #team"
+ fst <$> getGroupLinks cc "team" GRMember True
+
+setLinkType :: T.Text -> T.Text -> String -> String
+setLinkType from to = T.unpack . T.replace from to . T.pack
+
+invalidLink :: HasCallStack => TestCC -> IO ()
+invalidLink cc = do
+ cc <## ""
+ cc <## "Connection link is invalid, possibly it was created in a previous version."
+ cc <## "Please ask your contact to check /version and update if needed."
+ cc <##. "To update run: "
+
testShortLinkInvitationPrepareContact :: HasCallStack => TestParams -> IO ()
testShortLinkInvitationPrepareContact = testChat2 aliceProfile bobProfile test
where
diff --git a/tests/ChatTests/Utils.hs b/tests/ChatTests/Utils.hs
index 3769f41edd..63b6864dc1 100644
--- a/tests/ChatTests/Utils.hs
+++ b/tests/ChatTests/Utils.hs
@@ -1055,7 +1055,7 @@ stableJSON = \case
v -> v
where
stableField k v
- | k `elem` ["createdAt", "updatedAt", "chatTs", "userMemberProfileSentAt", "itemTs"] = J.String "1970-01-01T00:00:00Z"
- | k `elem` ["agentConnId", "xContactId", "connFullLink", "connShortLink", "contactLink", "groupLink", "viaGroupLinkUri", "simplexUri", "memberId", "memberPubKey", "publicGroupId", "businessId", "customerId", "itemSharedMsgId"] = J.String $ JK.toText k
+ | k `elem` ["createdAt", "updatedAt", "chatTs", "userMemberProfileSentAt", "itemTs", "deletedTs", "fileExpires"] = J.String "1970-01-01T00:00:00Z"
+ | k `elem` ["agentConnId", "xContactId", "connFullLink", "connShortLink", "contactLink", "groupLink", "viaGroupLinkUri", "simplexUri", "memberId", "memberPubKey", "publicGroupId", "businessId", "customerId", "itemSharedMsgId", "fileDescrText"] = J.String $ JK.toText k
| k == "groupRelays", J.Array a <- v = J.Array $ J.String "groupRelay" <$ a
| otherwise = stableJSON v
diff --git a/tests/fixtures/api/connect/group-link-as-address.json b/tests/fixtures/api/connect/group-link-as-address.json
new file mode 100644
index 0000000000..6eaf3e7abf
--- /dev/null
+++ b/tests/fixtures/api/connect/group-link-as-address.json
@@ -0,0 +1,30 @@
+{
+ "commands": {
+ "/_connect plan 1 GROUP_LINK": {
+ "error": {
+ "errorType": {
+ "type": "invalidConnReq"
+ },
+ "type": "error"
+ }
+ }
+ },
+ "markdown": {
+ "GROUP_LINK": {
+ "formattedText": [
+ {
+ "format": {
+ "linkType": "contact",
+ "simplexUri": "simplexUri",
+ "smpHosts": [
+ "localhost"
+ ],
+ "type": "simplexLink"
+ },
+ "text": "GROUP_LINK"
+ }
+ ]
+ }
+ },
+ "uris": {}
+}
diff --git a/tests/fixtures/api/connect/group-link-as-channel.json b/tests/fixtures/api/connect/group-link-as-channel.json
new file mode 100644
index 0000000000..c32c496b1c
--- /dev/null
+++ b/tests/fixtures/api/connect/group-link-as-channel.json
@@ -0,0 +1,30 @@
+{
+ "commands": {
+ "/_connect plan 1 GROUP_LINK": {
+ "error": {
+ "errorType": {
+ "type": "invalidConnReq"
+ },
+ "type": "error"
+ }
+ }
+ },
+ "markdown": {
+ "GROUP_LINK": {
+ "formattedText": [
+ {
+ "format": {
+ "linkType": "channel",
+ "simplexUri": "simplexUri",
+ "smpHosts": [
+ "localhost"
+ ],
+ "type": "simplexLink"
+ },
+ "text": "GROUP_LINK"
+ }
+ ]
+ }
+ },
+ "uris": {}
+}
diff --git a/tests/fixtures/api/connect/request-rejected.json b/tests/fixtures/api/connect/request-rejected.json
new file mode 100644
index 0000000000..84e749426a
--- /dev/null
+++ b/tests/fixtures/api/connect/request-rejected.json
@@ -0,0 +1,318 @@
+{
+ "commands": {
+ "/_get chats 1 pcc=on": {
+ "result": {
+ "chats": [
+ {
+ "chatInfo": {
+ "contact": {
+ "activeConn": {
+ "agentConnId": "agentConnId",
+ "authErrCounter": 0,
+ "connChatVersion": 9,
+ "connId": 1,
+ "connLevel": 0,
+ "connStatus": {
+ "type": "joined"
+ },
+ "connType": "contact",
+ "contactConnInitiated": true,
+ "createdAt": "1970-01-01T00:00:00Z",
+ "entityId": 2,
+ "localAlias": "",
+ "peerChatVRange": {
+ "maxVersion": 1,
+ "minVersion": 1
+ },
+ "pqEncryption": true,
+ "pqSupport": true,
+ "quotaErrCounter": 0,
+ "viaGroupLink": false,
+ "xContactId": "xContactId"
+ },
+ "chatDeleted": false,
+ "chatSettings": {
+ "enableNtfs": "all",
+ "favorite": false
+ },
+ "chatTags": [],
+ "chatTs": "1970-01-01T00:00:00Z",
+ "contactGrpInvSent": false,
+ "contactId": 2,
+ "contactStatus": "rejected",
+ "contactUsed": true,
+ "createdAt": "1970-01-01T00:00:00Z",
+ "localDisplayName": "alice",
+ "mergedPreferences": {
+ "calls": {
+ "contactPreference": {
+ "allow": "yes"
+ },
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "yes"
+ },
+ "type": "user"
+ }
+ },
+ "commands": [],
+ "files": {
+ "contactPreference": {
+ "allow": "always"
+ },
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "always"
+ },
+ "type": "user"
+ }
+ },
+ "fullDelete": {
+ "contactPreference": {
+ "allow": "no"
+ },
+ "enabled": {
+ "forContact": false,
+ "forUser": false
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "no"
+ },
+ "type": "user"
+ }
+ },
+ "reactions": {
+ "contactPreference": {
+ "allow": "yes"
+ },
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "yes"
+ },
+ "type": "user"
+ }
+ },
+ "sessions": {
+ "contactPreference": {
+ "allow": "no"
+ },
+ "enabled": {
+ "forContact": false,
+ "forUser": false
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "no"
+ },
+ "type": "user"
+ }
+ },
+ "timedMessages": {
+ "contactPreference": {
+ "allow": "yes"
+ },
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "yes"
+ },
+ "type": "user"
+ }
+ },
+ "voice": {
+ "contactPreference": {
+ "allow": "yes"
+ },
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "userPreference": {
+ "preference": {
+ "allow": "yes"
+ },
+ "type": "user"
+ }
+ }
+ },
+ "preparedContact": {
+ "connLinkToConnect": {
+ "connFullLink": "connFullLink",
+ "connShortLink": "connShortLink"
+ },
+ "uiConnLinkType": "con"
+ },
+ "profile": {
+ "displayName": "alice",
+ "fullName": "",
+ "localAlias": "",
+ "preferences": {
+ "calls": {
+ "allow": "yes"
+ },
+ "commands": [],
+ "files": {
+ "allow": "always"
+ },
+ "fullDelete": {
+ "allow": "no"
+ },
+ "reactions": {
+ "allow": "yes"
+ },
+ "sessions": {
+ "allow": "no"
+ },
+ "timedMessages": {
+ "allow": "yes"
+ },
+ "voice": {
+ "allow": "yes"
+ }
+ },
+ "profileId": 2,
+ "shortDescr": "Alice"
+ },
+ "updatedAt": "1970-01-01T00:00:00Z",
+ "userPreferences": {}
+ },
+ "type": "direct"
+ },
+ "chatItems": [
+ {
+ "chatDir": {
+ "type": "directRcv"
+ },
+ "content": {
+ "enabled": {
+ "forContact": true,
+ "forUser": true
+ },
+ "feature": "calls",
+ "type": "rcvChatFeature"
+ },
+ "mentions": {},
+ "meta": {
+ "createdAt": "1970-01-01T00:00:00Z",
+ "deletable": false,
+ "editable": false,
+ "hasLink": false,
+ "itemEdited": false,
+ "itemId": 7,
+ "itemStatus": {
+ "type": "rcvRead"
+ },
+ "itemText": "Audio/video calls: enabled",
+ "itemTs": "1970-01-01T00:00:00Z",
+ "showGroupAsSender": false,
+ "updatedAt": "1970-01-01T00:00:00Z",
+ "userMention": false
+ },
+ "reactions": []
+ }
+ ],
+ "chatStats": {
+ "minUnreadItemId": 0,
+ "reportsCount": 0,
+ "unreadChat": false,
+ "unreadCount": 0,
+ "unreadMentions": 0
+ }
+ }
+ ],
+ "type": "apiChats",
+ "user": {
+ "activeOrder": 1,
+ "activeUser": true,
+ "agentUserId": "1",
+ "autoAcceptGroupInvitations": false,
+ "autoAcceptMemberContacts": false,
+ "clientService": false,
+ "fullPreferences": {
+ "calls": {
+ "allow": "yes"
+ },
+ "commands": [],
+ "files": {
+ "allow": "always"
+ },
+ "fullDelete": {
+ "allow": "no"
+ },
+ "reactions": {
+ "allow": "yes"
+ },
+ "sessions": {
+ "allow": "no"
+ },
+ "timedMessages": {
+ "allow": "yes"
+ },
+ "voice": {
+ "allow": "yes"
+ }
+ },
+ "localDisplayName": "bob",
+ "profile": {
+ "displayName": "bob",
+ "fullName": "",
+ "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAKHGlDQ1BJQ0MgUHJvZmlsZQAASImFVgdUVNcWve9Nb7QZeu9NehtAem/Sq6gMQ28OQxWxgAQjEFFEREARNFQFg1KjiIhiIQgoYA9IEFBisCAq6OQNJNH4//r/zDpz9ttzz7n73ffWmg0A6QCDxYqD+QCIT0hmezlYywQEBsngngEYCAIy0AC6DGYSy8rDwxUg8Xf9d7wbAxC33tHgzvrP3/9nCISFJzEBgIIRTGey2MkILkawT1oyi4tnEUxjI6IQvMLFkauYqxjQQtewwuoaHy8bBNMBwJMZDHYkAERbhJdJZUYic4hhCNZOCItOQDB3vjkzioFwxLsIXhcRl5IOAImrRzs+fivCk7QRrIL0shAcwNUW+tX8yH/tFfrPXgxG5D84Pi6F+dc9ck+HHJ7g641UMSQlQATQBHEgBaQDGcACbLAVYaIRJhx5Dv+9j77aZ4OsZIFtSEc0iARRIBnpt/9qlvfqpGSQBhjImnCEcUU+NtxnujZy4fbqVEiU/wuXdQyA9S0cDqfzC+e2F4DzyLkSB79wyi0A8KoBcL2GmcJOXePQ3C8MIAJeQAOiQArIAxXuWwMMgSmwBHbAGbgDHxAINgMmojceUZUGMkEWyAX54AA4D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YzCPop7dwJ3zRfJ7GDuso4YJGRa0yZgg4tUaNXdGrbuZWKKxzYYEJc2xp9AUUjGt8KC2jvgYadF8+10vJyDnNLXwbdiWUZi0fUK01Eoc+AZhCLZVzK4Vq6sDUdz+0dEcbbTTIOJmAyTVhx/WmvrExbv2jtPhWLKodjCtefZiEeZeVZWWSndgwj6fVf3XON8Qwq15++uoqrfYVrow6dGBpCq79ME291jaB0/Q2CPncyht/99MNO/vr9AqW/CGi8sJqbAAAAAElFTkSuQmCC",
+ "localAlias": "",
+ "preferences": {
+ "calls": {
+ "allow": "yes"
+ },
+ "commands": [],
+ "files": {
+ "allow": "always"
+ },
+ "fullDelete": {
+ "allow": "no"
+ },
+ "reactions": {
+ "allow": "yes"
+ },
+ "sessions": {
+ "allow": "no"
+ },
+ "timedMessages": {
+ "allow": "yes"
+ },
+ "voice": {
+ "allow": "yes"
+ }
+ },
+ "profileId": 1,
+ "shortDescr": "Bob"
+ },
+ "sendRcptsContacts": true,
+ "sendRcptsSmallGroups": true,
+ "showNtfs": true,
+ "userChatRelay": false,
+ "userContactId": 1,
+ "userId": 1
+ }
+ }
+ }
+ },
+ "markdown": {
+ "": {}
+ },
+ "uris": {}
+}
From e283e5f3d4e50929029d573dd7ff2b6388f2ffa0 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 07:31:55 +0000
Subject: [PATCH 02/20] libs: nodejs 7.1.4 (#8263)
* nodejs: live test reads the updated item under the key of 7.1 and 7.2 cores
* libs: nodejs 7.1.4
---
packages/simplex-chat-nodejs/package.json | 2 +-
packages/simplex-chat-nodejs/src/release.ts | 14 +++++++-------
packages/simplex-chat-nodejs/tests/live.test.ts | 9 +++++++--
3 files changed, 15 insertions(+), 10 deletions(-)
diff --git a/packages/simplex-chat-nodejs/package.json b/packages/simplex-chat-nodejs/package.json
index c7430c247a..25222fbfcd 100644
--- a/packages/simplex-chat-nodejs/package.json
+++ b/packages/simplex-chat-nodejs/package.json
@@ -1,6 +1,6 @@
{
"name": "simplex-chat",
- "version": "7.1.3",
+ "version": "7.1.4",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"gypfile": false,
diff --git a/packages/simplex-chat-nodejs/src/release.ts b/packages/simplex-chat-nodejs/src/release.ts
index 7587633550..a9dd64788a 100644
--- a/packages/simplex-chat-nodejs/src/release.ts
+++ b/packages/simplex-chat-nodejs/src/release.ts
@@ -1,16 +1,16 @@
// Written by scripts/ci/packages_release.py from the simplex-chat-libs releases.
-export const LIBS_RELEASE = "core-7.1.3.0"
+export const LIBS_RELEASE = "core-7.1.4.0"
export const ADDON_RELEASE: string | undefined = "nodejs-addon-cce06d8"
export const SHA256: {readonly [asset: string]: string} = {
- "simplex-chat-libs-linux-aarch64.zip": "46e296417de8cddc0d6f800d7c634dec410a1af20ea38ff31f224ef388aaeb00",
- "simplex-chat-libs-linux-x86_64-postgres.zip": "ea89b4e95836c79c887cc13a2dc9fc66e319b21ee4148ca38817539657601050",
- "simplex-chat-libs-linux-x86_64.zip": "12b6ea97c64a5ea53a66f47e827dc8c0d6bc767fd44b22aab47786ac90e91d01",
- "simplex-chat-libs-macos-aarch64.zip": "b7612b05cd17267f4e24efacfd16fa4a9f9b0c39b34c2f52465e34395492a452",
- "simplex-chat-libs-macos-x86_64.zip": "ce7a9a2be0cd0e6782902d8ce4420e8660e4e2360d7fc0248584a0163f1a236d",
- "simplex-chat-libs-windows-x86_64.zip": "a9ed55c82753d57cfddaddee78cc989b0edf3fe5fe08d7214e6f84ab43609999",
+ "simplex-chat-libs-linux-aarch64.zip": "5ab4be63353e49b0d24b70b154745d2e45c288903e0c17078b8f957e3633ca6b",
+ "simplex-chat-libs-linux-x86_64-postgres.zip": "77cf1e2c9a75b723ce18abc5c02873dbe08d37dca069a0d815dca3095143439a",
+ "simplex-chat-libs-linux-x86_64.zip": "d4888149b29fd9d4ca690d2a8f3763dde477b77fe1ea6927d5990137bceeab6b",
+ "simplex-chat-libs-macos-aarch64.zip": "32450fef49e2e38db33783fe0761f4af16463a5cd7a204f8c41875909db60b56",
+ "simplex-chat-libs-macos-x86_64.zip": "3ab5efc5bbc5b8ddfa6a24a4d79e318fff3df0dd4c3334c5cd9acb1b0288101c",
+ "simplex-chat-libs-windows-x86_64.zip": "c88e185442cb738d53d2dc2d5408c4cb9efedaa910c677ec10e8dd74c12b0223",
"simplex-chat-nodejs-linux-aarch64.node": "de09cf5653772370fbd1ab2b046a9a2b68f3d2a078103befb2d4eb3e11748ebb",
"simplex-chat-nodejs-linux-x86_64.node": "fda77e39a5d38b1132a6a04ef9f9cd2c939a429e709f28c81c3777684ba73603",
"simplex-chat-nodejs-macos-aarch64.node": "3da7ae0064c151a0508d3f0a208a9af5647a8113df8d9164f76c786a882d68df",
diff --git a/packages/simplex-chat-nodejs/tests/live.test.ts b/packages/simplex-chat-nodejs/tests/live.test.ts
index 526e230c51..beb80fa445 100644
--- a/packages/simplex-chat-nodejs/tests/live.test.ts
+++ b/packages/simplex-chat-nodejs/tests/live.test.ts
@@ -39,8 +39,13 @@ describeIfSmpServerAvailable("Live message tests (use local SMP server)", () =>
const timeout = 10000
const received = (check: (meta: T.CIMeta) => boolean) =>
bob.wait("newChatItems", ({chatItems}) => chatItems.some(({chatItem: {meta}}) => check(meta)), timeout)
+ const updatedItem = (event: {chatItemUpdate?: {chatItem: T.ChatItem}; chatItem?: {chatItem: T.ChatItem}}) =>
+ (event.chatItemUpdate ?? event.chatItem)?.chatItem
const updated = (check: (meta: T.CIMeta) => boolean) =>
- bob.wait("chatItemUpdated", ({chatItemUpdate: {chatItem: {meta}}}) => check(meta), timeout)
+ bob.wait("chatItemUpdated", event => {
+ const item = updatedItem(event)
+ return item !== undefined && check(item.meta)
+ }, timeout)
const live = new api.LiveMessage(alice, CT.Direct, bobContact.contactId, 500)
const started = received(meta => meta.itemLive === true && meta.itemText === "")
@@ -52,7 +57,7 @@ describeIfSmpServerAvailable("Live message tests (use local SMP server)", () =>
expect(await updatedLive).toBeDefined()
const finalized = updated(meta => meta.itemId === itemId && meta.itemLive === false && meta.itemText === "Hello world")
await live.end("Hello world")
- expect((await finalized)?.chatItemUpdate.chatItem.meta.itemEdited).toBe(false)
+ expect(updatedItem((await finalized)!)?.meta.itemEdited).toBe(false)
const emptyStarted = received(meta => meta.itemLive === true && meta.itemText === "")
live.update("")
From b5ee352c8f25352b078ac08831a3e184f0d3d9f3 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 13:55:59 +0000
Subject: [PATCH 03/20] mcp: session states coloured by what they need, green
for working (#8265)
* mcp: session states in the colours of what they need: green working, orange waiting in the chat, red idle
* mcp: the space after waiting for you in the tests
* mcp: a session with a background command shows working in the background
---
packages/simplex-chat-mcp/REFERENCE.md | 20 +++++++------
packages/simplex-chat-mcp/TESTING.md | 2 +-
packages/simplex-chat-mcp/spec/api.md | 9 +++---
packages/simplex-chat-mcp/spec/flows.md | 6 ++--
packages/simplex-chat-mcp/src/hub.ts | 10 +++----
.../simplex-chat-mcp/test/e2e/service.test.ts | 6 ++--
.../test/unit/sessions.test.ts | 28 +++++++++----------
7 files changed, 42 insertions(+), 39 deletions(-)
diff --git a/packages/simplex-chat-mcp/REFERENCE.md b/packages/simplex-chat-mcp/REFERENCE.md
index 2a2dc02fbe..557b0092be 100644
--- a/packages/simplex-chat-mcp/REFERENCE.md
+++ b/packages/simplex-chat-mcp/REFERENCE.md
@@ -576,18 +576,20 @@ Only you see this link: it never enters Claude's context or tool results. Scan t
After the first owner joins, Claude posts the list of sessions in the Main group, after its greeting:
```
-🟠 3 · simplex-chat: working
-🔵 6 · website: waiting for you, 2 approvals
-🔵 7 · docs: waiting for you in Claude Code
-🟢 8 · app: idle
+🟢 3 · simplex-chat: working
+🟠 6 · website: waiting for you, 2 approvals
+⛔️ 7 · docs: waiting for you in Claude Code
+🔴 8 · app: idle
+⚙️ 9 · api: working in the background
⚪ Not running: 5 · bio, 4 · notes, 2 · openclaw, 1 · first
```
-- A session is running while its Claude Code runs, or while cards wait for a decision in its group. Each running session has a line, by number:
- - `🔵 N · NAME: waiting for you, K approvals`: K cards wait in the session's group. A tool-use card counts only while Claude Code shows its permission dialog, or while Claude Code's state can't be read.
- - `🔵 N · NAME: waiting for you in Claude Code`: Claude Code waits for an answer in its own window, such as a dialog.
- - `🟠 N · NAME: working`: Claude Code works on a turn, or a subagent works for it.
- - `🟢 N · NAME: idle`: Claude Code waits for the next prompt, also while a background command runs.
+- A session is running while its Claude Code runs, or while cards wait for a decision in its group. Each running session has a line, by number. Green is the state to keep:
+ - `🟢 N · NAME: working`: Claude Code works on a turn, or a subagent works for it.
+ - `🟠 N · NAME: waiting for you, K approvals`: K cards wait in the session's group, for a decision in the chat. A tool-use card counts only while Claude Code shows its permission dialog, or while Claude Code's state can't be read.
+ - `⛔️ N · NAME: waiting for you in Claude Code`: Claude Code waits for an answer in its own window, such as a dialog, which the chat can't give.
+ - `⚙️ N · NAME: working in the background`: Claude Code waits for the next prompt while a background command runs. The command's end starts a turn without a prompt.
+ - `🔴 N · NAME: idle`: Claude Code waits for the next prompt, and nothing runs.
- `▶️ N · NAME: running`: Claude Code's state can't be read.
- The last line names every other session of the data folder, newest first. Without any session, the list is `No sessions.`
- The states are Claude Code's own: the plugin reads them from Claude Code's record of its process, `sessions/PID.json` in `CLAUDE_CONFIG_DIR` or `~/.claude`.
diff --git a/packages/simplex-chat-mcp/TESTING.md b/packages/simplex-chat-mcp/TESTING.md
index b0b48d50f1..4c76c9b070 100644
--- a/packages/simplex-chat-mcp/TESTING.md
+++ b/packages/simplex-chat-mcp/TESTING.md
@@ -245,7 +245,7 @@ In a session started as in step 2 above:
- The plugin's folder had no `node_modules/.package-lock.json`.
- With the same keys in `.claude/settings.json` of the folder, and without `--settings`, the run had no tool of the plugin.
19. Start Claude Code as in step 2 with an empty data folder and a machine name: `SIMPLEX_MCP_HOME=/tmp/simplex-mcp-fresh SIMPLEX_MCP_MACHINE=laptop claude --plugin-dir /tmp/simplex-plugin --dangerously-load-development-channels plugin:simplex@inline`. Exit it before the QR code shows. Start it again the same way. The QR code shows within seconds, for the group "Claude Control - laptop". Stop that service: `kill $(cat /tmp/simplex-mcp-fresh/service.lock)`.
-20. With the session of step 2 running and a second session started as in step 2 in another folder, the Main group shows the list of sessions, one line for each. Ask Claude to run `sleep 20` with Bash: its line shows 🟠 working. Send `Run ls with Bash.` in its group: the line shows 🔵 waiting for you, 1 approval; tap `/approve N`, and it shows 🟠 working, then 🟢 idle when the turn ends. Press Esc during a turn: the line shows 🟢 idle within 2 seconds, although Claude Code runs no Stop hook. Ask Claude to ask you a question with AskUserQuestion: the line shows 🔵 waiting for you in Claude Code. Exit the second Claude Code: its session moves into the last line, `⚪ Not running: `. `/sessions` replies with the same text.
+20. With the session of step 2 running and a second session started as in step 2 in another folder, the Main group shows the list of sessions, one line for each. Ask Claude to run `sleep 20` with Bash: its line shows 🟢 working. Send `Run ls with Bash.` in its group: the line shows 🟠 waiting for you, 1 approval; tap `/approve N`, and it shows 🟢 working, then 🔴 idle when the turn ends. Press Esc during a turn: the line shows 🔴 idle within 2 seconds, although Claude Code runs no Stop hook. Ask Claude to run `sleep 60` with Bash in the background: after its turn ends, the line shows ⚙️ working in the background until the command ends. Ask Claude to ask you a question with AskUserQuestion: the line shows ⛔️ waiting for you in Claude Code. Exit the second Claude Code: its session moves into the last line, `⚪ Not running: `. `/sessions` replies with the same text.
21. Send `Read README.md, say what you are doing before each step, and then summarize it in 30 lines.` in the group. An empty message from Claude appears at once, as a reply to your message, with typing dots. Claude's first remark or step fills it, and each later remark and the answer appear from their first line, growing by whole lines, at most every 3 seconds. The steps' lines appear between them. Each message ends without an edited mark. The answer's message ends with `Done in`, the turn's time and tokens in small print, and the chat list shows the answer. In the terminal, Claude's text appears by whole lines.
22. Send `Name a fruit.` in the group, and after the answer edit that message to `Name a vegetable.` Claude answers with a vegetable, as a reply to your message. In the transcript, the second tag has the same `item` as the first and `edited="true"`. Edit it into `/list`, and nothing happens. Turn on live mode in the app, type `Name a colour.` slowly, and send it. Claude answers once, after you send it, and the transcript has one tag with `Name a colour.`
23. Stop the service: `kill $(cat /tmp/simplex-mcp-test/service.lock)`.
diff --git a/packages/simplex-chat-mcp/spec/api.md b/packages/simplex-chat-mcp/spec/api.md
index 30c8a667c0..1833f4fa72 100644
--- a/packages/simplex-chat-mcp/spec/api.md
+++ b/packages/simplex-chat-mcp/spec/api.md
@@ -735,10 +735,11 @@ Posts:
| Part | Text | Condition |
|---|---|---|
-| a running session | `🔵 N · NAME: waiting for you, K approvals`, `1 approval` for one | K pending cards of the session, without those cancelled by a stop. A tool-use card counts while Claude Code's state is `waiting` or unknown |
-| | `🔵 N · NAME: waiting for you in Claude Code` | no card; attached; state `waiting` |
-| | `🟠 N · NAME: working` | no card; attached; state `busy` |
-| | `🟢 N · NAME: idle` | no card; attached; state `idle` or `shell` |
+| a running session | `🟠 N · NAME: waiting for you, K approvals`, `1 approval` for one | K pending cards of the session, without those cancelled by a stop. A tool-use card counts while Claude Code's state is `waiting` or unknown |
+| | `⛔️ N · NAME: waiting for you in Claude Code` | no card; attached; state `waiting` |
+| | `🟢 N · NAME: working` | no card; attached; state `busy` |
+| | `🔴 N · NAME: idle` | no card; attached; state `idle` |
+| | `⚙️ N · NAME: working in the background` | no card; attached; state `shell` |
| | `▶️ N · NAME: running` | no card; attached; no record path, no record file, or another state |
| the other sessions | `⚪ Not running: N · NAME, N · NAME, K older sessions`, newest first | sessions without a card and without an attachment, or all of them while the service stops |
| no session | `No sessions.` | |
diff --git a/packages/simplex-chat-mcp/spec/flows.md b/packages/simplex-chat-mcp/spec/flows.md
index afbd40e68b..8c9a968aea 100644
--- a/packages/simplex-chat-mcp/spec/flows.md
+++ b/packages/simplex-chat-mcp/spec/flows.md
@@ -1691,18 +1691,18 @@ sequenceDiagram
CC->>R: status busy
D->>N: every 2 s: readRecord, the session attached
N->>R: read status
- D->>M: showList: 🟠 N · NAME: working, then the not running line
+ D->>M: showList: 🟢 N · NAME: working, then the not running line
M->>C: no list yet, an owner in the group: apiSendMessages #35;M, priority -1
M->>C: apiSetGroupCustomData #35;M {simplexMcpMain: true, simplexMcpList: {item, at}}
C->>O: the list
CC->>R: status waiting, a permission dialog
CC->>S: permission_request
S->>D: POST /permission
- D->>M: showList: 🔵 N · NAME: waiting for you, 1 approval
+ D->>M: showList: 🟠 N · NAME: waiting for you, 1 approval
M->>C: apiUpdateChatItem #35;M item
C->>O: the list edited, no alert
CC->>R: status idle
- D->>M: showList: 🟢 N · NAME: idle
+ D->>M: showList: 🔴 N · NAME: idle
M->>C: apiUpdateChatItem #35;M item
Note over D,M: the list 23 hours old, or its edit refused
M->>C: apiSendMessages #35;M the new list, priority -1, and its item saved
diff --git a/packages/simplex-chat-mcp/src/hub.ts b/packages/simplex-chat-mcp/src/hub.ts
index a072a80077..bb2f806f5a 100644
--- a/packages/simplex-chat-mcp/src/hub.ts
+++ b/packages/simplex-chat-mcp/src/hub.ts
@@ -65,10 +65,10 @@ const listCheckMs = 2_000
const recordReadMs = 1_000
// spec: spec/api.md#list-of-sessions
const claudeStates = new Map([
- ["waiting", ["🔵", "waiting for you in Claude Code"]],
- ["busy", ["🟠", "working"]],
- ["idle", ["🟢", "idle"]],
- ["shell", ["🟢", "idle"]],
+ ["waiting", ["⛔️", "waiting for you in Claude Code"]],
+ ["busy", ["🟢", "working"]],
+ ["idle", ["🔴", "idle"]],
+ ["shell", ["⚙️", "working in the background"]],
])
// spec: spec/api.md#list-of-sessions
const unknownState: [string, string] = ["▶️", "running"]
@@ -263,7 +263,7 @@ export class Session {
const state = claudeStates.get(this.claudeStatus ?? "")
const dialog = state === undefined || this.claudeStatus === "waiting"
const cards = this.actions.pending().filter(({tool, interrupted}) => !interrupted && (dialog || tool !== "permission")).length
- if (cards > 0) return `🔵 ${this.displayName}: waiting for you, ${cards} approval${cards === 1 ? "" : "s"}`
+ if (cards > 0) return `🟠 ${this.displayName}: waiting for you, ${cards} approval${cards === 1 ? "" : "s"}`
if (!this.attached) return undefined
const [emoji, text] = state ?? unknownState
return `${emoji} ${this.displayName}: ${text}`
diff --git a/packages/simplex-chat-mcp/test/e2e/service.test.ts b/packages/simplex-chat-mcp/test/e2e/service.test.ts
index d2df3ee19d..f31e885c2e 100644
--- a/packages/simplex-chat-mcp/test/e2e/service.test.ts
+++ b/packages/simplex-chat-mcp/test/e2e/service.test.ts
@@ -255,17 +255,17 @@ test("the Main group shows every session in one list, the running ones with thei
await until(() => attached.length === 1)
const owner = await client.request("GET", "/link")
const invitations = joinSessionGroups(alice, ["1 · one", "2 · two"])
- const working = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "🟠 1 · one: working\n⚪ Not running: 2 · two")
+ const working = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "🟢 1 · one: working\n⚪ Not running: 2 · two")
const mainGroupId = await joinByLink(alice, owner.link!)
const list = await working
expect(list.chatInfo).toMatchObject({type: "group", groupInfo: {groupId: mainGroupId}})
await invitations
const edited = (text: string): Promise => updated(alice.chat, inGroup(mainGroupId, ({chatItem}) => chatItem.meta.itemId === list.chatItem.meta.itemId && chatItem.meta.itemText === text))
- const waiting = edited("🔵 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
+ const waiting = edited("🟠 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
writeFileSync(record, JSON.stringify({status: "waiting", waitingFor: "permission prompt"}))
await client.request("POST", "/permission", {id: one, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
await waiting
- const idle = edited("🟢 1 · one: idle\n⚪ Not running: 2 · two")
+ const idle = edited("🔴 1 · one: idle\n⚪ Not running: 2 · two")
writeFileSync(record, JSON.stringify({status: "idle"}))
await idle
const ended = edited("⚪ Not running: 2 · two, 1 · one")
diff --git a/packages/simplex-chat-mcp/test/unit/sessions.test.ts b/packages/simplex-chat-mcp/test/unit/sessions.test.ts
index 6bc9e62fc2..61be401878 100644
--- a/packages/simplex-chat-mcp/test/unit/sessions.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/sessions.test.ts
@@ -2606,7 +2606,7 @@ describe("Main group", () => {
expect(chat.invitations.at(-1)).toEqual({groupId: 21, viaGroupId: 10, groupMemberId: 3, memberRole: T.GroupMemberRole.Owner})
})
- it("posts the list of every session after the greeting, silent, and edits it as Claude Code's records and the cards change: working, waiting for you, waiting for you in Claude Code, idle, and the ⚪ line after an exit", async () => {
+ it("posts the list of every session after the greeting, silent, and edits it as Claude Code's records and the cards change: working, waiting for you, waiting for you in Claude Code, idle, working in the background, and the ⚪ line after an exit", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat, [self])
const one = await openSession(hub, id1, stored(1, "one"))
@@ -2631,15 +2631,15 @@ describe("Main group", () => {
await hub.showSessions()
return chat.updates.length === edits ? undefined : chat.updates.at(-1)!.text
}
- expect(await shows("busy")).toBe("🟠 1 · one: working\n⚪ Not running: 2 · two")
+ expect(await shows("busy")).toBe("🟢 1 · one: working\n⚪ Not running: 2 · two")
expect(chat.updates.at(-1)).toMatchObject({chatId: 10, itemId: list})
expect(await shows("busy")).toBeUndefined()
- expect(await shows("waiting")).toBe("🔵 1 · one: waiting for you in Claude Code\n⚪ Not running: 2 · two")
+ expect(await shows("waiting")).toBe("⛔️ 1 · one: waiting for you in Claude Code\n⚪ Not running: 2 · two")
one.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
- expect(await shows("waiting")).toBe("🔵 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
- expect(await shows("busy")).toBe("🟠 1 · one: working\n⚪ Not running: 2 · two")
- expect(await shows("idle")).toBe("🟢 1 · one: idle\n⚪ Not running: 2 · two")
- expect(await shows("shell")).toBeUndefined()
+ expect(await shows("waiting")).toBe("🟠 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
+ expect(await shows("busy")).toBe("🟢 1 · one: working\n⚪ Not running: 2 · two")
+ expect(await shows("idle")).toBe("🔴 1 · one: idle\n⚪ Not running: 2 · two")
+ expect(await shows("shell")).toBe("⚙️ 1 · one: working in the background\n⚪ Not running: 2 · two")
one.endPermissions()
one.onLine = undefined
expect(await shows("idle")).toBe("⚪ Not running: 2 · two, 1 · one")
@@ -2656,18 +2656,18 @@ describe("Main group", () => {
one.onLine = () => undefined
one.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
two.requestMode("host")
- expect(hub.sessionsText()).toBe("🔵 1 · one: waiting for you, 1 approval\n🔵 2 · two: waiting for you, 1 approval")
+ expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 1 approval\n🟠 2 · two: waiting for you, 1 approval")
one.record = join(root, "claude-1.json")
writeFileSync(one.record, JSON.stringify({status: "busy"}))
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🟠 1 · one: working\n🔵 2 · two: waiting for you, 1 approval")
+ expect(hub.sessionsText()).toBe("🟢 1 · one: working\n🟠 2 · two: waiting for you, 1 approval")
writeFileSync(one.record, JSON.stringify({status: "compacting"}))
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🔵 1 · one: waiting for you, 1 approval\n🔵 2 · two: waiting for you, 1 approval")
+ expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 1 approval\n🟠 2 · two: waiting for you, 1 approval")
one.permission({id: id1, requestId: "fghij", toolName: "Write", description: "Write a file", inputPreview: "a.txt"})
writeFileSync(one.record, JSON.stringify({status: "waiting"}))
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🔵 1 · one: waiting for you, 2 approvals\n🔵 2 · two: waiting for you, 1 approval")
+ expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 2 approvals\n🟠 2 · two: waiting for you, 1 approval")
let stopped = false
const stopping = hub.stop().then(() => (stopped = true))
await until(() => chat.updates.filter(({chatId}) => chatId === 10).at(-1)?.text === "⚪ Not running: 2 · two, 1 · one")
@@ -2688,10 +2688,10 @@ describe("Main group", () => {
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
writeFileSync(one.record, JSON.stringify({status: "busy"}))
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🟠 1 · one: working")
+ expect(hub.sessionsText()).toBe("🟢 1 · one: working")
writeFileSync(one.record, '{"pid": 100, "sta')
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🟠 1 · one: working")
+ expect(hub.sessionsText()).toBe("🟢 1 · one: working")
writeFileSync(one.record, JSON.stringify({status: "compacting"}))
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
@@ -2720,7 +2720,7 @@ describe("Main group", () => {
await hub.showSessions()
expect(Date.now() - started).toBeLessThan(3_000)
expect(opened).toHaveBeenCalledTimes(1)
- expect(hub.sessionsText()).toBe("🟠 1 · one: working")
+ expect(hub.sessionsText()).toBe("🟢 1 · one: working")
})
it("deletes a new list whose item it could not save and posts it again at the next render, and does not send a text the core refused as too large again until the text changes", async () => {
From d9830bfa910ebd23bf4430652bd5542024f40bf9 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 14:04:46 +0000
Subject: [PATCH 04/20] mcp: a readable README, and the roadmap lines of 0.3.0
(#8264)
* mcp: readme by what the plugin does for its users, roadmap lines of 0.3.0
* mcp: almost every waiting state
* mcp: reply, edit and react in one line
* mcp: flat layout without the avatar note
* mcp: sessions use flat layout
* mcp: shorter lines on answers, the Main group and approvals
* mcp: approvals line without the taps
* mcp: live stream line
* mcp: status line
* mcp: shorter lines
---
packages/simplex-chat-mcp/README.md | 55 ++++++++++++++++------------
packages/simplex-chat-mcp/ROADMAP.md | 14 ++++---
2 files changed, 41 insertions(+), 28 deletions(-)
diff --git a/packages/simplex-chat-mcp/README.md b/packages/simplex-chat-mcp/README.md
index c855ef5a74..65864c32c9 100644
--- a/packages/simplex-chat-mcp/README.md
+++ b/packages/simplex-chat-mcp/README.md
@@ -10,7 +10,32 @@ With this package, Claude Code can join channels and groups, talk to bots, and e
-## Run Claude Code from the app
+🏗️ marks what is on the [roadmap](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/ROADMAP.md).
+
+## Use your agents in private chats, with the full chat UX
+
+- No phone number, email or account. Agents have their own profile, without access to your other chats.
+- Send prompts with images and files, and see answers live. Terminal prompts sent to the chat too.
+- Reply and edit messages, send reactions.
+- Sessions use flat layout.
+- 🏗️ Voice messages, code highlighting, widgets, etc.
+
+## Work with others in the same session
+
+- Invite people to the Main group, and they join any session's group.
+- Only owners and admins can approve tool calls.
+- The Main group shows every session's state.
+- 🏗️ Each session as a topic in one group.
+- 🏗️ Agent teams: mention an agent to message it.
+
+## Control your agents' activity
+
+- Agents ask before they act in other chats or use a tool such as Bash.
+- A live stream of agent's work: tasks, tool calls, etc.
+- Session and machine status.
+- 🏗️ Code diffs, almost every waiting state answered from the chat, etc.
+
+## Start
You need Node.js 22 or later, Claude Code, and the [SimpleX Chat app](https://simplex.chat/downloads/) 7.1 or later.
@@ -27,41 +52,25 @@ You need Node.js 22 or later, Claude Code, and the [SimpleX Chat app](https://si
claude --dangerously-load-development-channels plugin:simplex@simplex-chat
```
- If you don't want to run SimpleX MCP as a channel, start `claude` without the flag to use it as an MCP server. [Read more](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/REFERENCE.md#install).
+ Scan the QR code with the SimpleX app and tap Join: the Main group "Claude Control" appears. The first start downloads the SimpleX core library, so the QR code can take a minute.
- Scan the QR code with the SimpleX app and tap Join. The group "Claude Control" appears. At the first start the plugin downloads the SimpleX core library, so the QR code can take a minute. If you close Claude Code before then, the next start shows it.
+3. Each Claude Code session gets its own group, such as "1 · my-project". Join it from the invitation in "Claude Control", and send prompts there.
- On several machines or containers, set `SIMPLEX_MCP_MACHINE` on each, for example `SIMPLEX_MCP_MACHINE=laptop`, to name its group "Claude Control - laptop".
-
-3. Each Claude Code session gets its own group, such as "1 · my-project". Join it from the invitation in "Claude Control". A list there shows every session and its state: working, waiting for you or idle.
-
-4. Send prompts in the session's group, and Claude answers there, live as it writes. The answer's last message ends with a line in small print with the turn's time and tokens and the machine's free memory and disk, such as `Done in 2 min 51 s · 16K output tokens · 673K tokens in context · RAM 12 GB free · disk 3.4 GB free❗️`, with ❗️ when one runs low. A switch of the model or the effort level appears as one line. Reply to a message to show Claude which one you mean. Claude also gets your reactions, as emoji replies, and the new text of a prompt you edit. Prompts you type in the terminal appear there too, and Claude Code's own prompts, such as a finished background task, appear as one line each. Each step of Claude's work, such as running the tests, appears as one line, completed with its outcome when the step ends. A line also shows when Claude Code summarises the session's context. Before Claude acts in other chats or uses a tool such as Bash, it asks in the group, and one tap approves. Another tap approves the tool for the rest of the session.
-
-5. Optionally, add your plan's 5-hour and weekly usage to the last line of each answer, and get a status line in the terminal, with this setting in `~/.claude/settings.json`. It replaces a status line of your own. [Read more](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/REFERENCE.md#status-line).
-
- ```json
- "statusLine": {"type": "command", "command": "node \"${SIMPLEX_MCP_HOME:-$HOME/.simplex-mcp}/status-line.js\""}
- ```
+[REFERENCE.md](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/REFERENCE.md) covers the plugin without the channel, several machines or containers, the status line, options, recovery and security.
## Safety
- Anyone in "Claude Control" can join your sessions as an admin, so only invite people you trust.
-- In a session, admins and owners can prompt Claude and approve what it does. Other members can only prompt, and observers can only read.
+- In a session, admins and owners can prompt the agent and approve what it does. Other members can only prompt, and observers can only read.
- A tool approved for the session runs without asking until the session ends or `/revoke`. Claude Code still asks where its own rules require it, such as before a change to `.git` or `.bashrc`.
- Claude Code doesn't run `!` or `/` commands sent in the group.
-- Claude sends files to the group only if the group allows them.
-- Claude has no SimpleX address, so nobody can contact it first.
+- Agents send files to the group only if the group allows them.
+- Agents have no SimpleX address, so nobody can contact them first.
## Only Claude Code, for now
The agent is tested with Claude Code. Tell us which other apps and models you want to use in [an issue](https://github.com/simplex-chat/simplex-chat/issues), or contribute.
-## Reference
-
-[REFERENCE.md](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/REFERENCE.md) covers the plugin's options, recovery and security. It also explains shared settings for several machines or containers, and running the agent as an MCP server without the channel.
-
-What comes next: [Roadmap](https://github.com/simplex-chat/simplex-chat/blob/master/packages/simplex-chat-mcp/ROADMAP.md).
-
## Own a part of SimpleX
Business is moving into messages, and AI agents follow: an agent can ask a company's agent in a chat instead of opening the company's website, and buy there too. These chats hold plans, purchases and accounts, so with AI everyone feels the need for private and secure communication.
diff --git a/packages/simplex-chat-mcp/ROADMAP.md b/packages/simplex-chat-mcp/ROADMAP.md
index 548890807b..2cb4f4e7da 100644
--- a/packages/simplex-chat-mcp/ROADMAP.md
+++ b/packages/simplex-chat-mcp/ROADMAP.md
@@ -15,17 +15,21 @@ What comes next for Claude Code in SimpleX Chat.
## In your sessions
-- ✅ Reply to a message, and Claude knows which one you mean.
-- ✅ React to a message, and Claude sees your reaction.
-- ✅ Allow a tool for the rest of a session with one tap.
-- ✅ See when a session's context is summarised.
- ✅ One list in the Main group shows every session and its state: working, waiting for you or idle.
- See what Claude is doing while it works, with its code changes as diffs.
-- ✅ The model, effort and usage of each session show in its description, updated as they change.
+- ✅ React to a message, and Claude sees your reaction.
+- ✅ Reply to a message, and Claude knows which one you mean.
+- ✅ The model and effort of each session show in its description, updated as they change, and the usage of each turn in the last line of its answer.
+- ✅ See when a session's context is summarised.
+- ✅ Allow a tool for the rest of a session with one tap.
- Each session is a topic inside one group, not a group of its own.
- Claude can offer choices and other small interactive widgets in the chat.
- Start a new session from the desktop app, in a folder you choose.
+- Send voice messages to Claude.
+- Delete your latest prompt, and Claude knows you withdrew it.
+- Answer from the chat almost every time Claude Code waits for you.
## More agents
- Codex and other agents, alongside Claude Code.
+- Claude's subagents and teammates join the session's group with their own profiles, and a mention of one by name sends it a message.
From 44a193b54f146121f2c48c770178e691f5a2518f Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 14:05:45 +0000
Subject: [PATCH 05/20] mcp: 0.3.1 with simplex-chat 7.1.4 (#8266)
---
packages/simplex-chat-mcp/.claude-plugin/plugin.json | 2 +-
packages/simplex-chat-mcp/package-lock.json | 12 ++++++------
packages/simplex-chat-mcp/package.json | 4 ++--
3 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/packages/simplex-chat-mcp/.claude-plugin/plugin.json b/packages/simplex-chat-mcp/.claude-plugin/plugin.json
index 848a901e13..17b10cc98e 100644
--- a/packages/simplex-chat-mcp/.claude-plugin/plugin.json
+++ b/packages/simplex-chat-mcp/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "simplex",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "Each Claude Code session gets its own SimpleX group. There you prompt the session, approve its actions and tool use, and read its answers.",
"author": {"name": "SimpleX Chat", "url": "https://simplex.chat"},
"homepage": "https://github.com/simplex-chat/simplex-chat/tree/stable/packages/simplex-chat-mcp#readme",
diff --git a/packages/simplex-chat-mcp/package-lock.json b/packages/simplex-chat-mcp/package-lock.json
index 738926f8ef..618e47c008 100644
--- a/packages/simplex-chat-mcp/package-lock.json
+++ b/packages/simplex-chat-mcp/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@simplex-chat/mcp",
- "version": "0.3.0",
+ "version": "0.3.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@simplex-chat/mcp",
- "version": "0.3.0",
+ "version": "0.3.1",
"bundleDependencies": [
"@modelcontextprotocol/node",
"@modelcontextprotocol/server",
@@ -20,7 +20,7 @@
"@modelcontextprotocol/server": "^2.3.1",
"@simplex-chat/types": "^7.1.3",
"qrcode": "^1.5",
- "simplex-chat": "^7.1.3"
+ "simplex-chat": "^7.1.4"
},
"bin": {
"simplex-mcp": "dist/cli.js"
@@ -4319,9 +4319,9 @@
"license": "ISC"
},
"node_modules/simplex-chat": {
- "version": "7.1.3",
- "resolved": "https://registry.npmjs.org/simplex-chat/-/simplex-chat-7.1.3.tgz",
- "integrity": "sha512-StC2e0qZQS/L9VfHA1oWUTh3LIYSfo3Rj5hlGRZq0z2UjkH3nkbjmHI9z56316pT2EpXugPanW396Acfx+wTRA==",
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/simplex-chat/-/simplex-chat-7.1.4.tgz",
+ "integrity": "sha512-Uc4QNCAXhlsmEvySp307t59k/ke7oAWsZqYEsM6fAcufeT4LsART2KF7vzBhJZTAZQk2JOCLjwRxfpGE31tIFA==",
"inBundle": true,
"license": "AGPL-3.0",
"dependencies": {
diff --git a/packages/simplex-chat-mcp/package.json b/packages/simplex-chat-mcp/package.json
index c9b2f4b239..7264f2f20a 100644
--- a/packages/simplex-chat-mcp/package.json
+++ b/packages/simplex-chat-mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "@simplex-chat/mcp",
- "version": "0.3.0",
+ "version": "0.3.1",
"description": "MCP server and Claude Code plugin that give AI agents a SimpleX profile, approved in your app",
"bin": {
"simplex-mcp": "dist/cli.js"
@@ -30,7 +30,7 @@
"@modelcontextprotocol/server": "^2.3.1",
"@simplex-chat/types": "^7.1.3",
"qrcode": "^1.5",
- "simplex-chat": "^7.1.3"
+ "simplex-chat": "^7.1.4"
},
"bundleDependencies": true,
"devDependencies": {
From 86ce68883db81cc612ec8254e1032a0cdd655534 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 21:26:33 +0000
Subject: [PATCH 06/20] docs: testing approaches of the codebase (#8255)
---
CLAUDE.md | 1 +
docs/CONTRIBUTING.md | 2 +
docs/contributing/TESTS.md | 301 +++++++++++++++++++++++++++++++++++++
3 files changed, 304 insertions(+)
create mode 100644 docs/contributing/TESTS.md
diff --git a/CLAUDE.md b/CLAUDE.md
index 2c3cceced7..f490f20416 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,4 +1,5 @@
@docs/CONTRIBUTING.md
@docs/contributing/PROJECT.md
@docs/contributing/CODE.md
+@docs/contributing/TESTS.md
@scripts/ci/README.md
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 4207e62743..3479d43014 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -21,6 +21,8 @@ Please discuss the problem you want to solve and your detailed implementation pl
./contributing/CODE.md has details about general requirements common for `simplexmq` and `simplex-chat` repositories.
+./contributing/TESTS.md has the testing approaches of this repository: the tests required for a change, how they are written and run, and where CI runs them.
+
CLAUDE.md in the repository root imports these files, this guide and ../scripts/ci/README.md for Claude Code; apps/ios/CLAUDE.md and apps/multiplatform/CLAUDE.md import the README of each app.
## Compiling with SQLCipher encryption enabled
diff --git a/docs/contributing/TESTS.md b/docs/contributing/TESTS.md
new file mode 100644
index 0000000000..b2ec7d318d
--- /dev/null
+++ b/docs/contributing/TESTS.md
@@ -0,0 +1,301 @@
+# Testing
+
+The testing approaches of this repository: what is checked, how a test is written and run, and where CI runs it. The CI scopes, the reduced build and the `ci-tests` block of a pull request: [CI on GitHub's runners](../../scripts/ci/README.md).
+
+## Tests for a change
+
+| Change | Tests |
+|---|---|
+| Behaviour of the chat core: messages, groups, files, profiles, connections | [chat scenario test](#chat-scenario-tests) |
+| Encoding of a protocol message or a JSON type, markdown, a pure function of the core | [unit test](#unit-tests) |
+| Command, response, event or type of the core API | [Bot API docs](#checks-against-committed-files), regenerated
[app fixture](#app-fixtures), when an app processes it |
+| Database migration | [schema dumps](#checks-against-committed-files) of SQLite and PostgreSQL
query plans |
+| Directory service, badge service, remote sessions | the [suite](#suites) of the area |
+| App processing of a core response or event | [app fixture](#app-fixtures), replayed in Kotlin and iOS tests |
+| App screen | a preview, rendered by the [desktop](#desktop-snapshots) and [iOS](#simplex-snapshots) snapshot tests |
+| Flow across app screens | a case of an [app workflow](#app-workflows) |
+| Kotlin or Swift code without views | [desktopTest or commonTest](#kotlin-apps)
[SimpleX Unit Tests](#simplex-unit-tests) |
+| Package, bot, website or CI script | the tests of its [scope](#packages-and-other-scopes) |
+| Scope lacking CI tests | its CI coverage, in the same pull request ([Adding CI coverage](../../scripts/ci/README.md#adding-ci-coverage)) |
+
+## Core
+
+The hspec suite `simplex-chat-test` of simplex-chat.cabal, with the entry point [tests/Test.hs](../../tests/Test.hs). Building it, running it and selecting tests by hspec match patterns: [CI guide, core](../../scripts/ci/README.md#core). A pattern is a path of `describe` and `it` names, for example `/SimpleX chat client/direct tests/`.
+
+- A new test module is added to `other-modules` of the test suite in simplex-chat.cabal, and its spec to `main` of Test.hs.
+- `tests/tmp` contains a directory per test (`tmpBracket` in Test.hs) and is emptied at the start and the end of a run (`withTmpFiles` in ChatClient.hs).
+- With `CI=true`, set on GitHub's runners, the tests marked `xdescribe''` and `xit''` are skipped, and on macOS those marked `xitMacCI` ([ChatTests/Utils.hs](../../tests/ChatTests/Utils.hs)); the tests marked `xit'` are skipped on Linux.
+- [tests/fixtures](../../tests/fixtures): images and files sent in the tests, TLS credentials of the test servers, and the [app fixtures](#app-fixtures) in `api`.
+- In the full matrix of build.yml, the whole suite runs on Linux x86_64, with GHC 9.6.3 and 8.10.7, and on macOS aarch64; on a draft pull request, the tests matched by its `ci-tests` block run.
+- Coverage: `-fhpc` added to `ghc-options` of the test suite in simplex-chat.cabal.
+
+### Suites
+
+| Pattern | Module | Checked |
+|---|---|---|
+| `/SimpleX chat client/` | [ChatTests.hs](../../tests/ChatTests.hs) | [chat scenarios](#chat-scenario-tests): direct, forward, group, chat relay, local, file, profile and chat list tests |
+| `/names tests/` | ChatTests/Names.hs | SimpleX names, resolved by a local resolver ([NameResolver.hs](../../tests/NameResolver.hs)); SQLite only |
+| `/SimpleX chat protocol/` | ProtocolTests.hs | chat protocol messages, short link data, batch limits, preferences JSON |
+| `/JSON Tests/` | JSONTests.hs, JSONFixtures.hs | conversion of the Swift JSON form to the tagged form, with QuickCheck; JSON of markdown |
+| `/SimpleX chat markdown/` | MarkdownTests.hs | the markdown parser |
+| `/SimpleX chat view/` | ViewTests.hs | functions of the CLI view |
+| `/Mobile API Tests/` | MobileTests.hs | the API of the core library (src/Simplex/Chat/Mobile.hs) and its C functions; SQLite only |
+| `/Message batching/` | MessageBatching.hs | batches of messages and of relay deliveries |
+| `/Valid names/` | ValidNames.hs | display names made valid |
+| `/Random servers/` | RandomServers.hs | the random choice of preset servers |
+| `/Operators/` | OperatorTests.hs | server operators, usage conditions, validation of user servers |
+| `/Member relations/` | MemberRelationsTests.hs | member relation vectors |
+| `/Image resize/` | ImageTests.hs | image resizing |
+| `/Supporter badges/` | BadgeTests.hs | badge credentials and proofs |
+| `/WebRTC encryption/` | WebRTCTests.hs | encryption of call media frames; SQLite only |
+| `/Remote session/` | RemoteTests.hs | a desktop controlling a mobile: handshake, messages, files |
+| `/SimpleX Directory service bot/`
`/SimpleX Directory names/` | Bots/DirectoryTests.hs | the directory service with chat clients (`withDirectoryService`); names: SQLite only |
+| `/SimpleX Broadcast bot/` | Bots/BroadcastTests.hs | the broadcast bot; skipped when `CI=true` |
+| `/SimpleX badge service/` | Bots/BadgeService/*Tests.hs | configuration, web server and schema, catalog, groups, invoice waiters, payment providers, store receipts; the providers are local fakes (`Fake*.hs`) |
+| `/SimpleX badge service e2e/` | Bots/BadgeService/BotTests.hs, GroupIntegrationTests.hs | the badge service bot with chat clients |
+| `/Schema dump/`
`/Postgres schema dump/`
`/Bot API docs/`
`/Save query plans/` | SchemaDump.hs, PostgresSchemaDump.hs, APIDocs.hs | [committed files](#checks-against-committed-files) |
+
+### Chat scenario tests
+
+- Checked: chat cores of several clients connected through a test SMP server, by the terminal output of each client, and by queries of a client's database for a state absent from the output.
+- Pattern, registered with `it "" testDirectMessage` in the spec of its module:
+
+ ```haskell
+ testDirectMessage :: HasCallStack => TestParams -> IO ()
+ testDirectMessage =
+ testChat2 aliceProfile bobProfile $ \alice bob -> do
+ connectUsers alice bob
+ alice #> "@bob hello"
+ bob <# "alice> hello"
+ ```
+
+- Helpers of [ChatClient.hs](../../tests/ChatClient.hs) and [ChatTests/Utils.hs](../../tests/ChatTests/Utils.hs):
+
+ | Helper | Use |
+ |---|---|
+ | `testChat2` … `testChat5`, `testChatCfgOpts2` | clients with new databases |
+ | `withNewTestChat`, `withTestChat` | one client with a new database; a restart with its database |
+ | `withNewTestChatCfgOpts` | a client with a `ChatConfig` and `ChatOpts`, such as `chatHooks` or `markRead = False` |
+ | `connectUsers`, `createGroup2`, `createGroup3` | a contact; a group of 2 or 3 members |
+ | `##>`, `#>`, `send` | a command and its echo; a message and its sent item, time removed; a command alone |
+ | `<##`, `<#`, `<##.`, `.<##` | the next line; the next line, time removed; its prefix; its suffix |
+ | `<###`, `concurrentlyN_` | lines in any order; lines of several clients at once |
+ | `#$>` | a command and a function of its output line, as in `("/_get chat @2 count=100", chat, [...])` |
+ | `withCCTransaction`, `shouldEventuallyReturn` | a query of the client's database; a value polled for 20 s |
+ | `withXFTPServer`, `withSmpServer'`, `withSmpServerAndNames` | an XFTP server; another SMP server; an SMP server with a names resolver |
+ | `versionTestMatrix2`, `testCfgVPrev`, `testCfgV1` | clients of the previous and of the first supported versions |
+ | `withTestOutput` | the terminal output of the clients printed |
+
+- Run: `/SimpleX chat client/ tests/`, for example `/SimpleX chat client/group tests/`.
+- CI: build-linux, step "Run tests".
+- Pitfalls:
+ - The output of every client is read to its end: a test fails when a client prints a line within 0.1 s after the test (`/` in `testChatN` and the `with…TestChat…` brackets).
+ - The lines of one client are read in order; the lines of several clients are awaited with `concurrently_` or `concurrentlyN_`.
+ - A test fails when a line is awaited for 20 s (`getTermLine'`) and when it runs longer than 180 s (`it` of ChatTests/Utils.hs, imported in place of hspec's).
+ - Each test has its own ports (`withPortBase`): the ports 7001–7003 of server addresses in `ChatOpts` are mapped to them (`testPortsCfg`), and `smpServerStr`, `smpServer2Str` and `xftpServerStr` return the addresses for commands and expected lines.
+ - One SMP server is started per test by `testBracket` of Test.hs; XFTP and other servers are started by the test.
+
+### Unit tests
+
+- Checked: functions and encodings of the core, in the [suites](#suites) without clients.
+- Pattern: a `Spec` of `describe` and `it` with hspec expectations, as in [ViewTests.hs](../../tests/ViewTests.hs) and [ProtocolTests.hs](../../tests/ProtocolTests.hs).
+- Pitfall: in MobileTests, the expected JSON is the Swift form on macOS with the `swift` flag and the tagged form otherwise; both forms are in JSONFixtures.hs.
+
+### Checks against committed files
+
+Each of these tests writes its file, then compares the new text with the previous one: the first run after a change of the text fails, and the next passes. The rewritten file is reviewed and committed with the change.
+
+| Pattern | Written | Source |
+|---|---|---|
+| `/Bot API docs/` | bots/api/COMMANDS.md, EVENTS.md, TYPES.md
packages/simplex-chat-client/types/typescript/src/*.ts
packages/simplex-chat-python/src/simplex_chat/types/_*.py | the API docs in bots/src/API/Docs (`testGenerate` in [APIDocs.hs](../../tests/APIDocs.hs)) |
+| `/Schema dump/` | src/Simplex/Chat/Store/SQLite/Migrations/chat_schema.sql | SQLite migrations, dumped with `sqlite3` |
+| `/Postgres schema dump/` | src/Simplex/Chat/Store/Postgres/Migrations/chat_schema.sql | PostgreSQL migrations, dumped with `pg_dump` |
+| `/Save query plans/` | chat_query_plans.txt and agent_query_plans.txt in src/Simplex/Chat/Store/SQLite/Migrations | the queries recorded in the run (`chatQueryStats`, `agentQueryStats`) |
+| recording tests | tests/fixtures/api | [app fixtures](#app-fixtures) |
+
+- Bot API docs also fail on a command, response or event of the API that is neither documented in bots/src/API/Docs nor listed in `cliCommands`, `undocumentedCommands`, `undocumentedResponses` or `undocumentedEvents`, on a type of a documented one missing from Docs/Types.hs, and on a documented command without responses. They run with GHC 9.6 and later (`MIN_VERSION_base(4,18,0)`), in SQLite builds.
+- Schema dump also checks down migrations (exceptions in `skipComparisonForDownMigrations`), STRICT tables, and the output of `.lint fkey-indexes` against chat_lint.sql, an empty file, so that the test fails for a foreign key without an index.
+- Save query plans is skipped when `CI=true`. The plans are of the queries of that run only, so the files are committed from a local run of the whole suite.
+
+### PostgreSQL
+
+- Run:
+
+ ```sh
+ cabal test simplex-chat-test --constraint 'simplexmq +client_postgres' --constraint 'simplex-chat +client_postgres' --ghc-options=-O0 --test-option=-m --test-option='/SimpleX chat client/'
+ ```
+
+ The flags `client_postgres` of simplexmq and simplex-chat, as in scripts/desktop/build-lib-linux.sh; `dbPostgres` is defined for the tests.
+- Needed: a PostgreSQL server that accepts the role `postgres` without a password, and `pg_dump`. The role `test_chat_user` and the database `test_chat_db` are created at the start of a run and dropped at its end (`withTestDB` in Test.hs); each client has its own schema, dropped after each test (`dropTestSchemas` in ChatClient.hs).
+- Left out of PostgreSQL builds: Schema dump, Bot API docs, WebRTC encryption, Mobile API Tests, both names suites, Save query plans.
+- CI: local runs only; build.yml builds the PostgreSQL library for releases (build-linux-postgres).
+- Pitfall: the Postgres schema dump calls `sed -i ''` (BSD sed) unless `CI=true`.
+
+## App fixtures
+
+The core's responses and events are recorded by core tests in [tests/fixtures/api](../../tests/fixtures/api) and replayed by Kotlin and iOS tests in place of the core library, so that app code is tested on the output of the current core.
+
+```mermaid
+flowchart LR
+ CT["core test
tests/ChatTests"] -->|"apiFixture
eventsFixture"| F["tests/fixtures/api"]
+ F --> T["Kotlin desktopTest
iOS SimpleX Unit Tests"]
+ T -->|"recorded responses
in place of the core"| V["app functions and views"]
+ T -->|"recorded events"| P["processReceivedMsg"]
+ V --> M["ChatModel, alerts, notifications"]
+ P --> M
+```
+
+### Recording
+
+Helpers of [ChatTests/Utils.hs](../../tests/ChatTests/Utils.hs), called in a chat scenario test:
+
+| Helper | Written to `tests/fixtures/api/.json` |
+|---|---|
+| `apiFixture fixture cc placeholders FixtureRequests {frCommands, frMarkdown, frUris}` | an object with `commands`, `markdown` and `uris`, keyed by the request: the response to each command, encoded by `chatSendCmd` of the core library's API; `chatParseMarkdown` of each text; `chatParseUri` of each link |
+| `nameFixture fixture cc name` | `apiFixture` of `/_connect plan 1 ` and of the markdown of the name, in `names/` |
+| `eventsFixture fixture events steps` | an array of the events appended by `recordItemEvent events`, in `eventHook` of `chatHooks`, during `steps`: `newChatItems` and `chatItemUpdated`, encoded as `chatRecvMsg` encodes them |
+| `nameMovedFixture` | a `nameMoved` event, built from the IDs of the named contacts and groups |
+
+Examples: `testPlanKnownNameAvailable` in ChatTests/Names.hs, `testDirectMessageUpdatePrevItem` and `testMissedCall` in ChatTests/Direct.hs.
+
+Stable recordings:
+
+- Values of each run are replaced by `stableJSON`:
+
+ | Fields | Replaced by |
+ |---|---|
+ | `createdAt`
`updatedAt`
`chatTs`
`userMemberProfileSentAt`
`itemTs` | `1970-01-01T00:00:00Z` |
+ | `agentConnId`
`xContactId`
`connFullLink`
`connShortLink`
`contactLink`
`groupLink`
`viaGroupLinkUri`
`simplexUri`
`memberId`
`memberPubKey`
`publicGroupId`
`businessId`
`customerId`
`itemSharedMsgId` | the field name |
+ | `groupRelays` | `"groupRelay"` per element |
+
+ A field with a new value in each run is added to this list.
+- Strings of the test, such as links, are replaced by the `placeholders` of `apiFixture`, in keys and values: `[(cLink, "CONTACT_LINK")]` in `testPlanAddressContactViaAddress`, so that the app test connects to `CONTACT_LINK`.
+- The recorded state is awaited first: the response to an update is recorded after the item status in the database is `snd_rcvd ok complete` (`shouldEventuallyReturn` in `testDirectMessageUpdatePrevItem`), and the steps of `eventsFixture` end after the expected number of events (`testMissedCall`).
+- The client whose events are recorded has `markRead = False`: the CLI marks received items read when it prints them (`runTerminalOutput` in src/Simplex/Chat/Terminal/Output.hs), while the apps receive unread items.
+- Recordings are in the tagged JSON form of builds without the `swift` flag.
+
+### Replay
+
+| | Kotlin, common/src/commonMain | iOS |
+|---|---|---|
+| Commands | `chatSendCmdRetry`, platform/Core.kt | `sendSimpleXCmdStr`, SimpleXChat/API.swift |
+| Markdown | `chatParseMarkdown`, platform/Core.kt | `parseSimpleXMarkdownText`, SimpleXChat/API.swift |
+| Links | `chatParseUri`, platform/Core.kt | `parseSanitizeUri`, SimpleXChat/API.swift |
+| Events | `ChatController.processReceivedMsg`, model/SimpleXAPI.kt | `processReceivedMsg`, Shared/Model/SimpleXAPI.swift |
+| Notifications | `ntfManager`, platform/NtfManager.kt | `NtfManager.shared`, Shared/Model/NtfManager.swift |
+| Recording read by | `fixtureText` | `fixtureJSON`, then `singleFieldJSON` to the Swift JSON form |
+| Tests | [NameAlertsTest.kt](../../apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/NameAlertsTest.kt), [ChatItemUpdateTest.kt](../../apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/ChatItemUpdateTest.kt) | [NameAlertsTests.swift](../../apps/ios/SimpleX%20Unit%20Tests/NameAlertsTests.swift), [ChatItemUpdateTests.swift](../../apps/ios/SimpleX%20Unit%20Tests/ChatItemUpdateTests.swift) |
+
+- Pattern: `recorded(fixture)` in the NameAlerts tests sets the first three seams to lookups in the recording; the test fails at tear-down on a request without a recorded response, unless the request is checked with `assertRequested`. The ChatItemUpdate tests decode the recorded events, pass each to `processReceivedMsg` and compare `ChatModel`. Tear-down restores the seams and clears the model.
+- Run and CI: [Kotlin apps](#kotlin-apps), [SimpleX Unit Tests](#simplex-unit-tests). CI runs the kotlin and ios scopes for a change in tests/fixtures/api (`BUILD_CHANGES` in scripts/ci/packages_release.py). The recording tests are core tests, selected in the `ci-tests` block by the patterns of the [CI guide, core](../../scripts/ci/README.md#core).
+- Pitfalls:
+ - `singleFieldJSON` converts each object with a `type` field, except `MsgContent`, recognized by its tags. The core encodes other types with `type` in both JSON forms: the types of `taggedObjectJSON` in src, such as `MsgChatLink`, `LinkContent`, `MsgScope` and `ChatBotCommand`, and `MsgReaction`, by its own instance. A recording with them requires another conversion rule.
+ - The tests use the app's singletons, such as `ChatModel` and `AlertManager`: each test restores what it changes.
+ - The core is reached only through the replaced seams: the Kotlin test JVM does not load the core library, and the iOS app host in CI is linked with stub libraries.
+
+## Kotlin apps
+
+In apps/multiplatform:
+
+| Source set | Gradle task | Contents |
+|---|---|---|
+| common/src/commonTest | `:common:desktopTest` | tests of common code (kotlin.test) |
+| common/src/desktopTest | `:common:desktopTest` | JVM tests: Compose views with `runComposeUiTest`, layout positions with `renderScene` and `Modifier.record` ([LayoutRecorder.kt](../../apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/LayoutRecorder.kt)), files with `withTempDir`, [app fixtures](#app-fixtures), [snapshots](#desktop-snapshots) |
+| android/src/test | `:android:testFossDebugUnitTest` | a template test, `ExampleUnitTest` |
+| android/src/androidTest | `connectedFossDebugAndroidTest`, with a device or an emulator | a template test, `ExampleInstrumentedTest` |
+
+- Run: `./gradlew :common:desktopTest`; one class: `./gradlew :common:desktopTest --tests chat.simplex.app.ChatItemUpdateTest`. The CI command: [CI guide, kotlin](../../scripts/ci/README.md#kotlin).
+- CI: build.yml, step "Build and test Kotlin apps" (kotlin scope); desktop-linux, app job.
+- Pitfalls:
+ - The working directory is apps/multiplatform/common: recordings are read from `../../../tests/fixtures/api`, sources from `src/`.
+ - The tests use the app's singletons, such as `ChatModel`, `appPrefs` and `simplexWindowState`: they are restored in `@AfterTest`.
+ - The test JVM does not load the core library: code that calls it is tested with the replaced seams of [app fixtures](#replay).
+
+### Desktop snapshots
+
+- Checked: each `@Preview` of commonMain and desktopMain, rendered in the light and dark themes by `SnapshotTest` ([SnapshotTest.kt](../../apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt)), equals its reference in [common/src/desktopTest/snapshots](../../apps/multiplatform/common/src/desktopTest/snapshots), within 8 of 255 per colour channel ([snapshots-compare.py](../../scripts/ci/snapshots-compare.py)).
+- Write: a new `@Preview` is added to `previewScenes`, with `chatItemFontScales` for a chat item, or to `previewsCallingCore` when its layout calls the core library; `everyPreviewIsRendered` fails otherwise. A preview uses `previewDate` in place of the current time.
+- Record and check: with `scripts/ci/snapshots-remote.py desktop record`, desktop-linux renders the previews of the pushed branch, and the renders replace the references, for review and commit; with `check`, the renders that differ are listed.
+- Run, from apps/multiplatform, then from the repository root:
+
+ ```sh
+ SNAPSHOT_DIR= ./gradlew -Psimplex.assets.dir=../../assets :common:desktopTest --tests chat.simplex.app.SnapshotTest
+ python3 scripts/ci/snapshots-compare.py apps/multiplatform/common/src/desktopTest/snapshots
+ ```
+
+- CI: desktop-linux, step "Compare snapshots"; in build.yml, the previews are rendered without a comparison.
+- Details: [desktop-linux README](../../scripts/ci/desktop-linux/README.md), "Snapshots".
+
+## iOS app
+
+In apps/ios, SimpleX.xcodeproj:
+
+| Target | Kind | Scheme | CI |
+|---|---|---|---|
+| SimpleX Unit Tests | unit tests hosted by the app | SimpleX Unit Tests | build.yml, build-ios, step "Run iOS unit tests" (ios scope) |
+| SimpleX Snapshots | unit tests hosted by the app: preview renders and tests of a running chat | SimpleX (iOS) | ios-sim, after the smoke test |
+| Tests iOS | UI tests of Xcode's template | SimpleX (iOS) | local runs only |
+
+A new test file is added to its target in project.pbxproj: a PBXBuildFile, a PBXFileReference, the target's group and its Sources phase.
+
+### SimpleX Unit Tests
+
+- Checked: app code on [app fixtures](#app-fixtures) and other logic of the app.
+- Write: an `XCTestCase` in [apps/ios/SimpleX Unit Tests](../../apps/ios/SimpleX%20Unit%20Tests); `fixtureJSON`, `singleFieldJSON` and `waitFor` are at file scope of NameAlertsTests.swift.
+- Run, on macOS: `scripts/ci/ios-stub-libs.sh`, then the `xcodebuild test` command of the step "Run iOS unit tests" of build-ios in build.yml; or Product > Test with the scheme SimpleX Unit Tests.
+- Pitfalls:
+ - The stubs replace the libraries in apps/ios/Libraries/sim, where scripts/ios/prepare.sh puts the core built for the simulator.
+ - With the stubs, the app opens its database error screen and calls the core no more.
+ - The tests run with `-testLanguage en -testRegion US`; a test of dates sets `NSTimeZone.default` to UTC.
+
+### SimpleX Snapshots
+
+- Checked: each `PreviewProvider` of apps/ios, rendered in the light and dark themes, equals its reference in [References](../../apps/ios/SimpleX%20Snapshots/References), within 8 of 255 per colour channel; previews marked `allSizes` are rendered at three content sizes. [SnapshotTests.swift](../../apps/ios/SimpleX%20Snapshots/SnapshotTests.swift) also contains assertion tests of layout functions, calls and VoIP pushes; the VoIP push tests require a running chat (`waitUntilChatActive`).
+- Write: a new `PreviewProvider` is added to `previewScenes()`, or to `EXCLUDED` of [check-previews.py](../../apps/ios/SimpleX%20Snapshots/check-previews.py) when its renders differ between runs; check-previews.py fails on a `#Preview`. A preview uses `previewDate` in place of the current time.
+- Record and check: `scripts/ci/snapshots-remote.py ios record|check`, as for [desktop](#desktop-snapshots).
+- Run, from the repository root, with the core in apps/ios/Libraries/sim and a simulator where the app has a running chat: `SIM_UDID= scripts/ci/ios-sim/snapshots.sh ` ([snapshots.sh](../../scripts/ci/ios-sim/snapshots.sh)).
+- CI: build-ios runs check-previews.py; ios-sim renders and compares at the end of the smoke test, whose step fails on a difference.
+- Details: [ios-sim README](../../scripts/ci/ios-sim/README.md), "Snapshots".
+
+### Tests iOS
+
+Xcode's UI test template: `testExample` launches the app, `testLaunchPerformance` measures its launch, `testLaunch` attaches a screenshot of the launch screen. It is in the test action of the scheme SimpleX (iOS), with SimpleX Snapshots: `xcodebuild test -scheme "SimpleX (iOS)"` of [apps/ios/README.md](../../apps/ios/README.md) runs both.
+
+## App workflows
+
+The app built from a branch, its core included, driven on a device by scripts and, on request, by Claude following a test plan, with an optional test backend (relay, directory, names server, peers).
+
+| Workflow | App | Smoke test | Claude plan | README |
+|---|---|---|---|---|
+| `ios-sim` | iOS app in an iPhone simulator | onboarding
images sent in a group
snapshots | device-test-plan.md, cases per layout in claude-scope | [ios-sim](../../scripts/ci/ios-sim/README.md) |
+| `desktop-linux` | desktop app on a virtual display, Ubuntu | desktopTest with snapshots
onboarding
a local group
both layouts
images sent | claude-test.md, claude-scope | [desktop-linux](../../scripts/ci/desktop-linux/README.md) |
+| `android-emu` | debug APK in an Android emulator | onboarding
a local group
both layouts
images sent | claude-test.md, claude-scope | [android](../../scripts/ci/android/README.md) |
+
+- Write: a scripted case in the workflow's `smoke-test.sh`, with its `ui` driver; a Claude plan in the files of the table, with `backend: yes` in claude-scope when the cases use the test backend.
+- Run: by hand only, on any branch: [CI guide, Starting a run](../../scripts/ci/README.md#starting-a-run). Each run uploads the app for manual tests.
+- Pitfalls:
+ - A run with `claude` and `backend: yes` in claude-scope also requires the input `backend`, or its plan job fails.
+ - A Claude run requires the branch rule of the GitHub environment `app-sim-claude` to include the branch.
+ - The Android app runs under ARM translation: with the input `release`, the released app runs in the same emulator, to tell an app failure from the emulator's.
+
+## Packages and other scopes
+
+| Scope | Tests | Run |
+|---|---|---|
+| packages: Node.js library | [packages/simplex-chat-nodejs/tests](../../packages/simplex-chat-nodejs/tests), jest:
unit tests `*.unit.test.ts`, with `core` functions mocked
tests of the add-on and of library downloads
live tests with a local smp-server (`describeIfSmpServerAvailable`: `SMP_SERVER`, or a download on Linux) | `scripts/ci/package-tests.sh build linux-x86_64`
`scripts/ci/package-tests.sh test` |
+| packages: Python library | [packages/simplex-chat-python/tests](../../packages/simplex-chat-python/tests), pytest, with a fake libsimplex (`FakeLib`) | as above |
+| packages: TypeScript types | generated by [Bot API docs](#checks-against-committed-files), compiled by package-tests.sh | as above |
+| mcp | [packages/simplex-chat-mcp/test](../../packages/simplex-chat-mcp/test), jest:
`test/unit`
`test/e2e`, with a local smp-server and xftp-server
manual checks: [TESTING.md](../../packages/simplex-chat-mcp/TESTING.md) | `scripts/ci/scope-tests.sh mcp` |
+| support-bot | [apps/simplex-support-bot/bot.test.ts](../../apps/simplex-support-bot/bot.test.ts), vitest, with `simplex-chat` and `@simplex-chat/types` replaced by test/__mocks__ | `scripts/ci/scope-tests.sh support-bot` |
+| support-bot-light | [apps/simplex-support-bot-light/tests](../../apps/simplex-support-bot-light/tests), pytest, with `FakeChatApi` of conftest.py; ruff, pyright | `scripts/ci/scope-tests.sh support-bot-light` |
+| website | [website/test](../../website/test), `node --test` of src/js/simplex-lib.jsc | `npm test` in website |
+| badge-web | [apps/simplex-badge-service/web/test](../../apps/simplex-badge-service/web/test), `node --test` of the compiled tests, in UTC | `npm ci`, `npm test` in apps/simplex-badge-service/web |
+| ci-scripts | [scripts/ci/test_packages_release.py](../../scripts/ci/test_packages_release.py), unittest of packages_release.py | `python3 scripts/ci/test_packages_release.py` |
+
+CI of each scope: [CI guide, Scopes](../../scripts/ci/README.md#scopes). Scopes lacking CI tests, with tests run locally:
+
+| Scope | Run | Notes |
+|---|---|---|
+| ts-client | `npm test` in packages/simplex-chat-client/typescript | prettier, eslint and jest; client.test.ts is skipped |
+| webrtc | `npm test` in packages/simplex-chat-webrtc | fullstack.test.js requires `SIMPLEX_CHAT` and `SMP_SERVER`, the paths of the chat CLI and of smp-server |
+| calculator-bot | `npm test` in apps/simplex-calculator-bot | calculatorBot.test.ts: smp-server from `SMP_SERVER` or a download on Linux, and tests/fixtures/tls |
From f795d0a17a93d1f5822b887bc73e42fb3919b97c Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Thu, 19 Nov 2026 21:31:36 +0000
Subject: [PATCH 07/20] docs: app changes come with app tests on the core's
recorded responses (#8252)
---
docs/CONTRIBUTING.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 3479d43014..7262803694 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -95,6 +95,7 @@ For some complex features we create feature branches that will be merged once re
4. Mark the pull request ready for review once it is ready. CI then runs the full matrix on each push, and the code owners are requested for review.
5. Mark it as a draft again when more work is needed. After the approval, the pull request is merged by squash once CI passes.
6. A change to a scope without CI tests adds its build and tests to CI in the same pull request.
+7. A change of the apps' code adds, in the same pull request, app tests of all its changes on the core's real responses: core tests record the responses and events in tests/fixtures/api, and the Kotlin and iOS tests run the app code on them, with any platform service the code calls mocked (CI guide: "App test fixtures").
## Differences between GHC 8.10.7 and GHC 9.6.3
From 804242661e854ca1a3b646684482d8337edd3f38 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Fri, 20 Nov 2026 08:45:18 +0000
Subject: [PATCH 08/20] ci: decide the library claim from the written releases
(#8137)
* ci: test the library claim when reads return the previous releases
* ci: decide the library claim from the written releases
---
scripts/ci/packages_release.py | 14 ++++----
scripts/ci/test_packages_release.py | 54 ++++++++++++++++++++---------
2 files changed, 45 insertions(+), 23 deletions(-)
diff --git a/scripts/ci/packages_release.py b/scripts/ci/packages_release.py
index 9a10f5b721..57d959f17a 100644
--- a/scripts/ci/packages_release.py
+++ b/scripts/ci/packages_release.py
@@ -651,15 +651,15 @@ def read_releases() -> tuple[dict, str | None]:
return tomllib.loads(base64.b64decode(file["content"]).decode()), file["sha"]
-def record_releases(entries: list[tuple[str, str]], commit: str) -> str:
- """Adds the entries in one commit of simplex-chat-libs and returns that commit."""
+def record_releases(entries: list[tuple[str, str]], commit: str) -> tuple[dict, str]:
+ """Adds the entries in one commit of simplex-chat-libs and returns the releases of that commit with its sha."""
message = ", ".join(f"{key} {version}" for key, version in entries)
attempt = 1
while True:
releases, blob = read_releases()
updated = add_releases(releases, entries, commit)
if blob and updated == releases:
- return libs_api(f"commits?path={RELEASES_FILE}&per_page=1")[0]["sha"]
+ return updated, libs_api(f"commits?path={RELEASES_FILE}&per_page=1")[0]["sha"]
body = {
"message": message,
"content": base64.b64encode(render_releases(updated).encode()).decode(),
@@ -667,7 +667,7 @@ def record_releases(entries: list[tuple[str, str]], commit: str) -> str:
**({"sha": blob} if blob else {}),
}
try:
- return libs_api(f"contents/{RELEASES_FILE}", "PUT", body)["commit"]["sha"]
+ return updated, libs_api(f"contents/{RELEASES_FILE}", "PUT", body)["commit"]["sha"]
except urllib.error.HTTPError as e:
# 409 and 422: another writer changed or created the file since it was read
if e.code not in (409, 422) or attempt == RECORD_ATTEMPTS:
@@ -746,8 +746,7 @@ def claim_core(version: str, commit: str, branch: str) -> None:
return
if problem := types_problem(version, releases, branch):
sys.exit(problem)
- libs_commit = record_releases([(core_key(branch), version)], commit)
- releases, _ = read_releases()
+ releases, libs_commit = record_releases([(core_key(branch), version)], commit)
if recorded_core_commit(releases, version) == commit:
print("claim=new")
print(f"commit={libs_commit}")
@@ -894,7 +893,8 @@ def record(args: argparse.Namespace) -> None:
entries = [(key, version) for key, version in versions if version]
if not entries:
sys.exit("nothing to record")
- print(record_releases(entries, args.commit))
+ _, libs_commit = record_releases(entries, args.commit)
+ print(libs_commit)
def test_names() -> None:
diff --git a/scripts/ci/test_packages_release.py b/scripts/ci/test_packages_release.py
index 6b7603eae5..58031f92a2 100644
--- a/scripts/ci/test_packages_release.py
+++ b/scripts/ci/test_packages_release.py
@@ -88,6 +88,10 @@ def listed_release(tag: str, assets: list[str], n: int, draft: bool = False, bod
return {"id": n, "tag_name": tag, "draft": draft, "body": body, **github_release(assets, n)}
+def releases_file(releases: dict, blob: str) -> dict:
+ return {"content": base64.b64encode(render_releases(releases).encode()).decode(), "sha": blob}
+
+
def state(**overrides) -> State:
current = State(
libs_tag="core-1.0.0.1",
@@ -339,9 +343,6 @@ class ReleasesFileTest(unittest.TestCase):
class RecordReleasesTest(unittest.TestCase):
- def file(self, releases, blob):
- return {"content": base64.b64encode(render_releases(releases).encode()).decode(), "sha": blob}
-
def conflict(self):
error = urllib.error.HTTPError("url", 409, "Conflict", email.message.Message(), io.BytesIO())
self.addCleanup(error.close)
@@ -355,13 +356,13 @@ class RecordReleasesTest(unittest.TestCase):
return None if method == "GET" else {"commit": {"sha": "libs1"}}
with mock.patch.object(packages_release, "libs_api", api):
- self.assertEqual(record_releases([("core", "7.1.0.12")], "sx1"), "libs1")
+ self.assertEqual(record_releases([("core", "7.1.0.12")], "sx1"), ({"core": {"7.1.0.12": "sx1"}}, "libs1"))
_, method, body = calls[1]
self.assertEqual((method, body["message"], "sha" in body), ("PUT", "core 7.1.0.12", False))
self.assertEqual(tomllib.loads(base64.b64decode(body["content"]).decode()), {"core": {"7.1.0.12": "sx1"}})
def test_retries_when_another_writer_changed_the_file(self):
- reads = iter([self.file({"core": {"1": "a"}}, "blob1"), self.file({"core": {"1": "a", "2": "b"}}, "blob2")])
+ reads = iter([releases_file({"core": {"1": "a"}}, "blob1"), releases_file({"core": {"1": "a", "2": "b"}}, "blob2")])
puts = []
def api(path, method="GET", body=None):
@@ -372,21 +373,19 @@ class RecordReleasesTest(unittest.TestCase):
raise self.conflict()
return {"commit": {"sha": "libs2"}}
+ written = {"core": {"1": "a", "2": "b"}, "npm": {"simplex-chat": {"3": "sx3"}}}
with mock.patch.object(packages_release, "libs_api", api):
- self.assertEqual(record_releases([("npm/simplex-chat", "3")], "sx3"), "libs2")
+ self.assertEqual(record_releases([("npm/simplex-chat", "3")], "sx3"), (written, "libs2"))
self.assertEqual([body["sha"] for body in puts], ["blob1", "blob2"])
- self.assertEqual(
- tomllib.loads(base64.b64decode(puts[1]["content"]).decode()),
- {"core": {"1": "a", "2": "b"}, "npm": {"simplex-chat": {"3": "sx3"}}},
- )
+ self.assertEqual(tomllib.loads(base64.b64decode(puts[1]["content"]).decode()), written)
def test_recorded_entries_return_the_last_commit_of_the_file(self):
def api(path, method="GET", body=None):
self.assertEqual(method, "GET")
- return [{"sha": "libs0"}] if path.startswith("commits") else self.file({"core": {"1": "a"}}, "blob1")
+ return [{"sha": "libs0"}] if path.startswith("commits") else releases_file({"core": {"1": "a"}}, "blob1")
with mock.patch.object(packages_release, "libs_api", api):
- self.assertEqual(record_releases([("core", "1")], "other"), "libs0")
+ self.assertEqual(record_releases([("core", "1")], "other"), ({"core": {"1": "a"}}, "libs0"))
class GitRepoTest(unittest.TestCase):
@@ -640,7 +639,7 @@ class PackageStateTest(GitRepoTest):
with (
mock.patch.object(packages_release, "ROOT", self.repo),
mock.patch.object(packages_release, "python_project", return_value="simplex-chat"),
- mock.patch.object(packages_release, "record_releases", return_value="libs1") as record,
+ mock.patch.object(packages_release, "record_releases", return_value=({}, "libs1")) as record,
contextlib.redirect_stdout(io.StringIO()),
):
packages_release.main(["record", "--commit", "sx1", "--mcp", "0.2.0"])
@@ -786,11 +785,10 @@ class PublishReleaseTest(unittest.TestCase):
class ClaimCoreTest(unittest.TestCase):
def claim(self, recorded, after_record=None, problem=None, version="7.1.0.12", branch="master"):
- reads = iter([(recorded, "blob"), (after_record or recorded, "blob")])
- self.record = mock.Mock(return_value="libs1")
+ self.record = mock.Mock(return_value=(after_record or recorded, "libs1"))
output = io.StringIO()
with (
- mock.patch.object(packages_release, "read_releases", lambda: next(reads)),
+ mock.patch.object(packages_release, "read_releases", return_value=(recorded, "blob")),
mock.patch.object(packages_release, "record_releases", self.record),
mock.patch.object(packages_release, "types_problem", return_value=problem),
contextlib.redirect_stdout(output),
@@ -836,6 +834,30 @@ class ClaimCoreTest(unittest.TestCase):
claimed = {"core": {"master": {"7.1.0.11": "sx0", "7.1.0.12": "sx2"}}}
self.assertEqual(self.claim({"core": {"master": {"7.1.0.11": "sx0"}}}, claimed), ["claim=skip"])
+ def test_written_claim_is_new_when_reads_return_the_previous_file(self):
+ previous = {"core": {"master": {"7.1.0.11": "sx0"}}}
+ puts = []
+
+ def api(path, method="GET", body=None):
+ if method == "GET":
+ return releases_file(previous, "blob1")
+ puts.append(body)
+ return {"commit": {"sha": "libs1"}}
+
+ output = io.StringIO()
+ with (
+ mock.patch.object(packages_release, "libs_api", api),
+ mock.patch.object(packages_release, "types_problem", return_value=None),
+ contextlib.redirect_stdout(output),
+ ):
+ claim_core("7.1.0.12", "sx1", "master")
+ self.assertEqual(output.getvalue().splitlines(), ["claim=new", "commit=libs1"])
+ self.assertEqual([body["sha"] for body in puts], ["blob1"])
+ self.assertEqual(
+ tomllib.loads(base64.b64decode(puts[0]["content"]).decode()),
+ {"core": {"master": {"7.1.0.11": "sx0", "7.1.0.12": "sx1"}}},
+ )
+
class TypesProblemTest(unittest.TestCase):
def problem(self, types, changed=True, published=False, releases=None):
From 14c0fa04a08afebb23cb7138c65f017f9abc9339 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Fri, 20 Nov 2026 11:44:41 +0000
Subject: [PATCH 09/20] tests: record name fixtures after the channel join
settles (#8250)
---
tests/ChatTests/Names.hs | 10 ++++++++++
tests/fixtures/api/names/plan-known-failed.json | 1 +
tests/fixtures/api/names/search-team.json | 3 ++-
3 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/tests/ChatTests/Names.hs b/tests/ChatTests/Names.hs
index 6a2f1eedba..1453d64c16 100644
--- a/tests/ChatTests/Names.hs
+++ b/tests/ChatTests/Names.hs
@@ -322,6 +322,7 @@ testChannelDomainVerify ps = withSmpServerAndNames ps $ \reg ->
alice ##> "/_verify domain #1"
alice <## "SimpleX name #team verified"
memberJoinChannel "team" [cath] [alice] shortLink fullLink bob
+ settleTeamJoin alice cath bob
bob ##> "/_verify domain #1"
bob <## "SimpleX name #team verified"
-- the name is re-pointed to a different link: verification fails
@@ -1007,10 +1008,18 @@ joinVerifiedTeam reg alice cath bob = do
registerName reg teamSimplexName (channelNameRecord "team.simplex" (T.pack shortLink))
setChannelDomain alice cath "alice" "team" "team.simplex"
memberJoinChannel "team" [cath] [alice] shortLink fullLink bob
+ settleTeamJoin alice cath bob
bob ##> "/_verify domain #1"
bob <## "SimpleX name #team verified"
pure shortLink
+settleTeamJoin :: HasCallStack => TestCC -> TestCC -> TestCC -> IO ()
+settleTeamJoin alice cath bob = do
+ alice #> "#team hi"
+ cath <# "#team> hi"
+ bob <# "#team> hi [>>]"
+ waitQueuedLinkUpdates alice
+
knownGroupPlan :: HasCallStack => String -> String -> TestCC -> IO ()
knownGroupPlan g name cc = do
cc <## ("group link: known group #" <> g)
@@ -1099,6 +1108,7 @@ withTeamChats test = withChannelChats $ \reg alice cath bob -> do
alice <## "new contact address set"
connectBobByName "@team.simplex" alice bob
joinChannelByName "team" alice cath bob
+ settleTeamJoin alice cath bob
test reg contactLink channelLink alice bob
testNameRecordOrWarning :: IO ()
diff --git a/tests/fixtures/api/names/plan-known-failed.json b/tests/fixtures/api/names/plan-known-failed.json
index d353142e9e..7a2872e115 100644
--- a/tests/fixtures/api/names/plan-known-failed.json
+++ b/tests/fixtures/api/names/plan-known-failed.json
@@ -161,6 +161,7 @@
"connShortLink": "connShortLink"
}
},
+ "rosterVersion": 0,
"updatedAt": "1970-01-01T00:00:00Z",
"useRelays": true,
"userMemberProfileSentAt": "1970-01-01T00:00:00Z",
diff --git a/tests/fixtures/api/names/search-team.json b/tests/fixtures/api/names/search-team.json
index 4a323cd752..84fc33d23a 100644
--- a/tests/fixtures/api/names/search-team.json
+++ b/tests/fixtures/api/names/search-team.json
@@ -89,7 +89,7 @@
}
},
"groupSummary": {
- "currentMembers": 2,
+ "currentMembers": 3,
"publicMemberCount": 1
},
"localAlias": "",
@@ -161,6 +161,7 @@
"connShortLink": "connShortLink"
}
},
+ "rosterVersion": 0,
"updatedAt": "1970-01-01T00:00:00Z",
"useRelays": true,
"userMemberProfileSentAt": "1970-01-01T00:00:00Z",
From 1966ac32e3f316acb66d8b928d680f4f12782ce5 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Fri, 20 Nov 2026 12:28:26 +0000
Subject: [PATCH 10/20] core, ci: update sqlcipher-simple to 0.4.19.0 and
simplexmq (#8270)
* update sqlcipher-simple to 0.4.19.0
* sqlcipher-simple from simplex-chat/sqlcipher-simple
* update simplexmq
* ci: restore source repositories only for the same cabal.project
* ci: keep restored source checkouts only at their pinned commits
---
cabal.project | 4 ++--
scripts/ci/prune-old-builds.sh | 7 +++++++
scripts/nix/sha256map.nix | 4 ++--
3 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/cabal.project b/cabal.project
index 8b9737a40e..7c7fe8ac23 100644
--- a/cabal.project
+++ b/cabal.project
@@ -21,7 +21,7 @@ constraints: zip +disable-bzip2 +disable-zstd
source-repository-package
type: git
location: https://github.com/simplex-chat/simplexmq.git
- tag: fdbcb24d86460977382e1237591cd505c3b37fa1
+ tag: d38bcf50131d59f027d170731e4ea22031650611
source-repository-package
type: git
@@ -36,7 +36,7 @@ source-repository-package
source-repository-package
type: git
location: https://github.com/simplex-chat/sqlcipher-simple.git
- tag: a46bd361a19376c5211f1058908fc0ae6bf42446
+ tag: 6bf2796de625dca678c70e98560010c6ec7ed635
source-repository-package
type: git
diff --git a/scripts/ci/prune-old-builds.sh b/scripts/ci/prune-old-builds.sh
index 520fb6bf45..f2a7b88f4b 100755
--- a/scripts/ci/prune-old-builds.sh
+++ b/scripts/ci/prune-old-builds.sh
@@ -6,4 +6,11 @@ for dir in "$@"; do
if [ -d "$dir/build" ]; then
find "$dir/build" -mindepth 3 -maxdepth 3 -type d -name 'simplex-chat-*' ! -name "simplex-chat-$version" -exec rm -rf {} +
fi
+ for src in "$dir"/src/*/; do
+ [ -e "$src.git" ] || continue
+ rev=$(git -C "$src" rev-parse HEAD 2>/dev/null || true)
+ if [ -z "$rev" ] || ! grep -q "tag: $rev" cabal.project; then
+ rm -rf "$src"
+ fi
+ done
done
diff --git a/scripts/nix/sha256map.nix b/scripts/nix/sha256map.nix
index 3db71b94b7..3b9632effe 100644
--- a/scripts/nix/sha256map.nix
+++ b/scripts/nix/sha256map.nix
@@ -1,8 +1,8 @@
{
- "https://github.com/simplex-chat/simplexmq.git"."fdbcb24d86460977382e1237591cd505c3b37fa1" = "0w384jwxfaw8n7fvcc55c8076dpiclb29vgmh7vdzhwyz20grk44";
+ "https://github.com/simplex-chat/simplexmq.git"."d38bcf50131d59f027d170731e4ea22031650611" = "1qd18bqg6zji5s6rcaw63rdbyj82sc5jn1apfq2pbkxs9cybwjyy";
"https://github.com/simplex-chat/hs-socks.git"."a30cc7a79a08d8108316094f8f2f82a0c5e1ac51" = "0yasvnr7g91k76mjkamvzab2kvlb1g5pspjyjn2fr6v83swjhj38";
"https://github.com/simplex-chat/direct-sqlcipher.git"."2330df3dc8c4b660674d3c02d76bb86f66c2abee" = "11pfj1vqsjdl26nplkr2l6z1xj7cn153qijj5gknmlzq3krn7x1i";
- "https://github.com/simplex-chat/sqlcipher-simple.git"."a46bd361a19376c5211f1058908fc0ae6bf42446" = "1z0r78d8f0812kxbgsm735qf6xx8lvaz27k1a0b4a2m0sshpd5gl";
+ "https://github.com/simplex-chat/sqlcipher-simple.git"."6bf2796de625dca678c70e98560010c6ec7ed635" = "0mgkm2d6c4vsv689niy2fi0q58pk13mpvm4idzmn0vhwyi2wmv1g";
"https://github.com/simplex-chat/aeson.git"."aab7b5a14d6c5ea64c64dcaee418de1bb00dcc2b" = "0jz7kda8gai893vyvj96fy962ncv8dcsx71fbddyy8zrvc88jfrr";
"https://github.com/simplex-chat/haskell-terminal.git"."f708b00009b54890172068f168bf98508ffcd495" = "0zmq7lmfsk8m340g47g5963yba7i88n4afa6z93sg9px5jv1mijj";
"https://github.com/simplex-chat/android-support.git"."9aa09f148089d6752ce563b14c2df1895718d806" = "0pbf2pf13v2kjzi397nr13f1h3jv0imvsq8rpiyy2qyx5vd50pqn";
From d08e249ea56a96560d0aafa278c3ca9d648fc1cb Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Fri, 20 Nov 2026 12:29:04 +0000
Subject: [PATCH 11/20] android, desktop, ios: copy markdown files with line
breaks, and the whole file with one button (#8269)
* android, desktop: test copying lines from the markdown text view
* android, desktop: keep line breaks in text copied from markdown files
* android, desktop: check the last copied text in the markdown view test
* android, desktop, ios: button to copy the whole markdown file
* android, desktop: test the markdown file copy button
* android, desktop, ios: ask before copying markdown files over 128 KB
* android, desktop, ios: title the markdown copy alerts File too large
* ios: test the markdown file copy button
* android, desktop, ios: preview the markdown file view and test the copy limit
* android, desktop, ios: snapshot references of the markdown file view
---
.../Chat/ChatItem/MarkdownFileView.swift | 43 +++++-
.../MarkdownFileView-dark-large.png | Bin 0 -> 18217 bytes
.../MarkdownFileView-light-large.png | Bin 0 -> 20769 bytes
.../ios/SimpleX Snapshots/SnapshotTests.swift | 1 +
.../MarkdownFileTests.swift | 26 ++++
apps/ios/SimpleX.xcodeproj/project.pbxproj | 4 +
.../views/chat/item/MarkdownFileView.kt | 98 +++++++++++--
.../moko-resources/base/strings.xml | 3 +
.../chat/simplex/app/MarkdownFileViewTest.kt | 134 ++++++++++++++++++
.../kotlin/chat/simplex/app/SnapshotTest.kt | 1 +
....PreviewMarkdownFileView-dark-font-100.png | Bin 0 -> 17560 bytes
...PreviewMarkdownFileView-light-font-100.png | Bin 0 -> 16070 bytes
12 files changed, 294 insertions(+), 16 deletions(-)
create mode 100644 apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png
create mode 100644 apps/ios/SimpleX Snapshots/References/MarkdownFileView-light-large.png
create mode 100644 apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift
create mode 100644 apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt
create mode 100644 apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png
create mode 100644 apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift
index 555ff9d429..508606e124 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift
@@ -3,6 +3,7 @@ import SimpleXChat
import Ink
private let MAX_MARKDOWN_VIEW_SIZE: Int64 = 1_048_576
+private let MAX_MARKDOWN_COPY_SIZE: Int64 = 131_072
private let MAX_MARKDOWN_LINE_LENGTH = 15_000
private let MAX_MARKDOWN_NESTING = 16
private let MAX_MARKDOWN_LINK_NESTING = 4
@@ -27,7 +28,7 @@ func showMarkdownFile(_ file: CIFile) {
let hasBidiControls = text.unicodeScalars.contains(where: isBidiControl)
await MainActor.run {
showAppSheet {
- MarkdownFileView(file: file, fileSource: fileSource, lines: shownLines, html: html, hasBidiControls: hasBidiControls)
+ MarkdownFileView(file: file, fileSource: fileSource, text: text, lines: shownLines, html: html, hasBidiControls: hasBidiControls)
}
}
} catch {
@@ -166,10 +167,31 @@ private func openMarkdownFileLink(_ url: URL) {
}
}
+func copyMarkdownFile(_ file: CIFile, _ text: String) {
+ if file.fileSize > MAX_MARKDOWN_COPY_SIZE {
+ showAlert(
+ NSLocalizedString("File too large", comment: "alert title"),
+ message: String.localizedStringWithFormat(
+ NSLocalizedString("Your file is %@. Do you want to copy it?", comment: "alert message"),
+ ByteCountFormatter.string(fromByteCount: file.fileSize, countStyle: .binary)
+ ),
+ actions: {[
+ cancelAlertAction,
+ UIAlertAction(title: NSLocalizedString("Copy", comment: "alert button"), style: .default) { _ in
+ UIPasteboard.general.string = text
+ }
+ ]}
+ )
+ } else {
+ UIPasteboard.general.string = text
+ }
+}
+
struct MarkdownFileView: View {
@AppStorage(DEFAULT_MARKDOWN_FILE_TEXT_VIEW) private var textView = false
let file: CIFile
let fileSource: CryptoFile
+ let text: String
let lines: [String]
let html: String?
let hasBidiControls: Bool
@@ -203,6 +225,11 @@ struct MarkdownFileView: View {
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
+ Button {
+ copyMarkdownFile(file, text)
+ } label: {
+ Image(systemName: "doc.on.doc")
+ }
if html != nil {
Button {
textView.toggle()
@@ -221,3 +248,17 @@ struct MarkdownFileView: View {
.navigationViewStyle(.stack)
}
}
+
+struct MarkdownFileView_Previews: PreviewProvider {
+ static var previews: some View {
+ let text = "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n"
+ MarkdownFileView(
+ file: CIFile.getSample(fileName: "notes.md", fileSize: Int64(text.utf8.count), filePath: "notes.md"),
+ fileSource: CryptoFile.plain("notes.md"),
+ text: text,
+ lines: text.components(separatedBy: "\n"),
+ html: nil,
+ hasBidiControls: false
+ )
+ }
+}
diff --git a/apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png b/apps/ios/SimpleX Snapshots/References/MarkdownFileView-dark-large.png
new file mode 100644
index 0000000000000000000000000000000000000000..a9969a11869059f0347ea6f46ac1d55c1443b57c
GIT binary patch
literal 18217
zcmeIaWmp_t_wI>9;?UFFL4?86P^Lf?(9nuQ6QqD~o<@{PK_LW^O4{!^)p|(WvqBZ@F&01g>oEPb*uh`GPUQk
z_VYgVP@?ae^!op(6btw~P2>vZs)Z7JT1;?}1~^eMdp|fR^x?6YIVhz3zTrKon6J`n
zH|!6ICg3`|o)&!H4*lf&_Gtd*d$(e4JRC#WZM)i(^tq83-lqHY?l8yeOwVooc7!~Z
z|J%UTj3~;wLqAeOS1$|!=GSi1gnZFZCkyk*4A+y&<``TSql1a`myV-?NHY90eggXr
z#}_;dw>3vtO7rQQ$xRxaOq;sV!dL+r1csIl+7RgWe9;^GFsJ6WOU_j=0`*-}pE&;y=-(*@iygWka7
z`4an+4K*A#LO})N7pYM8{cE7*5{`s{%w}t+nPsnwPz|>K5(S>T+`u_Ip
zb$1#r>|cB0KS*q7rYpA?k_v`m4HaT(IDv>xtDD^XiV-fJ1#-(qv2Ug{k
zA+ouyuvCF9df%a1`kwFpdRQ4MU0Go9kq%*Nq|>ghDnqDzxgsj8gT!gDO4&-=f2U+h*Wg
z@ad=!HD@BBvL(C@OF4}O0V30`?Xx)(r1!FLB9;73(I93)zG-6ROuu%cmCr>ltb1hE
z0(X#kt`Da=t|2N!iU&-;ZN6y4ouU9!O&`
z9@)-G#2L$W+Zg=~iNeoZq1JSz!dfo}VxF7yh*X>F^6~0ZTvpFYgu{+zjJ0u;?RtAU
zVQSq&k0L6o)NAMTO9vC4a$VBX==8ib`finOdU7?+H2m9$@IAx2%5u5Jkj1ug&UA|R
zg#Ju5ZNR?k@c?MkwPINu1qfs{|2`y!p8Ezz96;TA|>1fBMz-V&%nm$l-(Li5=@Z;t4yS|C`86U7;A0#PwA`L0ID
z(*+G}%B6nGMzCZBaH8F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^TlUDhbS-6+y&n>u34%M84=|}M@y8H`
zSaQ%%s8J^pieFDDIwj!{7Nwt2+%+J}<+w_?DoAV4heu_{_^B_oZV4%$Z#35qJbp6Syj&
zF_uF~>%1&3k0})##{STlTdOech6#LE`=Ve7L_krut9|pRRqi)mHug%y#x;_u|HI#-
zKB3#952h=)M_r!{^J8(Y#zi`f+<7s34>a|Z;hV_@4B$D6Yw$eA@3p!opjiNxKNU>f
zEd>u7vVmSoOQtoTDFL3oka*w>6vvS&=oQ!I0UovR9KK*bb^qK{FS;EkmI=c+&BbgB^X+`?MJ}Wxzrz*-{e?@NkC`=oQ{l
zV+NZ4o$P-j``=~o-wpO(H25#h{=b|QWX84)!Jj;Ey8T-K|7ElPQty9I^ZyZnMg7Ca
z!1(v?9XYHN1A`><_I}&{f=LM4SUtZ)_Wk9TD2MdhWwCGw%5a3=m|1|vDC90CCYBgx
z6HN%L1&078#KNx3&TEHoxI>kLf!S1!jYH6fGitVHzfQ?+hjxD(iJa`dN8}F|k~9@d?P|31J`R
zd;55lyCFLm|Gnvd!~5Tb^xrM>UvT&@_WqY;{>!KTk;8wC^dEx$?+x2WRGS|Qo~p&)
R{ [SnapshotScene] {
SnapshotScene(IntegrityErrorItemView_Previews.self, allSizes: true),
SnapshotScene(LargeLinkPreview_Previews.self, allSizes: true),
SnapshotScene(LocalAuthView_Previews.self),
+ SnapshotScene(MarkdownFileView_Previews.self, device: true),
SnapshotScene(MarkdownHelp_Previews.self),
SnapshotScene(MarkedDeletedItemView_Previews.self, allSizes: true),
SnapshotScene(MemberAdmissionView_Previews.self),
diff --git a/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift b/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift
new file mode 100644
index 0000000000..92e931f3e5
--- /dev/null
+++ b/apps/ios/SimpleX Unit Tests/MarkdownFileTests.swift
@@ -0,0 +1,26 @@
+import XCTest
+import UIKit
+@testable import SimpleX
+@testable import SimpleXChat
+
+final class MarkdownFileTests: XCTestCase {
+ @MainActor
+ func testCopyAsksAbove128KB() async throws {
+ let text = "alpha\n\ngamma"
+ UIPasteboard.general.string = "unchanged"
+ copyMarkdownFile(CIFile.getSample(fileSize: 131_072), text)
+ XCTAssertEqual(UIPasteboard.general.string, text)
+ UIPasteboard.general.string = "unchanged"
+ copyMarkdownFile(CIFile.getSample(fileSize: 131_073), text)
+ try await waitFor { (getTopViewController() as? UIAlertController)?.isBeingPresented == false }
+ let alert = try XCTUnwrap(getTopViewController() as? UIAlertController)
+ XCTAssertEqual(alert.title, "File too large")
+ XCTAssertEqual(alert.message, "Your file is 128 KB. Do you want to copy it?")
+ XCTAssertEqual(UIPasteboard.general.string, "unchanged")
+ let copy = try XCTUnwrap(alert.actions.first { $0.title == "Copy" })
+ let handler = unsafeBitCast(copy.value(forKey: "handler") as AnyObject, to: (@convention(block) (UIAlertAction) -> Void).self)
+ await withCheckedContinuation { done in alert.dismiss(animated: false) { done.resume() } }
+ handler(copy)
+ XCTAssertEqual(UIPasteboard.general.string, text)
+ }
+}
diff --git a/apps/ios/SimpleX.xcodeproj/project.pbxproj b/apps/ios/SimpleX.xcodeproj/project.pbxproj
index 530bc4c124..3242c7ea27 100644
--- a/apps/ios/SimpleX.xcodeproj/project.pbxproj
+++ b/apps/ios/SimpleX.xcodeproj/project.pbxproj
@@ -272,6 +272,7 @@
E5AEC0C22F9C000100270665 /* SnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0C12F9C000100270665 /* SnapshotTests.swift */; };
4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000005 /* NameAlertsTests.swift */; };
4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */; };
+ 6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */; };
E5AEC0AF2F91A73500270665 /* ComposeChatLinkView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */; };
E5C0BBE82F82B45500EA7527 /* SimpleXAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */; };
E5C0BBEB2F82B45500EA7527 /* SharedAssets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E5C0BBEA2F82B45500EA7527 /* SharedAssets.xcassets */; };
@@ -684,6 +685,7 @@
E5AEC0C32F9C000100270665 /* SimpleX Snapshots.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Snapshots.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
4E57A1E70000000000000005 /* NameAlertsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NameAlertsTests.swift; sourceTree = ""; };
4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatItemUpdateTests.swift; sourceTree = ""; };
+ 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownFileTests.swift; sourceTree = ""; };
4E57A1E70000000000000007 /* SimpleX Unit Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "SimpleX Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
E5AEC0AE2F91A73500270665 /* ComposeChatLinkView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeChatLinkView.swift; sourceTree = ""; };
E5C0BBE72F82B45500EA7527 /* SimpleXAssets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = SimpleXAssets.xcassets; sourceTree = ""; };
@@ -1038,6 +1040,7 @@
children = (
4E57A1E70000000000000005 /* NameAlertsTests.swift */,
4E57A1E70000000000000013 /* ChatItemUpdateTests.swift */,
+ 6D4F1C2A9B3E000000000001 /* MarkdownFileTests.swift */,
);
path = "SimpleX Unit Tests";
sourceTree = "";
@@ -1926,6 +1929,7 @@
files = (
4E57A1E70000000000000006 /* NameAlertsTests.swift in Sources */,
4E57A1E70000000000000014 /* ChatItemUpdateTests.swift in Sources */,
+ 6D4F1C2A9B3E000000000002 /* MarkdownFileTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
diff --git a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt
index a763e47d43..7681120144 100644
--- a/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt
+++ b/apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/views/chat/item/MarkdownFileView.kt
@@ -1,18 +1,22 @@
package chat.simplex.common.views.chat.item
import SectionBottomSpacer
+import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.*
import androidx.compose.runtime.*
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.painter.BitmapPainter
+import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.platform.UriHandler
+import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
@@ -25,6 +29,7 @@ import chat.simplex.common.model.*
import chat.simplex.common.model.ChatController.appPrefs
import chat.simplex.common.platform.*
import chat.simplex.common.ui.theme.DEFAULT_PADDING
+import chat.simplex.common.ui.theme.SimpleXTheme
import chat.simplex.common.ui.theme.WarningOrange
import chat.simplex.common.views.chat.topPaddingToContent
import chat.simplex.common.views.helpers.*
@@ -41,6 +46,7 @@ import dev.icerock.moko.resources.compose.painterResource
import dev.icerock.moko.resources.compose.stringResource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.ast.ASTNode
@@ -56,6 +62,8 @@ import java.util.Base64
private const val DATA_IMAGE = "data:image/"
private val IMAGE_TYPES = listOf(ImageFileType.JPEG, ImageFileType.PNG)
private const val MAX_MARKDOWN_VIEW_SIZE: Long = 1_048_576
+private const val MAX_MARKDOWN_COPY_SIZE = 131_072
+private const val MAX_ANDROID_COPY_SIZE = 524_288
private const val MAX_MARKDOWN_LINE_LENGTH = 15_000
private const val MAX_MARKDOWN_DEPTH = 32
private const val MAX_MARKDOWN_TABLE_ROWS = 200
@@ -67,7 +75,9 @@ private val bidiControlChar = Regex("[\\u061C\\u200E\\u200F\\u202A-\\u202E\\u206
private val invisibleCharMarkerStyle = SpanStyle(color = WarningOrange)
-private class MarkdownDocument(val lines: List, val formatted: State.Success?, val hasBidiControls: Boolean)
+internal class MarkdownLine(val text: String, val lineBreak: Boolean)
+
+internal class MarkdownDocument(val text: String, val lines: List, val formatted: State.Success?, val hasBidiControls: Boolean)
fun isMarkdownFile(file: CIFile): Boolean =
file.fileSize <= MAX_MARKDOWN_VIEW_SIZE && file.fileName.substringAfterLast('.', "").lowercase() in listOf("md", "markdown")
@@ -90,26 +100,31 @@ fun showMarkdownFile(file: CIFile) {
AlertManager.shared.showAlertMsg(generalGetString(MR.strings.error), e.message)
return@withLongRunningApi
}
- val text = decodedText(bytes)
- val lines = text.lines()
- val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null
- val document = MarkdownDocument(
- lines.flatMap { line -> line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") } },
- formatted,
- bidiControlChar.containsMatchIn(text)
- )
+ val document = markdownDocument(bytes)
withContext(Dispatchers.Main) {
if (appPlatform.isDesktop && ModalManager.center.isTopModalOpen(ModalViewId.MARKDOWN_FILE)) ModalManager.center.closeModal()
- ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = {
- if (formatted != null) MarkdownViewSwitch()
- MarkdownFileSaveButton(file, bytes)
- }) {
+ ModalManager.center.showModal(id = ModalViewId.MARKDOWN_FILE, endButtons = { MarkdownFileButtons(file, bytes, document) }) {
key(this) { MarkdownFileView(file.fileName, document) }
}
}
}
}
+internal suspend fun markdownDocument(bytes: ByteArray): MarkdownDocument {
+ val text = decodedText(bytes)
+ val lines = text.lines()
+ val formatted = if (lines.all { it.length <= MAX_MARKDOWN_LINE_LENGTH }) formattedWithinLimits(text) else null
+ return MarkdownDocument(
+ text,
+ lines.flatMapIndexed { i, line ->
+ val chunks = line.chunked(MAX_MARKDOWN_LINE_LENGTH).ifEmpty { listOf("") }
+ chunks.mapIndexed { j, chunk -> MarkdownLine(chunk, lineBreak = i < lines.lastIndex && j == chunks.lastIndex) }
+ },
+ formatted,
+ bidiControlChar.containsMatchIn(text)
+ )
+}
+
private fun decodedText(bytes: ByteArray): String =
Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
@@ -145,6 +160,39 @@ private fun MarkdownViewSwitch() {
}
}
+@Composable
+private fun MarkdownFileButtons(file: CIFile, bytes: ByteArray, document: MarkdownDocument) {
+ MarkdownFileCopyButton(document.text, bytes.size, if (appPlatform.isAndroid) MAX_ANDROID_COPY_SIZE else null)
+ if (document.formatted != null) MarkdownViewSwitch()
+ MarkdownFileSaveButton(file, bytes)
+}
+
+@Composable
+internal fun MarkdownFileCopyButton(text: String, fileSize: Int, maxSize: Int?) {
+ val clipboard = LocalClipboardManager.current
+ IconButton({
+ val copy = {
+ clipboard.setText(AnnotatedString(text))
+ showToast(generalGetString(MR.strings.copied))
+ }
+ when {
+ maxSize != null && fileSize > maxSize -> AlertManager.shared.showAlertMsg(
+ generalGetString(MR.strings.markdown_file_too_large),
+ String.format(generalGetString(MR.strings.markdown_file_copy_limit), formatBytes(maxSize.toLong()))
+ )
+ fileSize > MAX_MARKDOWN_COPY_SIZE -> AlertManager.shared.showAlertDialog(
+ title = generalGetString(MR.strings.markdown_file_too_large),
+ text = String.format(generalGetString(MR.strings.markdown_file_copy_large), formatBytes(fileSize.toLong())),
+ confirmText = generalGetString(MR.strings.copy_verb),
+ onConfirm = copy
+ )
+ else -> copy()
+ }
+ }) {
+ Icon(painterResource(MR.images.ic_content_copy), stringResource(MR.strings.copy_verb), tint = MaterialTheme.colors.primary)
+ }
+}
+
@Composable
private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) {
val saveFileLauncher = rememberFileChooserLauncher(false, bytes) { to: URI? ->
@@ -156,14 +204,17 @@ private fun MarkdownFileSaveButton(file: CIFile, bytes: ByteArray) {
}
@Composable
-private fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
+internal fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
val textView = remember { appPrefs.markdownFileTextView.state }
val formatted = document.formatted
if (textView.value || formatted == null) {
SelectionContainer {
MarkdownFileColumn(fileName, document.hasBidiControls) {
items(document.lines) { line ->
- Text(remember(line) { withInvisibleCharMarkers(line) }, Modifier.padding(horizontal = DEFAULT_PADDING), fontFamily = FontFamily.Monospace)
+ Box(Modifier.padding(horizontal = DEFAULT_PADDING)) {
+ Text(remember(line) { withInvisibleCharMarkers(line.text) }, fontFamily = FontFamily.Monospace)
+ if (line.lineBreak) SelectableLineBreak()
+ }
}
}
}
@@ -172,6 +223,11 @@ private fun MarkdownFileView(fileName: String, document: MarkdownDocument) {
}
}
+@Composable
+private fun BoxScope.SelectableLineBreak() {
+ Text("\n", Modifier.align(Alignment.BottomEnd).height(1.dp).clearAndSetSemantics {})
+}
+
private fun withInvisibleCharMarkers(line: String): AnnotatedString = buildAnnotatedString {
var start = 0
invisibleChar.findAll(line).forEach {
@@ -294,3 +350,15 @@ private fun hasImageSignature(base64: String): Boolean {
val header = runCatching { Base64.getDecoder().decode(base64.take(12)) }.getOrNull() ?: return false
return IMAGE_TYPES.any { it.matches(header) }
}
+
+@Preview
+@Composable
+fun PreviewMarkdownFileView() {
+ val bytes = remember { "# Release notes\n\n- markdown files in chats\n- a button to copy the file\n".encodeToByteArray() }
+ val document = remember { runBlocking { markdownDocument(bytes) } }
+ SimpleXTheme {
+ ModalView(close = {}, endButtons = { MarkdownFileButtons(CIFile.getSample(fileName = "notes.md"), bytes, document) }) {
+ MarkdownFileView("notes.md", document)
+ }
+ }
+}
diff --git a/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml b/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml
index af5b3a089d..27cf5f7f17 100644
--- a/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml
+++ b/apps/multiplatform/common/src/commonMain/moko-resources/base/strings.xml
@@ -721,6 +721,9 @@
Formatted view
Text view
This file has text direction characters. The text can be shown in a different order than it is written.
+ File too large
+ Only files up to %s can be copied. Save the file to open it in another app.
+ Your file is %s. Do you want to copy it?
Loading the file
Please, wait while the file is being loaded from the linked mobile
File error
diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt
new file mode 100644
index 0000000000..14bb297d90
--- /dev/null
+++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/MarkdownFileViewTest.kt
@@ -0,0 +1,134 @@
+package chat.simplex.app
+
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.key.Key
+import androidx.compose.ui.platform.ClipEntry
+import androidx.compose.ui.platform.Clipboard
+import androidx.compose.ui.platform.ClipboardManager
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.platform.NativeClipboard
+import androidx.compose.ui.test.ExperimentalTestApi
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.onRoot
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performKeyInput
+import androidx.compose.ui.test.performMouseInput
+import androidx.compose.ui.test.pressKey
+import androidx.compose.ui.test.runComposeUiTest
+import androidx.compose.ui.text.AnnotatedString
+import chat.simplex.common.model.ChatController.appPrefs
+import chat.simplex.common.simplexWindowState
+import chat.simplex.common.views.chat.item.MarkdownFileCopyButton
+import chat.simplex.common.views.chat.item.MarkdownFileView
+import chat.simplex.common.views.chat.item.markdownDocument
+import chat.simplex.common.views.helpers.AlertManager
+import chat.simplex.common.views.helpers.LocalAppBarHandler
+import chat.simplex.common.views.helpers.rememberAppBarHandler
+import kotlinx.coroutines.runBlocking
+import java.awt.datatransfer.DataFlavor
+import java.awt.datatransfer.Transferable
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+
+@OptIn(ExperimentalTestApi::class)
+class MarkdownFileViewTest {
+ @Test
+ fun copiedSelectionKeepsLineBreaks() = runComposeUiTest {
+ val textView = appPrefs.markdownFileTextView.get()
+ appPrefs.markdownFileTextView.set(true)
+ try {
+ val clipboard = RecordingClipboard()
+ val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) }
+ setContent {
+ CompositionLocalProvider(LocalClipboard provides clipboard, LocalAppBarHandler provides rememberAppBarHandler()) {
+ MarkdownFileView("test.md", document)
+ }
+ }
+ val first = onNodeWithText("alpha").fetchSemanticsNode().boundsInRoot
+ val last = onNodeWithText("gamma").fetchSemanticsNode().boundsInRoot
+ onRoot().performMouseInput {
+ moveTo(Offset(first.left + 1f, first.center.y))
+ press()
+ moveTo(Offset(last.right + 10f, last.center.y))
+ release()
+ }
+ onRoot().performKeyInput { pressKey(Key.Copy) }
+ waitForIdle()
+ assertEquals("alpha\n\ngamma", clipboard.text)
+ } finally {
+ appPrefs.markdownFileTextView.set(textView)
+ }
+ }
+
+ @Test
+ fun copyButtonWarnsAbove128KB() = runComposeUiTest {
+ var copied: String? = null
+ val clipboard = object : ClipboardManager {
+ override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text }
+ override fun getText(): AnnotatedString? = null
+ }
+ val document = runBlocking { markdownDocument("alpha\n\ngamma".toByteArray()) }
+ var fileSize by mutableStateOf(131_072)
+ try {
+ setContent {
+ CompositionLocalProvider(LocalClipboardManager provides clipboard) {
+ MarkdownFileCopyButton(document.text, fileSize, null)
+ }
+ AlertManager.shared.showInView()
+ }
+ onNodeWithContentDescription("Copy").performClick()
+ assertEquals("alpha\n\ngamma", copied)
+ copied = null
+ fileSize = 131_073
+ onNodeWithContentDescription("Copy").performClick()
+ onNodeWithText("Your file is 128 KB. Do you want to copy it?").assertExists()
+ assertNull(copied)
+ onNodeWithText("Copy").performClick()
+ assertEquals("alpha\n\ngamma", copied)
+ } finally {
+ AlertManager.shared.hideAllAlerts()
+ simplexWindowState.toasts.clear()
+ }
+ }
+
+ @Test
+ fun copyButtonRefusesAboveHardLimit() = runComposeUiTest {
+ var copied: String? = null
+ val clipboard = object : ClipboardManager {
+ override fun setText(annotatedString: AnnotatedString) { copied = annotatedString.text }
+ override fun getText(): AnnotatedString? = null
+ }
+ try {
+ setContent {
+ CompositionLocalProvider(LocalClipboardManager provides clipboard) {
+ MarkdownFileCopyButton("alpha", 524_289, 524_288)
+ }
+ AlertManager.shared.showInView()
+ }
+ onNodeWithContentDescription("Copy").performClick()
+ onNodeWithText("Only files up to 512 KB can be copied. Save the file to open it in another app.").assertExists()
+ assertNull(copied)
+ } finally {
+ AlertManager.shared.hideAllAlerts()
+ }
+ }
+}
+
+private class RecordingClipboard : Clipboard {
+ var text: String? = null
+
+ override suspend fun getClipEntry(): ClipEntry? = null
+
+ override suspend fun setClipEntry(clipEntry: ClipEntry?) {
+ text = (clipEntry?.nativeClipEntry as Transferable).getTransferData(DataFlavor.stringFlavor) as String
+ }
+
+ override val nativeClipboard: NativeClipboard get() = this
+}
diff --git a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt
index 69c657e2a7..1d4f9c7167 100644
--- a/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt
+++ b/apps/multiplatform/common/src/desktopTest/kotlin/chat/simplex/app/SnapshotTest.kt
@@ -99,6 +99,7 @@ private val previewScenes = listOf(
SnapshotScene("DeletedItemView.PreviewDeletedItemView", chatItemFontScales) { PreviewDeletedItemView() },
SnapshotScene("IntegrityErrorItemView.IntegrityErrorItemViewPreview", chatItemFontScales) { IntegrityErrorItemViewPreview() },
SnapshotScene("MarkedDeletedItemView.PreviewMarkedDeletedItemView", chatItemFontScales) { PreviewMarkedDeletedItemView() },
+ SnapshotScene("MarkdownFileView.PreviewMarkdownFileView") { PreviewMarkdownFileView() },
SnapshotScene("ChatHelpView.PreviewChatHelpLayout") { PreviewChatHelpLayout() },
SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkDirect") { PreviewChatListNavLinkDirect() },
SnapshotScene("ChatListNavLinkView.PreviewChatListNavLinkGroup") { PreviewChatListNavLinkGroup() },
diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-dark-font-100.png
new file mode 100644
index 0000000000000000000000000000000000000000..1e04eb43d51ea82f65c6729fff81e36033ee67cc
GIT binary patch
literal 17560
zcmd6P2UJtrx-M31z_uU?0$Tx*Zl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Yz+w;cwDx0Z<4hA2
z>xb^#CJdzxc_I{hd1kmuZ*%inmjpUT6hG=<-+jgN%rWjgL*`Z%>1xf?i>}!+FTzTs
z$?mq)F~8y{&ZIulo-}J&eZ8DS{P@ou`9CL~zvrbtv(#7WlKcSX2K$LH1_AJ=
QM(9+Pv>p~IJbC#)04b|tZ2$lO
literal 0
HcmV?d00001
diff --git a/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png b/apps/multiplatform/common/src/desktopTest/snapshots/MarkdownFileView.PreviewMarkdownFileView-light-font-100.png
new file mode 100644
index 0000000000000000000000000000000000000000..37b173d0e926a606749b9ce5e4ce328bacb8f2d9
GIT binary patch
literal 16070
zcmeHucT`i`x^L8N-^jKiAfQwg5a~@|D@rd)N7_~dq<4a$L}lCQC3H|Jks?U%L`6Xe
zMF|k;VrU`sP!r1g)*0uVd+vSX{c-L+Z`?87yL*g15Y5V(^PAuNwYk=_>w4-e2RII(
zP$(8njjIMI)Q)HrYM0Z#J@7a9fi^t+_{IB*rqMq5FL2+Trzq5El;+jTM*e*>gZKP(
zR)01vbUeNKwv3G}$Beh<=0k&PhyOgH_4Q`|`Byz#eRFRgF2ln-Bpq*wn9tF;l}$|AC25CtdGB!@uOUf?#J*5*H56*#
zbzuHZ6za?l)Ne=r{$t;M)cr^l>aRb3*Fd5E`~~&bAE+xkQK$J)fBW$dSN-)n{uLL`
zDy^IEuCxf+2$Axs^EI>Kp<=DfWl?9UUR)K>I2c@dDDV1JOt~`Q6pYI2X!MIt=l-`1
zfyARnP+vsDqy9ef*&Fx#Lix9A406|J{K}4Wew&!yKBOd|JIFVqEc)3J_k37r9T$_9
zBec8g%izXQ!%Tsw&Xx>=HFN5;bo0p^mowB?dov5VGliTr9}QUPZ%^_%T7=S=e(5-u
zxeY&NO|Su-P{qCaq@=Spq_g~JXVEWI%yXmqcS}Du4dR_vNbK5PZnzZhC$UwgND7CLbX}5-2&)}+Iy~{Q6}5`ZNJ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