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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
* Fixed members of an iMessage group who never post not appearing in the
Matrix room. Every live group message now joins the members on Apple's
roster.
* Fixed an iMessage group created before its members were known staying named
"Group Chat". Unnamed groups are named after their members, locally only,
and the name follows roster and contact changes.
* Fixed group ghosts being removed from a room whose stored roster was unknown.
* Fixed starting a chat through the provisioning API with a bare phone number
or email (no `tel:` or `mailto:`) failing with IDS error 6001.
Expand Down
5 changes: 5 additions & 0 deletions docs/bridge-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@ groups cannot: their rooms refuse these changes.
group when you send the first message in the new room.
- **Rename.** Change the room name. The group is renamed for everyone. A group
name cannot be cleared from Matrix.
- **Unnamed groups.** A group nobody has named gets a room name built from its
members' contact names, which follows later roster and contact changes.
That name exists only on your homeserver; it is not sent to the group. Once
a participant names the group, or you rename the room, that name is used
and the built one is not brought back.
- **Photo.** Change or remove the room avatar. The picture is cropped to a
square and sent as the group photo.
- **Add and remove.** Use the room's own invite and remove on a contact's
Expand Down
34 changes: 24 additions & 10 deletions pkg/connector/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7859,9 +7859,19 @@ func (c *IMClient) GetChatInfo(ctx context.Context, portal *bridgev2.Portal) (*b
// Setting the name here for existing portals would revert correct
// names to stale values from CloudKit or metadata, and produce
// unwanted bridge bot "name changed" events.
// A built name is recorded as the bridge's own (GeneratedName), so
// later contact syncs may replace it; see macoun_group_names.go.
var generatedName *string
if portal.MXID == "" || portal.Name == "" {
groupName, _ := c.resolveGroupName(ctx, portalID)
chatInfo.Name = &groupName
groupName, authoritative := c.resolveGroupName(ctx, portalID)
if groupName != "" {
chatInfo.Name = &groupName
if !authoritative {
generatedName = &groupName
} else {
generatedName = new(string)
}
}
}

// Set group photo from cache or CloudKit.
Expand Down Expand Up @@ -7937,6 +7947,9 @@ func (c *IMClient) GetChatInfo(ctx context.Context, portal *bridgev2.Portal) (*b
return changed
}
}
if generatedName != nil {
chatInfo.ExtraUpdates = recordGeneratedGroupName(*generatedName, chatInfo.ExtraUpdates)
}
} else {
chatInfo.Type = ptr.Ptr(database.RoomTypeDM)
otherUser := makeUserID(portalID)
Expand Down Expand Up @@ -11906,7 +11919,7 @@ func (c *IMClient) makePortalKey(participants []string, groupName *string, sende
// Cache normalized participants in memory so resolveGroupMembers
// can find them immediately. The cloud_chat DB write happens async
// and may not complete before GetChatInfo is called during portal
// creation, which would cause the group name to resolve as "Group Chat".
// creation, which would leave the new room without a name.
if len(participants) > 0 {
normalized := make([]string, 0, len(participants))
for _, p := range participants {
Expand Down Expand Up @@ -12354,15 +12367,14 @@ func (c *IMClient) resolveGroupName(ctx context.Context, portalID string) (name
}

// 3) Build from contact-resolved member names (fallback, non-authoritative)
members := c.resolveGroupMembers(ctx, portalID)
if len(members) == 0 {
return "Group Chat", false
}
return c.buildGroupName(members), false
// With no members known yet there is nothing to name the group by: the
// result is empty and the room stays unnamed until the roster arrives.
return c.buildGroupName(c.resolveGroupMembers(ctx, portalID)), false
}

// buildGroupName creates a human-readable group name from member identifiers
// by resolving contact names where possible, falling back to phone/email.
// It returns "" when no member other than the user is known.
func (c *IMClient) buildGroupName(members []string) string {
var names []string
for _, memberID := range members {
Expand Down Expand Up @@ -12395,7 +12407,7 @@ func (c *IMClient) buildGroupName(members []string) string {
names = append(names, name)
}
if len(names) == 0 {
return "Group Chat"
return ""
}
if len(names) <= 4 {
return strings.Join(names, ", ")
Expand Down Expand Up @@ -14023,7 +14035,9 @@ func (c *IMClient) chatDBInfoToBridgev2(info *imessage.ChatInfo) *bridgev2.ChatI
if displayName == "" {
displayName = c.buildGroupName(info.Members)
}
chatInfo.Name = &displayName
if displayName != "" {
chatInfo.Name = &displayName
}
}

if parsed.IsGroup {
Expand Down
4 changes: 2 additions & 2 deletions pkg/connector/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ func fnRestoreChatFromCloudKit(ce *commands.Event, login *bridgev2.UserLogin, cl
}
}
if len(normalized) > 0 {
if built := client.buildGroupName(normalized); built != "" && built != "Group Chat" {
if built := client.buildGroupName(normalized); built != "" {
name = built
}
}
Expand Down Expand Up @@ -1101,7 +1101,7 @@ func friendlyPortalName(ctx context.Context, bridge *bridgev2.Bridge, client *IM
// For group chats, resolve from cloud store (display_name / contact names).
isGroup := strings.HasPrefix(portalID, "gid:") || strings.Contains(portalID, ",")
if isGroup && client != nil {
if name, _ := client.resolveGroupName(ctx, portalID); name != "" && name != "Group Chat" {
if name, _ := client.resolveGroupName(ctx, portalID); name != "" {
return name
}
}
Expand Down
8 changes: 6 additions & 2 deletions pkg/connector/dbmeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ import (
type PortalMetadata struct {
ThreadID string `json:"thread_id,omitempty"`
SenderGuid string `json:"sender_guid,omitempty"` // Persistent iMessage group UUID
GroupName string `json:"group_name,omitempty"` // iMessage cv_name for outbound routing
IsSms bool `json:"is_sms,omitempty"` // True if this portal routes through SMS
GroupName string `json:"group_name,omitempty"` // iMessage cv_name for outbound routing
IsSms bool `json:"is_sms,omitempty"` // True if this portal routes through SMS
// GeneratedName is the room name the bridge last built from the members
// of an unnamed group. While the room still has it, it is refreshed; see
// macoun_group_names.go. Local to Matrix, never sent to Apple.
GeneratedName string `json:"generated_name,omitempty"`
}

type GhostMetadata struct{}
Expand Down
90 changes: 90 additions & 0 deletions pkg/connector/macoun_group_names.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// macoun-matrix - A Matrix-iMessage puppeting bridge (fork of corten-matrix).
// SPDX-License-Identifier: MPL-2.0
//
// macoun: how the periodic contact sync decides whether a group room's name
// changes. Names the bridge sets are local to the homeserver: bridgev2 drops
// the bridge bot's own m.room.name events before they reach
// HandleMatrixRoomName, so none of this is ever sent to Apple.
//
// A group nobody has named gets a name built from its members ("Sam
// Rivera, Alex Chen"). The bridge records that name in
// PortalMetadata.GeneratedName, and while the room still carries it, later
// syncs replace it as the roster or contact names change. A name a
// participant gives the group, or one the user sets from Matrix, is not the
// recorded name, so it is never overwritten by a built one.

package connector

import (
"context"

"maunium.net/go/mautrix/bridgev2"
)

// groupNamePlaceholder is the name earlier builds gave a group whose members
// were not known yet. A room still called this is treated as unnamed.
const groupNamePlaceholder = "Group Chat"

// planGroupNameRefresh reports what refreshGroupPortalNamesFromContacts does
// with a group portal whose room is called current. newName and
// authoritative are resolveGroupName's results: authoritative is true for a
// name a participant gave the group, false for one built from the members.
// rename means set newName on the room. record means PortalMetadata.
// GeneratedName must be rewritten: to newName when that is a built name, or
// cleared when the group has a participant's name. A room named before
// GeneratedName existed, whose name is exactly what the bridge builds today,
// gets record without rename.
func planGroupNameRefresh(current, newName string, authoritative bool, meta *PortalMetadata) (rename, record bool) {
if newName == "" {
return false, false
}
if newName != current {
if !authoritative && !groupNameIsBridgeBuilt(current, meta) {
// A name someone chose (from Matrix, or a carrier group's
// own name) is not replaced by a built one.
return false, false
}
return true, true
}
want := ""
if !authoritative {
want = newName
}
have := ""
if meta != nil {
have = meta.GeneratedName
}
return false, want != have
}

// groupNameIsBridgeBuilt reports whether a group room's name is one the bridge
// chose itself and may replace: none, the old placeholder, or the name it
// last built.
func groupNameIsBridgeBuilt(current string, meta *PortalMetadata) bool {
if current == "" || current == groupNamePlaceholder {
return true
}
return meta != nil && meta.GeneratedName != "" && current == meta.GeneratedName
}

// recordGeneratedGroupName returns an ExtraUpdates step that stores the name
// the bridge built (or clears the record when the name is a participant's),
// running next after if one is given.
func recordGeneratedGroupName(generated string, next bridgev2.ExtraUpdater[*bridgev2.Portal]) bridgev2.ExtraUpdater[*bridgev2.Portal] {
return func(ctx context.Context, p *bridgev2.Portal) bool {
changed := false
if next != nil {
changed = next(ctx, p)
}
meta, ok := p.Metadata.(*PortalMetadata)
if !ok {
meta = &PortalMetadata{}
}
if meta.GeneratedName != generated {
meta.GeneratedName = generated
p.Metadata = meta
changed = true
}
return changed
}
}
74 changes: 74 additions & 0 deletions pkg/connector/macoun_group_names_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// macoun-matrix - A Matrix-iMessage puppeting bridge (fork of corten-matrix).
// SPDX-License-Identifier: MPL-2.0

package connector

import (
"context"
"testing"

"maunium.net/go/mautrix/bridgev2"
"maunium.net/go/mautrix/bridgev2/database"
)

// A group room created before its members were known was named "Group Chat"
// and kept that name after the roster arrived (seen on a live bridge: a
// three-person iMessage group, named "Group Chat" for months
// while its cloud_chat row lists both other members).
func TestGroupNameRefreshReplacesPlaceholder(t *testing.T) {
rename, record := planGroupNameRefresh("Group Chat", "Sam Rivera, Alex Chen", false, &PortalMetadata{})
if !rename || !record {
t.Fatalf(`placeholder: rename=%v record=%v, want both true`, rename, record)
}
}

// With no members to name the group by, there is no name to give it: the
// room is created unnamed and named once the roster is known.
func TestBuildGroupNameWithoutMembersIsEmpty(t *testing.T) {
if got := (&IMClient{}).buildGroupName(nil); got != "" {
t.Fatalf("buildGroupName(nil) = %q, want empty", got)
}
}

func TestGroupNameRefreshCases(t *testing.T) {
built := &PortalMetadata{GeneratedName: "Alex Chen, Sam Rivera"}
cases := []struct {
name string
current, newName string
authoritative bool
meta *PortalMetadata
wantRename, wantRecord bool
}{
{"unnamed room gets a built name", "", "Alex Chen", false, nil, true, true},
{"built name follows the roster", "Alex Chen, Sam Rivera", "Alex Chen, Sam Rivera, Jo Park", false, built, true, true},
{"name the user chose is kept", "Weekend trip", "Alex Chen, Sam Rivera", false, built, false, false},
{"carrier group's own name is kept", "Book Club", "Alex Chen, Sam Rivera, Jo Park", false, &PortalMetadata{}, false, false},
{"participant's name replaces a chosen one", "Weekend trip", "Book Club", true, nil, true, true},
{"older room already named after its members is recorded", "Alex Chen, Sam Rivera", "Alex Chen, Sam Rivera", false, &PortalMetadata{}, false, true},
{"recorded and unchanged does nothing", "Alex Chen, Sam Rivera", "Alex Chen, Sam Rivera", false, built, false, false},
{"participant names the group as the built name: record cleared", "Alex Chen, Sam Rivera", "Alex Chen, Sam Rivera", true, built, false, true},
{"nothing to build", "Group Chat", "", false, nil, false, false},
}
for _, tc := range cases {
rename, record := planGroupNameRefresh(tc.current, tc.newName, tc.authoritative, tc.meta)
if rename != tc.wantRename || record != tc.wantRecord {
t.Errorf("%s: rename=%v record=%v, want %v %v", tc.name, rename, record, tc.wantRename, tc.wantRecord)
}
}
}

func TestRecordGeneratedGroupNameRunsNextAndStores(t *testing.T) {
ran := false
next := func(context.Context, *bridgev2.Portal) bool { ran = true; return false }
p := &bridgev2.Portal{Portal: &database.Portal{Metadata: &PortalMetadata{SenderGuid: "G"}}}
if !recordGeneratedGroupName("Alex Chen", next)(context.Background(), p) {
t.Fatal("storing a new name should report a change")
}
meta := p.Metadata.(*PortalMetadata)
if !ran || meta.GeneratedName != "Alex Chen" || meta.SenderGuid != "G" {
t.Fatalf("ran=%v meta=%+v", ran, meta)
}
if recordGeneratedGroupName("Alex Chen", nil)(context.Background(), p) {
t.Fatal("storing the same name again should report no change")
}
}
1 change: 1 addition & 0 deletions pkg/connector/macoun_groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,7 @@ func (c *IMClient) CreateGroup(ctx context.Context, params *bridgev2.GroupCreate
// GetChatInfo gives unnamed groups.
if built := c.buildGroupName(participants); built != "" {
info.Name = &built
info.ExtraUpdates = recordGeneratedGroupName(built, info.ExtraUpdates)
}
}
return &bridgev2.CreateChatResponse{PortalKey: portalKey, PortalInfo: info}, nil
Expand Down
45 changes: 25 additions & 20 deletions pkg/connector/sync_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ func (c *IMClient) seedDeletedChatsFromRecycleBin(log zerolog.Logger) {
}
}
if len(normalized) > 0 {
if built := c.buildGroupName(normalized); built != "" && built != "Group Chat" {
if built := c.buildGroupName(normalized); built != "" {
name = built
}
}
Expand Down Expand Up @@ -1738,10 +1738,11 @@ func (c *IMClient) refreshGhostNamesFromContacts(log zerolog.Logger) {
log.Info().Int("reconciled", reconciled).Int("total", len(ghosts)).Msg("Reconciled ghost profiles from contacts")
}

// refreshGroupPortalNamesFromContacts re-resolves group portal names using
// contact data. Portals created before contacts loaded may have raw phone
// numbers / email addresses as the room name. This also picks up contact
// edits on subsequent periodic syncs.
// refreshGroupPortalNamesFromContacts re-resolves group portal names on every
// contact sync. A participant's name for the group replaces whatever the room
// has; a name built from the members replaces only a name the bridge built
// itself, so contact edits and roster changes reach unnamed groups while a
// name the user chose stays (see planGroupNameRefresh).
func (c *IMClient) refreshGroupPortalNamesFromContacts(log zerolog.Logger) {
if c.contacts == nil {
return
Expand All @@ -1768,14 +1769,23 @@ func (c *IMClient) refreshGroupPortalNamesFromContacts(log zerolog.Logger) {
total++

newName, authoritative := c.resolveGroupName(ctx, portalID)
if newName == "" || newName == portal.Name {
meta, _ := portal.Metadata.(*PortalMetadata)
rename, record := planGroupNameRefresh(portal.Name, newName, authoritative, meta)
if !rename && !record {
continue
}
// Don't overwrite an existing portal name with a contact-derived
// fallback — only authoritative sources (user-set iMessage group
// names from the in-memory cache or CloudKit) should rename.
if !authoritative && portal.Name != "" {
continue
info := &bridgev2.ChatInfo{
// Exclude from timeline so Beeper doesn't render
// contact-based name resolution as a bridge bot message.
ExcludeChangesFromTimeline: true,
}
generated := ""
if !authoritative {
generated = newName
}
info.ExtraUpdates = recordGeneratedGroupName(generated, nil)
if rename {
info.Name = &newName
}

c.UserLogin.QueueRemoteEvent(&simplevent.ChatInfoChange{
Expand All @@ -1789,16 +1799,11 @@ func (c *IMClient) refreshGroupPortalNamesFromContacts(log zerolog.Logger) {
return lc.Str("portal_id", portalID).Str("source", "group_name_refresh")
},
},
ChatInfoChange: &bridgev2.ChatInfoChange{
ChatInfo: &bridgev2.ChatInfo{
Name: &newName,
// Exclude from timeline so Beeper doesn't render
// contact-based name resolution as a bridge bot message.
ExcludeChangesFromTimeline: true,
},
},
ChatInfoChange: &bridgev2.ChatInfoChange{ChatInfo: info},
})
updated++
if rename {
updated++
}
}
log.Info().Int("updated", updated).Int("total_groups", total).Msg("Refreshed group portal names from contacts")
}
Expand Down
Loading