GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix(device): key slot↔companion mapping by full AD JID (#762)
Aldino Kemal0c818797e740
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.goindex cca9c836..2f47fbc4 100644--- a/src/domains/chatstorage/chatstorage.go+++ b/src/domains/chatstorage/chatstorage.go@@ -99,24 +99,29 @@ type MediaInfo struct {}// DeviceRecord tracks a registered device for persistence purposes.+// JID holds the bare-number (NonAD) form used for chat storage partitioning; ADJID+// holds the full companion identity (number:[email protected]) that pins the slot to+// one specific whatsmeow session. ADJID is empty until the first connect after+// pairing (the :NN suffix is only known once the socket authenticates).type DeviceRecord struct {- DeviceID string `db:"device_id"`- DisplayName string `db:"display_name"`- JID string `db:"jid"`- WebhookURL *string `db:"webhook_url"`- WebhookSecret string `db:"webhook_secret"`- WebhookEvents string `db:"webhook_events"`+ DeviceID string `db:"device_id"`+ DisplayName string `db:"display_name"`+ JID string `db:"jid"`+ ADJID string `db:"ad_jid"`+ WebhookURL *string `db:"webhook_url"`+ WebhookSecret string `db:"webhook_secret"`+ WebhookEvents string `db:"webhook_events"`WebhookInsecureSkipVerify bool `db:"webhook_insecure_skip_verify"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}// DeviceWebhookConfig holds the complete webhook configuration for a device.type DeviceWebhookConfig struct {- WebhookURL *string `json:"webhook_url,omitempty"`- WebhookSecret string `json:"webhook_secret,omitempty"`- WebhookEvents string `json:"webhook_events,omitempty"`- WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify,omitempty"`+ WebhookURL *string `json:"webhook_url,omitempty"`+ WebhookSecret string `json:"webhook_secret,omitempty"`+ WebhookEvents string `json:"webhook_events,omitempty"`+ WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify,omitempty"`}// MessageFilter represents query filters for messagesdiff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.goindex 350bfd53..7c7bd1a7 100644--- a/src/domains/chatstorage/interfaces.go+++ b/src/domains/chatstorage/interfaces.go@@ -65,7 +65,9 @@ type IChatStorageRepository interface {SaveDeviceRecord(record *DeviceRecord) errorListDeviceRecords() ([]*DeviceRecord, error)GetDeviceRecord(deviceID string) (*DeviceRecord, error)- // GetDeviceRecordByJID fetches a device record by its JID.+ // GetDeviceRecordByJID fetches a device record by its JID. A full AD JID resolves+ // the exact slot; a bare-number JID resolves only while unambiguous — when several+ // slots share the number it returns nil rather than an arbitrary sibling's record.GetDeviceRecordByJID(jid string) (*DeviceRecord, error)DeleteDeviceRecord(deviceID string) error// SetDeviceWebhookURL sets the webhook URL for a device.diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.goindex b39b14b4..ebb1185d 100644--- a/src/infrastructure/chatstorage/sqlite_repository.go+++ b/src/infrastructure/chatstorage/sqlite_repository.go@@ -1100,9 +1100,9 @@ func (r *SQLiteRepository) SaveDeviceRecord(record *domainChatStorage.DeviceReco// Try update first, then insert if no rows affected (cross-db compatible)result, err := r.db.Exec(`- UPDATE devices SET display_name = ?, jid = ?, updated_at = ?+ UPDATE devices SET display_name = ?, jid = ?, ad_jid = ?, updated_at = ?WHERE device_id = ?- `, record.DisplayName, record.JID, record.UpdatedAt, record.DeviceID)+ `, record.DisplayName, record.JID, record.ADJID, record.UpdatedAt, record.DeviceID)if err != nil {return err}@@ -1110,9 +1110,9 @@ func (r *SQLiteRepository) SaveDeviceRecord(record *domainChatStorage.DeviceRecorowsAffected, _ := result.RowsAffected()if rowsAffected == 0 {_, err = r.db.Exec(`- INSERT INTO devices (device_id, display_name, jid, created_at, updated_at)- VALUES (?, ?, ?, ?, ?)- `, record.DeviceID, record.DisplayName, record.JID, record.CreatedAt, record.UpdatedAt)+ INSERT INTO devices (device_id, display_name, jid, ad_jid, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)+ `, record.DeviceID, record.DisplayName, record.JID, record.ADJID, record.CreatedAt, record.UpdatedAt)}return err}@@ -1120,7 +1120,7 @@ func (r *SQLiteRepository) SaveDeviceRecord(record *domainChatStorage.DeviceReco// ListDeviceRecords returns all registered devices.func (r *SQLiteRepository) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {rows, err := r.db.Query(`- SELECT device_id, display_name, jid, created_at, updated_at+ SELECT device_id, display_name, jid, COALESCE(ad_jid, ''), created_at, updated_atFROM devicesORDER BY created_at ASC`)@@ -1132,7 +1132,7 @@ func (r *SQLiteRepository) ListDeviceRecords() ([]*domainChatStorage.DeviceRecorvar records []*domainChatStorage.DeviceRecordfor rows.Next() {var rec domainChatStorage.DeviceRecord- if err := rows.Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.CreatedAt, &rec.UpdatedAt); err != nil {+ if err := rows.Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.ADJID, &rec.CreatedAt, &rec.UpdatedAt); err != nil {return nil, err}records = append(records, &rec)@@ -1149,11 +1149,11 @@ func (r *SQLiteRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.rec := &domainChatStorage.DeviceRecord{}err := r.db.QueryRow(`- SELECT device_id, display_name, jid, created_at, updated_at+ SELECT device_id, display_name, jid, COALESCE(ad_jid, ''), created_at, updated_atFROM devicesWHERE device_id = ?LIMIT 1- `, deviceID).Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.CreatedAt, &rec.UpdatedAt)+ `, deviceID).Scan(&rec.DeviceID, &rec.DisplayName, &rec.JID, &rec.ADJID, &rec.CreatedAt, &rec.UpdatedAt)if err == sql.ErrNoRows {return nil, nil}@@ -1163,36 +1163,59 @@ func (r *SQLiteRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.return rec, nil}-// GetDeviceRecordByJID fetches a device registration by WhatsApp JID.+// GetDeviceRecordByJID fetches a device registration by WhatsApp JID. A full AD JID+// (number:[email protected]) resolves the exact slot. A bare-number JID resolves only+// while it is unambiguous: when several slots share the number (sibling companions,+// issue #760) it returns nil so callers fall back to their global defaults instead of+// acting on an arbitrary sibling's record (e.g. webhook routing).func (r *SQLiteRepository) GetDeviceRecordByJID(jid string) (*domainChatStorage.DeviceRecord, error) {if strings.TrimSpace(jid) == "" {return nil, fmt.Errorf("jid is required")}- rec := &domainChatStorage.DeviceRecord{}- err := r.db.QueryRow(`- SELECT device_id, display_name, jid, webhook_url, COALESCE(webhook_secret, ''), COALESCE(webhook_events, ''), COALESCE(webhook_insecure_skip_verify, FALSE), created_at, updated_at+ rows, err := r.db.Query(`+ SELECT device_id, display_name, jid, COALESCE(ad_jid, ''), webhook_url, COALESCE(webhook_secret, ''), COALESCE(webhook_events, ''), COALESCE(webhook_insecure_skip_verify, FALSE), created_at, updated_atFROM devices- WHERE jid = ?- LIMIT 1- `, jid).Scan(- &rec.DeviceID,- &rec.DisplayName,- &rec.JID,- &rec.WebhookURL,- &rec.WebhookSecret,- &rec.WebhookEvents,- &rec.WebhookInsecureSkipVerify,- &rec.CreatedAt,- &rec.UpdatedAt,- )- if err == sql.ErrNoRows {- return nil, nil- }+ WHERE jid = ? OR ad_jid = ?+ LIMIT 2+ `, jid, jid)if err != nil {return nil, err}- return rec, nil+ defer rows.Close()++ var records []*domainChatStorage.DeviceRecord+ for rows.Next() {+ rec := &domainChatStorage.DeviceRecord{}+ if err := rows.Scan(+ &rec.DeviceID,+ &rec.DisplayName,+ &rec.JID,+ &rec.ADJID,+ &rec.WebhookURL,+ &rec.WebhookSecret,+ &rec.WebhookEvents,+ &rec.WebhookInsecureSkipVerify,+ &rec.CreatedAt,+ &rec.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ records = append(records, rec)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }++ switch len(records) {+ case 0:+ return nil, nil+ case 1:+ return records[0], nil+ default:+ logrus.Warnf("[CHATSTORAGE] %s matches multiple device slots; ignoring device-specific record (use the full AD JID or device id to disambiguate)", jid)+ return nil, nil+ }}// DeleteDeviceRecord removes a device registration entry.@@ -2255,5 +2278,9 @@ func (r *SQLiteRepository) getMigrations() []string {// Migration 34: Store per-device webhook TLS verification override`ALTER TABLE devices ADD COLUMN webhook_insecure_skip_verify BOOLEAN DEFAULT FALSE`,++ // Migration 35: Store the full AD JID (number:[email protected]) per slot so the+ // slot<->companion mapping is precise when several slots share one number (issue #760)+ `ALTER TABLE devices ADD COLUMN ad_jid VARCHAR(255) DEFAULT ''`,}}diff --git a/src/infrastructure/chatstorage/sqlite_repository_device_adjid_test.go b/src/infrastructure/chatstorage/sqlite_repository_device_adjid_test.gonew file mode 100644index 00000000..61e21f23--- /dev/null+++ b/src/infrastructure/chatstorage/sqlite_repository_device_adjid_test.go@@ -0,0 +1,92 @@+package chatstorage++import (+ "testing"++ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+)++// The devices registry must round-trip the full AD JID (number:[email protected]) so+// the device manager can key the slot<->companion mapping precisely (issue #760).+func TestDeviceRecordADJIDRoundTrip(t *testing.T) {+ repo := newTestSQLiteRepository(t)++ adJID := "6281777000020:[email protected]"+ nonAD := "[email protected]"+ if err := repo.SaveDeviceRecord(&domainChatStorage.DeviceRecord{+ DeviceID: "slot-a",+ DisplayName: "Slot A",+ JID: nonAD,+ ADJID: adJID,+ }); err != nil {+ t.Fatalf("save device record: %v", err)+ }++ rec, err := repo.GetDeviceRecord("slot-a")+ if err != nil {+ t.Fatalf("get device record: %v", err)+ }+ if rec == nil || rec.ADJID != adJID {+ t.Fatalf("expected AD JID %q from GetDeviceRecord, got %+v", adJID, rec)+ }++ records, err := repo.ListDeviceRecords()+ if err != nil {+ t.Fatalf("list device records: %v", err)+ }+ if len(records) != 1 || records[0].ADJID != adJID {+ t.Fatalf("expected AD JID %q from ListDeviceRecords, got %+v", adJID, records)+ }++ // Updates must persist a cleared AD JID (logout keeps the slot but wipes identity).+ if err := repo.SaveDeviceRecord(&domainChatStorage.DeviceRecord{+ DeviceID: "slot-a",+ DisplayName: "Slot A",+ JID: "",+ ADJID: "",+ }); err != nil {+ t.Fatalf("update device record: %v", err)+ }+ rec, err = repo.GetDeviceRecord("slot-a")+ if err != nil {+ t.Fatalf("get updated device record: %v", err)+ }+ if rec == nil || rec.ADJID != "" || rec.JID != "" {+ t.Fatalf("expected cleared JIDs after update, got %+v", rec)+ }+}++// When two slots share a bare-number JID (sibling companions, issue #760) the+// JID-based lookup used for per-device webhook routing is ambiguous and must return+// nothing instead of an arbitrary sibling's record; the full AD JID resolves exactly.+func TestGetDeviceRecordByJID_RefusesAmbiguousBareNumberResolvesADJID(t *testing.T) {+ repo := newTestSQLiteRepository(t)++ nonAD := "[email protected]"+ adA := "6281777000021:[email protected]"+ adB := "6281777000021:[email protected]"+ for _, rec := range []*domainChatStorage.DeviceRecord{+ {DeviceID: "slot-a", DisplayName: "A", JID: nonAD, ADJID: adA},+ {DeviceID: "slot-b", DisplayName: "B", JID: nonAD, ADJID: adB},+ } {+ if err := repo.SaveDeviceRecord(rec); err != nil {+ t.Fatalf("save device record %s: %v", rec.DeviceID, err)+ }+ }++ rec, err := repo.GetDeviceRecordByJID(nonAD)+ if err != nil {+ t.Fatalf("ambiguous lookup should not error: %v", err)+ }+ if rec != nil {+ t.Fatalf("expected nil for ambiguous bare-number lookup, got %+v", rec)+ }++ rec, err = repo.GetDeviceRecordByJID(adB)+ if err != nil {+ t.Fatalf("AD JID lookup: %v", err)+ }+ if rec == nil || rec.DeviceID != "slot-b" {+ t.Fatalf("expected slot-b for AD JID lookup, got %+v", rec)+ }+}diff --git a/src/infrastructure/whatsapp/device_instance.go b/src/infrastructure/whatsapp/device_instance.goindex a7581870..28a844aa 100644--- a/src/infrastructure/whatsapp/device_instance.go+++ b/src/infrastructure/whatsapp/device_instance.go@@ -19,7 +19,8 @@ type DeviceInstance struct {state domainDevice.DeviceStatedisplayName stringphoneNumber string- jid string+ jid string // bare-number (NonAD) JID: chat storage / webhook partition key+ adJID string // full AD JID (number:[email protected]): pins the exact companion sessioncreatedAt time.TimeonLoggedOut func(deviceID string) // Callback for remote logout cleanup@@ -31,9 +32,11 @@ type DeviceInstance struct {func NewDeviceInstance(deviceID string, client *whatsmeow.Client, chatStorageRepo domainChatStorage.IChatStorageRepository) *DeviceInstance {jid := ""+ adJID := ""display := ""if client != nil && client.Store != nil && client.Store.ID != nil {jid = client.Store.ID.ToNonAD().String()+ adJID = client.Store.ID.String()display = client.Store.PushName}@@ -44,6 +47,7 @@ func NewDeviceInstance(deviceID string, client *whatsmeow.Client, chatStorageRepstate: domainDevice.DeviceStateDisconnected,displayName: display,jid: jid,+ adJID: adJID,createdAt: time.Now(),}}@@ -94,6 +98,14 @@ func (d *DeviceInstance) JID() string {return d.jid}+// ADJID returns the full companion identity (number:[email protected]), or "" while+// the slot is unpaired / the suffix is not yet known.+func (d *DeviceInstance) ADJID() string {+ d.mu.RLock()+ defer d.mu.RUnlock()+ return d.adJID+}+func (d *DeviceInstance) CreatedAt() time.Time {return d.createdAt}@@ -116,6 +128,7 @@ func (d *DeviceInstance) ResetClient() {defer d.mu.Unlock()d.client = nild.jid = ""+ d.adJID = ""d.phoneNumber = ""d.state = domainDevice.DeviceStateDisconnected}@@ -170,6 +183,7 @@ func (d *DeviceInstance) UpdateStateFromClient() domainDevice.DeviceState {func (d *DeviceInstance) refreshIdentityLocked() {if d.client != nil && d.client.Store != nil && d.client.Store.ID != nil {d.jid = d.client.Store.ID.ToNonAD().String()+ d.adJID = d.client.Store.ID.String()d.displayName = d.client.Store.PushName}}diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.goindex e2cd3f1e..ed22e1f3 100644--- a/src/infrastructure/whatsapp/device_manager.go+++ b/src/infrastructure/whatsapp/device_manager.go@@ -56,6 +56,7 @@ func (m *DeviceManager) AddDevice(instance *DeviceInstance) {DeviceID: instance.ID(),DisplayName: instance.DisplayName(),JID: instance.JID(),+ ADJID: instance.ADJID(),CreatedAt: instance.CreatedAt(),UpdatedAt: time.Now(),})@@ -72,6 +73,12 @@ func (m *DeviceManager) GetDevice(id string) (*DeviceInstance, bool) {func (m *DeviceManager) getDeviceByJID(jid string) (*DeviceInstance, bool) {m.mu.RLock()defer m.mu.RUnlock()+ // Prefer the exact companion identity so two slots on the same number stay distinct.+ for _, inst := range m.devices {+ if inst != nil && inst.ADJID() != "" && inst.ADJID() == jid {+ return inst, true+ }+ }for _, inst := range m.devices {if inst != nil && inst.JID() == jid {return inst, true@@ -80,6 +87,47 @@ func (m *DeviceManager) getDeviceByJID(jid string) (*DeviceInstance, bool) {return nil, false}+// storeIdentity returns the most precise store identity a slot knows: the full AD JID+// once the companion suffix is known, otherwise the bare-number JID.+func storeIdentity(inst *DeviceInstance) string {+ if inst == nil {+ return ""+ }+ if ad := inst.ADJID(); ad != "" {+ return ad+ }+ return inst.JID()+}++// sameStoreIdentity reports whether two store JIDs refer to the same companion+// session. JIDs with explicit device suffixes must match exactly; a bare-number JID+// (legacy rows/lookups that never carried the :NN suffix) matches any companion of+// that number.+func sameStoreIdentity(a, b types.JID) bool {+ if a.ToNonAD() != b.ToNonAD() {+ return false+ }+ if a.Device != 0 && b.Device != 0 {+ return a.Device == b.Device+ }+ return true+}++// slotIdentityMatches reports whether an existing slot refers to the same companion+// session as the given identity. When both sides know their AD JID it must match+// exactly (two slots may share a number); otherwise the bare number decides (records+// predating the ad_jid column).+func slotIdentityMatches(inst *DeviceInstance, nonAD, adJID string) bool {+ if inst == nil {+ return false+ }+ instAD := inst.ADJID()+ if adJID != "" && instAD != "" {+ return instAD == adJID+ }+ return nonAD != "" && inst.JID() == nonAD+}+// IsHealthy returns true if the device manager is initialized and has a valid store connection.// Note: This is a service initialization check, not a live connectivity check.// Returning true indicates the internal store is ready, but does not guarantee@@ -149,14 +197,20 @@ func (m *DeviceManager) RemoveDevice(id string) {}// deleteStoreRowsForJID removes the whatsmeow device rows (primary + keys containers)-// whose JID matches jid. Matching uses the NonAD form to mirror LoadExistingDevices,-// where the devices table stores NonAD JIDs. It is idempotent — a row that is already-// gone is simply not found — and an empty jid is a no-op (a slot that was never paired-// has no store rows to delete).+// matching the given identity. A full AD JID (number:[email protected]) deletes exactly+// that companion session; a bare-number JID (legacy slots that never stored the AD+// form) deletes only when it matches a single row — several sibling companion rows for+// one number are ambiguous, and deleting here could kill another slot's live session+// (issue #760). It is idempotent — a row that is already gone is simply not found —+// and an empty jid is a no-op (a slot that was never paired has no store rows).func (m *DeviceManager) deleteStoreRowsForJID(ctx context.Context, jid string) error {if strings.TrimSpace(jid) == "" {return nil}+ target, err := types.ParseJID(jid)+ if err != nil || target.User == "" {+ return nil+ }var firstErr errordeleteFrom := func(container *sqlstore.Container, label string) {@@ -169,18 +223,31 @@ func (m *DeviceManager) deleteStoreRowsForJID(ctx context.Context, jid string) efirstErr = errors.Join(firstErr, err)return}+ var matches []*store.Devicefor _, dev := range devices {if dev == nil || dev.ID == nil {continue}- if dev.ID.ToNonAD().String() != jid {+ if dev.ID.ToNonAD() != target.ToNonAD() {continue}+ // Deletion is stricter than sync matching: an AD target deletes only its+ // exact companion row. A bare-number (Device-0) row of the same number may+ // be a legacy slot's usable session and must never be taken along.+ if target.Device != 0 && dev.ID.Device != target.Device {+ continue+ }+ matches = append(matches, dev)+ }+ if target.Device == 0 && len(matches) > 1 {+ logrus.Warnf("[DEVICE_MANAGER] %d companion sessions in %s store match %s; skipping delete to avoid removing a sibling slot's session", len(matches), label, jid)+ return+ }+ for _, dev := range matches {if err := container.DeleteDevice(ctx, dev); err != nil {logrus.WithError(err).Warnf("[DEVICE_MANAGER] failed to delete jid %s from %s store", jid, label)firstErr = errors.Join(firstErr, err)}- break}}@@ -205,11 +272,11 @@ func (m *DeviceManager) PurgeDevice(ctx context.Context, deviceID string) error}}- // Resolve the device's WhatsApp JID before tearing anything down so we can delete- // its whatsmeow store rows by JID even when no live client is attached.+ // Resolve the device's WhatsApp identity before tearing anything down so we can+ // delete its whatsmeow store rows even when no live client is attached.var jid stringif inst, ok := m.GetDevice(deviceID); ok && inst != nil {- jid = inst.JID()+ jid = storeIdentity(inst)if cli := inst.GetClient(); cli != nil {// The WhatsApp unlink is best-effort: a dead/expired session may fail// here, but that must not block local cleanup or fail the purge.@@ -279,11 +346,15 @@ func (m *DeviceManager) keepSlotLogout(ctx context.Context, deviceID string) errif !ok || inst == nil {// The remote-logout callback can hold a stale id: InitWaCLI keys its instance by// the AD JID string, but loadFromRegistry may replace it with a registry slot- // keyed by uuid (instances store NonAD JIDs). Fall back to JID resolution so the+ // keyed by uuid. Fall back to JID resolution — exact AD JID first so siblings on+ // the same number stay distinct, then the bare number for legacy slots — so the// cleanup still lands on the surviving slot instead of leaving a stale JID and// an orphan keys-container row.if parsed, err := types.ParseJID(deviceID); err == nil && parsed.User != "" {- inst, ok = m.getDeviceByJID(parsed.ToNonAD().String())+ inst, ok = m.getDeviceByJID(parsed.String())+ if !ok {+ inst, ok = m.getDeviceByJID(parsed.ToNonAD().String())+ }}if !ok || inst == nil {return fmt.Errorf("device %s not found", deviceID)@@ -291,11 +362,11 @@ func (m *DeviceManager) keepSlotLogout(ctx context.Context, deviceID string) errdeviceID = inst.ID()}- // Resolve the JID before resetDeviceKeepSlot clears it, so we can delete the stored- // whatsmeow rows even when no live client is attached (slot loaded from storage).- // Always delete (don't rely on cli.Logout having done it): an orphan row would- // otherwise get matched back on restart. Idempotent when the row is already gone.- jid := inst.JID()+ // Resolve the identity before resetDeviceKeepSlot clears it, so we can delete the+ // stored whatsmeow rows even when no live client is attached (slot loaded from+ // storage). Always delete (don't rely on cli.Logout having done it): an orphan row+ // would otherwise get matched back on restart. Idempotent when the row is already gone.+ jid := storeIdentity(inst)var firstErr errorfirstErr = errors.Join(firstErr, m.deleteStoreRowsForJID(ctx, jid))@@ -319,6 +390,7 @@ func (m *DeviceManager) resetDeviceKeepSlot(deviceID string) error {DeviceID: deviceID,DisplayName: inst.DisplayName(),JID: "",+ ADJID: "",CreatedAt: inst.CreatedAt(),UpdatedAt: time.Now(),}); err != nil {@@ -419,68 +491,102 @@ func (m *DeviceManager) LoadExistingDevices(ctx context.Context) error {if dev == nil || dev.ID == nil {continue}- // Use NonAD JID to match with devices table which stores NonAD format- jid := dev.ID.ToNonAD().String()+ adJID := dev.ID.String()+ nonAD := dev.ID.ToNonAD().String()- // Check if device already exists by ID or JIDm.mu.RLock()- existingByID := m.devices[jid]- var matchedDevice *DeviceInstance- var orphanDevice *DeviceInstance+ var exactMatch, legacyMatch, orphanSlot *DeviceInstance+ numberClaimed := falsefor _, inst := range m.devices {- if inst.JID() == jid {- matchedDevice = inst- break- }- if inst.JID() == "" && orphanDevice == nil {- orphanDevice = inst+ switch {+ case inst.ADJID() == adJID:+ exactMatch = inst+ case inst.JID() == nonAD:+ numberClaimed = true+ if inst.ADJID() == "" && legacyMatch == nil {+ legacyMatch = inst+ }+ case inst.JID() == "" && inst.ADJID() == "" && orphanSlot == nil:+ orphanSlot = inst}}m.mu.RUnlock()- // Skip if already matched- if existingByID != nil {- m.applyStoreJID(existingByID, jid)+ // Slot already mapped to this exact companion session.+ if exactMatch != nil {+ m.applyStoreJID(exactMatch, *dev.ID)continue}- if matchedDevice != nil {++ // Legacy slot that only stored the bare number: backfill the companion identity+ // from the store row. When a number has several rows and no recorded AD JIDs the+ // first row wins — that ambiguity predates the ad_jid column.+ if legacyMatch != nil {+ logrus.Infof("[DEVICE_MANAGER] backfilling companion %s for device %s", adJID, legacyMatch.ID())+ m.applyStoreJID(legacyMatch, *dev.ID)+ m.persistInstanceRecord(legacyMatch)continue}- // Match orphaned device with this JID- if orphanDevice != nil {- logrus.Infof("[DEVICE_MANAGER] matching orphaned device %s with JID %s", orphanDevice.ID(), jid)- m.applyStoreJID(orphanDevice, jid)- if m.storage != nil {- _ = m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{- DeviceID: orphanDevice.ID(),- JID: jid,- })- }+ // Another slot already claims this number with a different companion: leave the+ // row alone instead of adopting it — dialing it would churn against a dead or+ // sibling session (issue #760).+ if numberClaimed {+ logrus.Warnf("[DEVICE_MANAGER] leaving unreferenced companion session %s alone: number already claimed by another slot", adJID)+ continue+ }++ // Match orphaned device (registered slot without a session) with this row.+ if orphanSlot != nil {+ logrus.Infof("[DEVICE_MANAGER] matching orphaned device %s with JID %s", orphanSlot.ID(), nonAD)+ m.applyStoreJID(orphanSlot, *dev.ID)+ m.persistInstanceRecord(orphanSlot)continue}// Create new device instance- instance := NewDeviceInstance(jid, nil, newDeviceChatStorage(jid, m.storage))+ instance := NewDeviceInstance(nonAD, nil, newDeviceChatStorage(nonAD, m.storage))instance.SetState(domainDevice.DeviceStateDisconnected)- m.applyStoreJID(instance, jid)+ m.applyStoreJID(instance, *dev.ID)m.AddDevice(instance)}return nil}-func (m *DeviceManager) applyStoreJID(instance *DeviceInstance, jid string) {- if instance == nil || jid == "" {+// applyStoreJID stamps a store row's identity onto a slot: the bare number as the+// chat-storage partition key and the full AD JID as the companion identity.+func (m *DeviceManager) applyStoreJID(instance *DeviceInstance, storeJID types.JID) {+ if instance == nil || storeJID.IsEmpty() {return}+ nonAD := storeJID.ToNonAD().String()instance.mu.Lock()- instance.jid = jid+ instance.jid = nonAD+ instance.adJID = storeJID.String()instance.mu.Unlock()- instance.SetChatStorage(newDeviceChatStorage(jid, m.storage))+ instance.SetChatStorage(newDeviceChatStorage(nonAD, m.storage))+}++// persistInstanceRecord upserts the slot's registry record from its in-memory state.+func (m *DeviceManager) persistInstanceRecord(inst *DeviceInstance) {+ if m.storage == nil || inst == nil || strings.TrimSpace(inst.ID()) == "" {+ return+ }+ _ = m.storage.SaveDeviceRecord(&domainChatStorage.DeviceRecord{+ DeviceID: inst.ID(),+ DisplayName: inst.DisplayName(),+ JID: inst.JID(),+ ADJID: inst.ADJID(),+ CreatedAt: inst.CreatedAt(),+ UpdatedAt: time.Now(),+ })}-// loadFromRegistry loads devices from the registry, handling deduplication.+// loadFromRegistry loads devices from the registry. Boot reconciliation never deletes+// registry records: two slots may legitimately share a phone number as distinct+// companion sessions (issue #760), and even a genuinely stale record is only skipped+// here — deletion belongs to explicit remove/purge.func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceRecord) {// Collect JIDs from manual devices (device_id doesn't contain @)manualDeviceJIDs := make(map[string]bool)@@ -493,8 +599,10 @@ func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceReco}}- // Load devices, removing auto-created duplicates- seenJIDs := make(map[string]bool)+ // The AD JID identifies the exact companion, so two slots on the same number are+ // distinct identities. Only records predating the ad_jid column fall back to the+ // bare number, where a duplicate is ambiguous and skipped (never deleted).+ seenIdentities := make(map[string]bool)for _, rec := range records {if rec == nil || strings.TrimSpace(rec.DeviceID) == "" {continue@@ -503,33 +611,34 @@ func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceReco// Skip auto-created devices if manual device with same JID existsisAutoCreated := strings.Contains(rec.DeviceID, "@")if isAutoCreated && manualDeviceJIDs[rec.DeviceID] {- logrus.Warnf("[DEVICE_MANAGER] removing auto-created device %s", rec.DeviceID)- _ = m.storage.DeleteDeviceRecord(rec.DeviceID)+ logrus.Warnf("[DEVICE_MANAGER] skipping auto-created device %s: a named slot claims this number", rec.DeviceID)continue}- // Skip duplicate JIDs- if rec.JID != "" {- if seenJIDs[rec.JID] {- logrus.Warnf("[DEVICE_MANAGER] removing duplicate JID device %s", rec.DeviceID)- _ = m.storage.DeleteDeviceRecord(rec.DeviceID)+ identity := rec.ADJID+ if identity == "" {+ identity = rec.JID+ }+ if identity != "" {+ if seenIdentities[identity] {+ logrus.Warnf("[DEVICE_MANAGER] skipping device %s: identity %s already loaded (record kept; remove the slot explicitly if stale)", rec.DeviceID, identity)continue}- seenJIDs[rec.JID] = true+ seenIdentities[identity] = true}- // Check if a device with this JID already exists in memory (from InitWaCLI)+ // Check if a device with this identity already exists in memory (from InitWaCLI)m.mu.RLock()var existingByJID *DeviceInstancefor id, inst := range m.devices {- if rec.JID != "" && inst.JID() == rec.JID && id != rec.DeviceID {+ if id != rec.DeviceID && slotIdentityMatches(inst, rec.JID, rec.ADJID) {existingByJID = instbreak}}m.mu.RUnlock()- // If device with matching JID exists, remove it and use the registry device+ // If device with matching identity exists, remove it and use the registry deviceif existingByJID != nil {m.mu.Lock()delete(m.devices, existingByJID.ID())@@ -546,6 +655,7 @@ func (m *DeviceManager) loadFromRegistry(records []*domainChatStorage.DeviceRecoinstance.SetState(domainDevice.DeviceStateDisconnected)instance.displayName = rec.DisplayNameinstance.jid = rec.JID+ instance.adJID = rec.ADJID// If we had an existing device with client, transfer the clientif existingByJID != nil {@@ -574,11 +684,11 @@ func (m *DeviceManager) EnsureDefault(client *DeviceInstance) {return}- // Check if any existing device has matching JID+ // Check if any existing device refers to the same companion sessionclientJID := client.JID()if clientJID != "" {for _, inst := range m.devices {- if inst.JID() == clientJID {+ if slotIdentityMatches(inst, clientJID, client.ADJID()) {// Update existing device with the new clientinst.SetClient(client.GetClient())return@@ -668,7 +778,7 @@ func (m *DeviceManager) ensureInstance(deviceID string) *DeviceInstance {// Check if any existing device has this as its JID (deviceID might be a JID)for _, inst := range m.devices {- if inst.JID() == deviceID {+ if inst.JID() == deviceID || (inst.ADJID() != "" && inst.ADJID() == deviceID) {if inst.GetChatStorage() == nil {storageDeviceID := inst.JID()if storageDeviceID == "" {@@ -690,38 +800,66 @@ func (m *DeviceManager) getOrCreateStoreDevice(ctx context.Context, deviceID strreturn nil, fmt.Errorf("store container is nil")}- // Try to reuse an existing device record if the ID maps to a JID.+ // Try to reuse an existing device record. The slot's own identity comes first: its+ // AD JID pins the exact companion session, while deviceID may itself be a JID.if deviceID != "" {- if jid, err := types.ParseJID(deviceID); err == nil {- if dev, err := findStoreDeviceByJID(ctx, m.store, jid); err != nil {- return nil, err- } else if dev != nil {- return dev, nil- }- }-- // If deviceID is not a valid JID, look up the device instance and use its JIDm.mu.RLock()var instJID string- if inst, ok := m.devices[deviceID]; ok && inst.JID() != "" {- instJID = inst.JID()+ if inst, ok := m.devices[deviceID]; ok {+ instJID = storeIdentity(inst)}m.mu.RUnlock()+ candidates := make([]string, 0, 2)if instJID != "" {- if jid, err := types.ParseJID(instJID); err == nil {- if dev, err := findStoreDeviceByJID(ctx, m.store, jid); err != nil {- return nil, err- } else if dev != nil {- return dev, nil- }+ candidates = append(candidates, instJID)+ }+ if deviceID != instJID {+ candidates = append(candidates, deviceID)+ }++ for _, candidate := range candidates {+ jid, err := types.ParseJID(candidate)+ if err != nil || jid.User == "" {+ continue+ }+ dev, err := findStoreDeviceByJID(ctx, m.store, jid)+ if err != nil {+ return nil, err+ }+ if dev == nil || dev.ID == nil {+ continue+ }+ // Never hand a slot a companion session that a sibling slot already claims —+ // that is a session hijack (issue #760). Fall through to a fresh device so+ // the slot can be re-paired instead.+ if m.companionClaimedByOther(deviceID, dev.ID.String()) {+ logrus.Warnf("[DEVICE_MANAGER] companion session %s is claimed by another slot; giving %s a fresh session", dev.ID.String(), deviceID)+ continue}+ return dev, nil}}return m.store.NewDevice(), nil}+// companionClaimedByOther reports whether a slot other than deviceID has recorded the+// given companion identity as its own.+func (m *DeviceManager) companionClaimedByOther(deviceID, adJID string) bool {+ if adJID == "" {+ return false+ }+ m.mu.RLock()+ defer m.mu.RUnlock()+ for id, inst := range m.devices {+ if id != deviceID && inst != nil && inst.ADJID() == adJID {+ return true+ }+ }+ return false+}+func (m *DeviceManager) configureKeysStore(ctx context.Context, device *store.Device) error {if m.keys == nil || device == nil || device.ID == nil {return nil@@ -745,17 +883,33 @@ func findStoreDeviceByJID(ctx context.Context, container *sqlstore.Container, jireturn dev, nil}+ // A JID with an explicit device suffix identifies one exact companion session; a+ // miss means that session is gone. Falling back to bare-number matching here could+ // silently return a sibling companion of the same number (issue #760).+ if jid.Device != 0 {+ return nil, nil+ }+devices, err := container.GetAllDevices(ctx)if err != nil {return nil, err}+ // Bare-number lookup (legacy slots that never stored the AD JID): resolve only+ // when it is unambiguous. Several companion rows for one number → never guess.+ var matches []*store.DevicetargetJID := jid.ToNonAD().String()for _, dev := range devices {if dev != nil && dev.ID != nil && dev.ID.ToNonAD().String() == targetJID {- return dev, nil+ matches = append(matches, dev)}}+ if len(matches) == 1 {+ return matches[0], nil+ }+ if len(matches) > 1 {+ logrus.Warnf("[DEVICE_MANAGER] %d companion sessions match %s; refusing to guess (re-pair the slot or purge the orphans)", len(matches), targetJID)+ }return nil, nil}diff --git a/src/infrastructure/whatsapp/device_manager_companion_test.go b/src/infrastructure/whatsapp/device_manager_companion_test.gonew file mode 100644index 00000000..671adcb2--- /dev/null+++ b/src/infrastructure/whatsapp/device_manager_companion_test.go@@ -0,0 +1,510 @@+package whatsapp++import (+ "context"+ "testing"+ "time"++ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"+ "go.mau.fi/whatsmeow/types"+)++// Tests for issue #760: when two device slots are linked to the SAME phone number+// (WhatsApp allows several companion devices per account), the slot<->companion+// mapping must be keyed by the full AD JID (number:[email protected]), never by the+// bare number alone. Guessing among sibling companion rows hijacks or deletes the+// wrong session.++// registryStubStorage extends keepSlotStubStorage with a device registry listing so+// LoadExistingDevices can be exercised with a non-nil storage.+type registryStubStorage struct {+ keepSlotStubStorage+ records []*domainChatStorage.DeviceRecord+}++func (s *registryStubStorage) ListDeviceRecords() ([]*domainChatStorage.DeviceRecord, error) {+ return s.records, nil+}++// countStoreRows returns how many device rows in the container share the NonAD number.+func countStoreRows(t *testing.T, ctx context.Context, m *DeviceManager, nonAD string) int {+ t.Helper()+ devices, err := m.store.GetAllDevices(ctx)+ if err != nil {+ t.Fatalf("get all devices: %v", err)+ }+ count := 0+ for _, d := range devices {+ if d != nil && d.ID != nil && d.ID.ToNonAD().String() == nonAD {+ count+++ }+ }+ return count+}++// findStoreDeviceByJID must resolve an AD JID exactly, and must refuse to guess when+// a bare-number lookup matches several sibling companion rows.+func TestFindStoreDeviceByJID_DoesNotGuessAmongSiblingCompanions(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000001", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000001", types.WhatsAppDomain, 32)+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ // Exact AD lookup resolves the precise companion.+ dev, err := findStoreDeviceByJID(ctx, container, adB)+ if err != nil {+ t.Fatalf("find by AD JID: %v", err)+ }+ if dev == nil || dev.ID == nil || dev.ID.String() != adB.String() {+ t.Fatalf("expected exact companion %s, got %v", adB.String(), dev)+ }++ // Bare-number lookup with two sibling rows is ambiguous: no guessing.+ dev, err = findStoreDeviceByJID(ctx, container, adA.ToNonAD())+ if err != nil {+ t.Fatalf("ambiguous NonAD lookup should not error, got: %v", err)+ }+ if dev != nil {+ t.Fatalf("expected no device for ambiguous NonAD lookup, got %s", dev.ID.String())+ }+}++// The single-row bare-number fallback must keep working (legacy records that never+// stored an AD JID rely on it).+func TestFindStoreDeviceByJID_SingleRowNonADFallbackStillResolves(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adJID := types.NewADJID("6281777000002", types.WhatsAppDomain, 7)+ if err := newTestStoreDevice(container, adJID, "only").Save(ctx); err != nil {+ t.Fatalf("save device: %v", err)+ }++ dev, err := findStoreDeviceByJID(ctx, container, adJID.ToNonAD())+ if err != nil {+ t.Fatalf("find by NonAD JID: %v", err)+ }+ if dev == nil || dev.ID == nil || dev.ID.String() != adJID.String() {+ t.Fatalf("expected single-row fallback to resolve %s, got %v", adJID.String(), dev)+ }+}++// EnsureClient must attach each slot to its own companion row when both slots know+// their AD JID, instead of handing the first row of the number to both slots.+func TestEnsureClient_ResolvesPreciseCompanionRowByADJID(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000003", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000003", types.WhatsAppDomain, 32)+ nonAD := adA.ToNonAD().String()+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ manager.devices["slot-a"] = &DeviceInstance{id: "slot-a", jid: nonAD, adJID: adA.String(), createdAt: time.Now()}+ manager.devices["slot-b"] = &DeviceInstance{id: "slot-b", jid: nonAD, adJID: adB.String(), createdAt: time.Now()}++ instB, err := manager.EnsureClient(ctx, "slot-b")+ if err != nil {+ t.Fatalf("ensure client slot-b: %v", err)+ }+ clientB := instB.GetClient()+ if clientB == nil || clientB.Store == nil || clientB.Store.ID == nil {+ t.Fatal("expected slot-b to get a paired client")+ }+ if got := clientB.Store.ID.String(); got != adB.String() {+ t.Fatalf("slot-b resolved to %s, want its own companion %s", got, adB.String())+ }++ instA, err := manager.EnsureClient(ctx, "slot-a")+ if err != nil {+ t.Fatalf("ensure client slot-a: %v", err)+ }+ clientA := instA.GetClient()+ if clientA == nil || clientA.Store == nil || clientA.Store.ID == nil {+ t.Fatal("expected slot-a to get a paired client")+ }+ if got := clientA.Store.ID.String(); got != adA.String() {+ t.Fatalf("slot-a resolved to %s, want its own companion %s", got, adA.String())+ }+}++// A slot that only knows its bare number must NOT adopt a companion row that is+// already claimed by a sibling slot's AD JID (session hijack). It should fall back to+// a fresh, unpaired store device so the slot can be re-paired.+func TestEnsureClient_DoesNotHijackSiblingCompanionRow(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adB := types.NewADJID("6281777000004", types.WhatsAppDomain, 32)+ nonAD := adB.ToNonAD().String()+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ manager.devices["slot-a"] = &DeviceInstance{id: "slot-a", jid: nonAD, createdAt: time.Now()}+ manager.devices["slot-b"] = &DeviceInstance{id: "slot-b", jid: nonAD, adJID: adB.String(), createdAt: time.Now()}++ instA, err := manager.EnsureClient(ctx, "slot-a")+ if err != nil {+ t.Fatalf("ensure client slot-a: %v", err)+ }+ clientA := instA.GetClient()+ if clientA == nil || clientA.Store == nil {+ t.Fatal("expected slot-a to get a client")+ }+ if clientA.Store.ID != nil && clientA.Store.ID.String() == adB.String() {+ t.Fatalf("slot-a hijacked sibling companion row %s", adB.String())+ }+ if clientA.Store.ID != nil {+ t.Fatalf("expected slot-a to get a fresh unpaired device, got %s", clientA.Store.ID.String())+ }+}++// deleteStoreRowsForJID must refuse an ambiguous bare-number delete when several+// sibling companion rows exist (it cannot know which one belongs to the slot).+func TestDeleteStoreRowsForJID_RefusesAmbiguousBareNumber(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000005", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000005", types.WhatsAppDomain, 32)+ nonAD := adA.ToNonAD().String()+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ if err := manager.deleteStoreRowsForJID(ctx, nonAD); err != nil {+ t.Fatalf("ambiguous delete should be a warn-and-skip, got error: %v", err)+ }++ if got := countStoreRows(t, ctx, manager, nonAD); got != 2 {+ t.Fatalf("expected both sibling rows to survive an ambiguous delete, got %d", got)+ }+}++// deleteStoreRowsForJID with a full AD JID must delete exactly that companion row.+func TestDeleteStoreRowsForJID_DeletesExactCompanionOnly(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000006", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000006", types.WhatsAppDomain, 32)+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ if err := manager.deleteStoreRowsForJID(ctx, adA.String()); err != nil {+ t.Fatalf("delete by AD JID: %v", err)+ }++ devices, err := container.GetAllDevices(ctx)+ if err != nil {+ t.Fatalf("get all devices: %v", err)+ }+ if len(devices) != 1 || devices[0].ID.String() != adB.String() {+ t.Fatalf("expected only sibling %s to survive, got %d rows", adB.String(), len(devices))+ }+}++// Deleting by a full AD JID must never take a bare-number (Device-0) row of the same+// number with it: such a row may be a legacy slot's usable session, and only the exact+// companion row certainly belongs to the target.+func TestDeleteStoreRowsForJID_ADTargetLeavesBareNumberRowAlone(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adJID := types.NewADJID("6281777000015", types.WhatsAppDomain, 28)+ nonADJID := adJID.ToNonAD()+ if err := newTestStoreDevice(container, adJID, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, nonADJID, "bare-number").Save(ctx); err != nil {+ t.Fatalf("save bare-number row: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ if err := manager.deleteStoreRowsForJID(ctx, adJID.String()); err != nil {+ t.Fatalf("delete by AD JID: %v", err)+ }++ devices, err := container.GetAllDevices(ctx)+ if err != nil {+ t.Fatalf("get all devices: %v", err)+ }+ if len(devices) != 1 || devices[0].ID.String() != nonADJID.String() {+ t.Fatalf("expected only the bare-number row to survive, got %d rows", len(devices))+ }+}++// keepSlotLogout must use the slot's AD JID so it deletes only its own companion row,+// leaving the sibling slot's session untouched.+func TestKeepSlotLogout_DeletesOnlyOwnCompanionRow(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000007", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000007", types.WhatsAppDomain, 32)+ nonAD := adA.ToNonAD().String()+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(container, nil, storage)+ instA := &DeviceInstance{id: "slot-a", jid: nonAD, adJID: adA.String(), createdAt: time.Now()}+ manager.devices["slot-a"] = instA+ manager.devices["slot-b"] = &DeviceInstance{id: "slot-b", jid: nonAD, adJID: adB.String(), createdAt: time.Now()}++ if err := manager.keepSlotLogout(ctx, "slot-a"); err != nil {+ t.Fatalf("keepSlotLogout: %v", err)+ }++ devices, err := container.GetAllDevices(ctx)+ if err != nil {+ t.Fatalf("get all devices: %v", err)+ }+ if len(devices) != 1 || devices[0].ID.String() != adB.String() {+ t.Fatalf("expected sibling companion %s to survive, got %d rows", adB.String(), len(devices))+ }+ if got := instA.ADJID(); got != "" {+ t.Fatalf("expected slot-a AD JID cleared after logout, got %q", got)+ }+ if len(storage.savedRecords) == 0 {+ t.Fatal("expected the kept slot to be persisted")+ }+ last := storage.savedRecords[len(storage.savedRecords)-1]+ if last.DeviceID != "slot-a" || last.JID != "" || last.ADJID != "" {+ t.Fatalf("expected persisted slot-a with cleared JIDs, got %+v", last)+ }+}++// loadFromRegistry must keep two slots that share a phone number when their AD JIDs+// identify distinct companions — deleting one is data loss.+func TestLoadFromRegistry_KeepsSiblingSlotsOnSameNumber(t *testing.T) {+ adA := types.NewADJID("6281777000008", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000008", types.WhatsAppDomain, 32)+ nonAD := adA.ToNonAD().String()++ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ manager.loadFromRegistry([]*domainChatStorage.DeviceRecord{+ {DeviceID: "slot-a", DisplayName: "A", JID: nonAD, ADJID: adA.String(), CreatedAt: time.Now()},+ {DeviceID: "slot-b", DisplayName: "B", JID: nonAD, ADJID: adB.String(), CreatedAt: time.Now()},+ })++ if len(storage.deletedRecords) != 0 {+ t.Fatalf("expected no registry deletions, got %v", storage.deletedRecords)+ }+ instA, okA := manager.GetDevice("slot-a")+ instB, okB := manager.GetDevice("slot-b")+ if !okA || !okB {+ t.Fatalf("expected both sibling slots to load, got a=%v b=%v", okA, okB)+ }+ if instA.ADJID() != adA.String() || instB.ADJID() != adB.String() {+ t.Fatalf("expected AD JIDs to load, got a=%q b=%q", instA.ADJID(), instB.ADJID())+ }+}++// Legacy duplicate records (same bare number, no AD JID) are ambiguous: the loader+// must skip the duplicate but MUST NOT delete its registry record at boot.+func TestLoadFromRegistry_LegacyDuplicateSkippedNotDeleted(t *testing.T) {+ nonAD := "[email protected]"++ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ manager.loadFromRegistry([]*domainChatStorage.DeviceRecord{+ {DeviceID: "slot-a", JID: nonAD, CreatedAt: time.Now()},+ {DeviceID: "slot-b", JID: nonAD, CreatedAt: time.Now()},+ })++ if len(storage.deletedRecords) != 0 {+ t.Fatalf("boot reconciliation must not delete registry records, got %v", storage.deletedRecords)+ }+ if _, ok := manager.GetDevice("slot-a"); !ok {+ t.Fatal("expected first slot to load")+ }+ if _, ok := manager.GetDevice("slot-b"); ok {+ t.Fatal("expected ambiguous duplicate slot to be skipped in memory")+ }+}++// The auto-created-duplicate cleanup must also become skip-and-warn instead of+// deleting records during startup reconciliation.+func TestLoadFromRegistry_AutoCreatedDuplicateSkippedNotDeleted(t *testing.T) {+ nonAD := "[email protected]"++ storage := &keepSlotStubStorage{}+ manager := NewDeviceManager(nil, nil, storage)++ manager.loadFromRegistry([]*domainChatStorage.DeviceRecord{+ {DeviceID: "slot-a", JID: nonAD, CreatedAt: time.Now()},+ {DeviceID: nonAD, JID: nonAD, CreatedAt: time.Now()}, // auto-created duplicate+ })++ if len(storage.deletedRecords) != 0 {+ t.Fatalf("boot reconciliation must not delete registry records, got %v", storage.deletedRecords)+ }+ if _, ok := manager.GetDevice("slot-a"); !ok {+ t.Fatal("expected manual slot to load")+ }+ if _, ok := manager.GetDevice(nonAD); ok {+ t.Fatal("expected auto-created duplicate to be skipped in memory")+ }+}++// LoadExistingDevices must backfill the AD JID for a legacy slot that only stored the+// bare number, and persist the enriched record.+func TestLoadExistingDevices_BackfillsADJIDForLegacySlot(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adJID := types.NewADJID("6281777000011", types.WhatsAppDomain, 28)+ nonAD := adJID.ToNonAD().String()+ if err := newTestStoreDevice(container, adJID, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }++ storage := ®istryStubStorage{}+ manager := NewDeviceManager(container, nil, storage)+ inst := &DeviceInstance{id: "slot-a", jid: nonAD, displayName: "A", createdAt: time.Now()}+ manager.devices["slot-a"] = inst++ if err := manager.LoadExistingDevices(ctx); err != nil {+ t.Fatalf("load existing devices: %v", err)+ }++ if got := inst.ADJID(); got != adJID.String() {+ t.Fatalf("expected backfilled AD JID %s, got %q", adJID.String(), got)+ }+ found := false+ for _, rec := range storage.savedRecords {+ if rec.DeviceID == "slot-a" && rec.ADJID == adJID.String() && rec.JID == nonAD {+ found = true+ }+ }+ if !found {+ t.Fatalf("expected backfilled record persisted, got %+v", storage.savedRecords)+ }+}++// LoadExistingDevices must not adopt sibling companion rows of a number that is+// already claimed by a slot — those orphans are left for explicit cleanup, so the+// auto-connect loop cannot dial dead sessions of a live number.+func TestLoadExistingDevices_DoesNotAdoptSiblingCompanionRows(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adA := types.NewADJID("6281777000012", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000012", types.WhatsAppDomain, 32)+ nonAD := adA.ToNonAD().String()+ if err := newTestStoreDevice(container, adA, "companion-28").Save(ctx); err != nil {+ t.Fatalf("save companion 28: %v", err)+ }+ if err := newTestStoreDevice(container, adB, "companion-32").Save(ctx); err != nil {+ t.Fatalf("save companion 32: %v", err)+ }++ storage := ®istryStubStorage{}+ manager := NewDeviceManager(container, nil, storage)+ inst := &DeviceInstance{id: "slot-a", jid: nonAD, adJID: adA.String(), createdAt: time.Now()}+ manager.devices["slot-a"] = inst++ if err := manager.LoadExistingDevices(ctx); err != nil {+ t.Fatalf("load existing devices: %v", err)+ }++ if got := len(manager.ListDevices()); got != 1 {+ t.Fatalf("expected sibling orphan row to stay unadopted, got %d instances", got)+ }+ if got := inst.ADJID(); got != adA.String() {+ t.Fatalf("expected slot-a to keep its own companion, got %q", got)+ }+}++// Adopting a store row for a completely unclaimed number must record the precise AD+// JID on the adopted instance (the legacy single-to-multi-device migration path).+func TestLoadExistingDevices_AdoptsUnclaimedRowWithPreciseADJID(t *testing.T) {+ ctx := context.Background()+ container := newTestSQLStore(t)++ adJID := types.NewADJID("6281777000013", types.WhatsAppDomain, 5)+ nonAD := adJID.ToNonAD().String()+ if err := newTestStoreDevice(container, adJID, "companion-5").Save(ctx); err != nil {+ t.Fatalf("save companion 5: %v", err)+ }++ manager := NewDeviceManager(container, nil, nil)+ if err := manager.LoadExistingDevices(ctx); err != nil {+ t.Fatalf("load existing devices: %v", err)+ }++ inst, ok := manager.GetDevice(nonAD)+ if !ok {+ t.Fatalf("expected adopted instance for %s", nonAD)+ }+ if inst.JID() != nonAD {+ t.Fatalf("expected adopted instance JID %s, got %q", nonAD, inst.JID())+ }+ if inst.ADJID() != adJID.String() {+ t.Fatalf("expected adopted instance AD JID %s, got %q", adJID.String(), inst.ADJID())+ }+}++// syncKeysDevice must distinguish sibling companions: a keys row for companion :32+// does not satisfy companion :28, whose keys row must still be synced.+func TestSyncKeysDevice_DistinguishesSiblingCompanions(t *testing.T) {+ ctx := context.Background()+ primaryStore := newTestSQLStore(t)+ keysStore := newTestSQLStore(t)++ adA := types.NewADJID("6281777000014", types.WhatsAppDomain, 28)+ adB := types.NewADJID("6281777000014", types.WhatsAppDomain, 32)+ if err := newTestStoreDevice(primaryStore, adA, "primary-28").Save(ctx); err != nil {+ t.Fatalf("save primary 28: %v", err)+ }+ if err := newTestStoreDevice(primaryStore, adB, "primary-32").Save(ctx); err != nil {+ t.Fatalf("save primary 32: %v", err)+ }+ if err := newTestStoreDevice(keysStore, adB, "keys-32").Save(ctx); err != nil {+ t.Fatalf("save keys 32: %v", err)+ }++ syncKeysDevice(ctx, primaryStore, keysStore, adA)++ devices, err := keysStore.GetAllDevices(ctx)+ if err != nil {+ t.Fatalf("get keys devices: %v", err)+ }+ if len(devices) != 2 {+ t.Fatalf("expected keys DB to hold both sibling companions, got %d", len(devices))+ }+ assertStoreHasDevice(t, devices, adA.String())+ assertStoreHasDevice(t, devices, adB.String())+}diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.goindex 0b5e95e4..b2c0bfd5 100644--- a/src/infrastructure/whatsapp/event_handler.go+++ b/src/infrastructure/whatsapp/event_handler.go@@ -243,6 +243,7 @@ func handleConnectionEvents(_ context.Context, client *whatsmeow.Client, instancDeviceID: instance.ID(),DisplayName: displayName,JID: jid,+ ADJID: instance.ADJID(),CreatedAt: instance.CreatedAt(),}); err != nil {log.Warnf("Failed to persist device record for %s: %v", instance.ID(), err)diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.goindex c6257ec5..e1a1b5dc 100644--- a/src/infrastructure/whatsapp/init.go+++ b/src/infrastructure/whatsapp/init.go@@ -53,15 +53,17 @@ func syncKeysDevice(ctx context.Context, db, keysDB *sqlstore.Container, jid typlog.Errorf("Failed to get keys devices: %v", err)return}- targetJID := dev.ID.ToNonAD().String()+ // Sibling companions of the same number are distinct sessions: a keys row for+ // companion :32 does not satisfy companion :28 (issue #760). Legacy bare-number+ // rows still match their AD counterpart.for _, existing := range devices {- if existing != nil && existing.ID != nil && existing.ID.ToNonAD().String() == targetJID {+ if existing != nil && existing.ID != nil && sameStoreIdentity(*existing.ID, *dev.ID) {return}}if err := keysDB.PutDevice(ctx, dev); err != nil {- log.Errorf("Failed to sync keys device %s: %v", targetJID, err)+ log.Errorf("Failed to sync keys device %s: %v", dev.ID.String(), err)}}