feat(backthink): 主动推送每次只发一个平台——决策渠道/最近活跃优先,平台含微信
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

主动推送目标不再取第一个白名单渠道(kook),也不再双目标 web+kook;改为每次只发一个平台,范围=全部已连接白名单渠道(含微信 weixin-ilink)。

backthink/push.go: pusher 单目标路由——web hint 一次 pushActive;im/auto/实体平台 hint 一次性 pushIM (msgs 置哨兵/实体平台),无 IM sink 时诚实降级 pushActive;保留 PushGate 降频与成功 RecordPush。
channelbridge/proactive.go: proactiveTarget 三级选择——①决策 [渠道:xxx] 实体平台且白名单+已连接优先;②最近活跃(主会话最近20条 newest-first 找白名单+已连接平台,web 会话自动跳过);③回退 NextConnectedAccount 用旋转游标避免永远 kook。微信不再排除、可被选中;决策 hint 指定非白名单渠道回退(不报错)。Bridge 新增 proactiveCursor 字段(mu 保护)。
context.go: guidancePrompt 描述改为每次挑一个合适渠道(含微信)。
测试: 决策优先/最近活跃/微信可选中/无信号回退旋转/单目标 等,go build/vet/test 全绿 + windows/darwin 交叉编译。stash@{0} 保留被取代的'web+kook双目标'WIP以备回滚。
This commit is contained in:
Aska committed 2026-09-08 13:34:22 +08:00
1 parent 12031bd13c
commit 3e4efa0e41
8 files changed
+419 -114

No files matched your search

+1 -1
View File
@@ -100,7 +100,7 @@ func guidancePrompt(trigger string) string {
"语言上:温暖、简短、克制、不粘人——一到两句为宜,不展开寒暄、不啰嗦、不抱怨、不频繁打扰,像想起她时轻轻说一句,说完就停。\n" +
"请把「是否主动说」与「发到哪个渠道」写成一个简短、格式固定的结尾,解析规则如下:\n" +
"[我决定:push] 或 [我决定:no_push]\n" +
"[渠道:web|im|kook|telegram|...|auto](可省略,auto/省略即交给默认:优先网页端、IM 兜底)\n" +
"[渠道:web|im|kook|telegram|weixin-ilink|...|auto](可省略,auto/省略即交给默认:每次只挑一个合适渠道——点名则优先,否则用她最近活跃的已连接渠道,含微信;不广播、不固定 web+Kook)\n" +
"上面两行之后,紧接你想说的话作为正文。\n" +
"整轮思考保持简短、单轮,不反复自我触发。"
}
@@ -76,11 +76,13 @@ type mockActive struct {
n int
err error
calls int
last adapter.UnifiedMessage
}
func (m *mockActive) SendProactive(ctx context.Context, msg adapter.UnifiedMessage) (int, error) {
m.mu.Lock()
m.calls++
m.last = msg
m.mu.Unlock()
return m.n, m.err
}
@@ -170,9 +170,10 @@ func TestThink_ParsesStructuredDecision_EndToEnd(t *testing.T) {
}
}
func TestThink_NoMarkerDefaultRoute_ActiveFirst(t *testing.T) {
func TestThink_NoMarkerDefaultRoute_IM(t *testing.T) {
t.Parallel()
// No channel marker → auto → active client first (the pre-P2 behavior).
// No channel marker → auto → a single IM channel (the bridge picks her choice /
// her recent platform / the whitelist default), NOT the active web client.
conclusion := "[我决定:push]\n洗衣机洗好了,衣服可以收了"
thinker := &mockThinker{text: conclusion}
active := &mockActive{n: 2}
@@ -188,18 +189,18 @@ func TestThink_NoMarkerDefaultRoute_ActiveFirst(t *testing.T) {
b.think(context.Background(), heartbeatTrigger())
if active.calls != 1 {
t.Fatalf("active calls = %d, want 1", active.calls)
if active.calls != 0 {
t.Fatalf("active calls = %d, want 0 (auto targets the IM bridge, not the web client)", active.calls)
}
if im.count() != 0 {
t.Fatalf("im calls = %d, want 0 (active preferred)", im.count())
if im.count() != 1 {
t.Fatalf("im calls = %d, want 1 (single IM target)", im.count())
}
recs, err := b.List(context.Background(), 10)
if err != nil {
t.Fatalf("List: %v", err)
}
if recs[0].PushResult.Route != RouteActiveClient {
t.Fatalf("record Route = %q, want %q", recs[0].PushResult.Route, RouteActiveClient)
if recs[0].PushResult.Route != RouteIMBridge {
t.Fatalf("record Route = %q, want %q", recs[0].PushResult.Route, RouteIMBridge)
}
if recs[0].PushResult.Pushed != true {
t.Fatalf("record Pushed = %v, want true", recs[0].PushResult.Pushed)
+34 -47
View File
@@ -96,10 +96,11 @@ type PushGate interface {
// PushRequest carries one proactive push attempt: the outbound message plus the
// channel target the autonomous conclusion asked for (design/20 §2 P2).
// ChannelHint is the lowercased [渠道:...] token: ""/auto keep the default
// active-client-first, IM-fallback route; "web" targets the active client; "im"
// targets the IM bridge; a concrete platform id (kook/telegram/...) targets the IM
// bridge with the message tagged for that platform.
// ChannelHint is the lowercased [渠道:...] token: ""/auto pick the default (the
// owner mandate: ONE channel, chosen by her / her most recent platform / the
// whitelist default); "web" targets the active client; "im" targets the IM bridge;
// a concrete platform id (kook/telegram/weixin-ilink/...) targets the IM bridge
// with the message tagged for that platform.
type PushRequest struct {
// Message is the normalized outbound proactive message.
Message adapter.UnifiedMessage
@@ -107,17 +108,19 @@ type PushRequest struct {
ChannelHint string
}
// Pusher delivers a proactive message under the active-client-first, IM-fallback
// policy (design/12 §3), bounded by the rate gate, honoring the channel hint the
// autonomous conclusion selected.
// Pusher delivers a proactive message to ONE target channel. It is bounded by the
// rate gate and honors the channel hint the autonomous conclusion selected: "web"
// goes to the active client, everything else goes over the IM bridge a single time,
// where the bridge picks the one channel (her choice → her most recent platform →
// whitelist default, WeChat included).
type Pusher interface {
// Push delivers req preferring the active client and falling back to the IM
// bridge, per the channel hint. It never blocks on a slow target.
// Push delivers req to a single target channel, per the channel hint. It never
// blocks on a slow target.
Push(ctx context.Context, req PushRequest) PushResult
}
// pusher is the concrete Pusher: it consults the gate, then tries the active
// client and falls back to IM, honoring the requested channel hint.
// pusher is the concrete Pusher: it consults the gate, then routes the message to
// exactly one target — the active client for a "web" hint, otherwise the IM bridge.
type pusher struct {
active ActiveClient
im IMAdapter
@@ -132,10 +135,14 @@ func newPusher(active ActiveClient, im IMAdapter, gate PushGate, log *slog.Logge
return &pusher{active: active, im: im, gate: gate, log: log}
}
// Push implements Pusher: it applies the rate gate, then resolves the channel
// hint to a route. A specific platform targets the IM bridge (tagged on the
// message) and falls back to the default route when no IM sink is wired, so the
// owner still receives the message rather than having it dropped.
// Push implements Pusher: it applies the rate gate, then routes the message to a
// single target. A "web" hint reaches the active web/native client; every other
// hint ("im", "auto", or a concrete platform) goes over the IM bridge once, where
// the bridge selects one owner channel (her [渠道:...] choice, then the platform she
// used most recently, then the whitelist default). The IM bridge is primary, so a
// push never fans out to several channels. When no IM sink is wired the active
// client is the honest fallback, so the owner is still reached rather than the
// message being dropped.
func (p *pusher) Push(ctx context.Context, req PushRequest) PushResult {
if err := ctx.Err(); err != nil {
return PushResult{Pushed: false, Route: RouteNone, Err: err.Error()}
@@ -148,27 +155,23 @@ func (p *pusher) Push(ctx context.Context, req PushRequest) PushResult {
hint := normalizeChannelHint(req.ChannelHint)
msg := req.Message
// A specific platform names the requested channel on the message so a
// platform-aware IM sink can honor it; auto/web/im keep the default platform.
if isSpecificChannel(hint) {
msg.Platform = hint
}
var res PushResult
switch hint {
case channelWeb:
if hint == channelWeb {
res = p.pushActive(ctx, msg)
case channelIM:
res = p.pushIM(ctx, msg)
case channelAuto:
res = p.pushDefault(ctx, msg)
default:
// A specific platform targets the IM bridge for that channel. With no IM
// sink wired (the backthink IM seam is single-sink), fall back to the
// default route so the owner is still reached; the hint is recorded.
} else {
// "im"/"auto"/a concrete platform all travel over the IM bridge once. A
// generic hint hands the sentinel platform so the bridge falls through to its
// recent-active / default selection; a concrete hint is honored when the
// channel is whitelisted and connected.
if hint == channelIM || hint == channelAuto {
msg.Platform = defaultProactivePlatform
} else {
msg.Platform = hint
}
res = p.pushIM(ctx, msg)
if !res.Pushed {
res = p.pushDefault(ctx, msg)
res = p.pushActive(ctx, msg)
}
}
// Only a real delivery advances the cooldown/per-kind windows, so an
@@ -179,22 +182,6 @@ func (p *pusher) Push(ctx context.Context, req PushRequest) PushResult {
return annotateHint(res, req.ChannelHint)
}
// pushDefault tries the active client first and falls back to the IM bridge.
func (p *pusher) pushDefault(ctx context.Context, msg adapter.UnifiedMessage) PushResult {
if p.active != nil {
n, err := p.active.SendProactive(ctx, msg)
if err != nil {
p.log.Warn("backthink active client push failed", "error", err)
} else if n > 0 {
return PushResult{Pushed: true, Route: RouteActiveClient, Detail: fmt.Sprintf("delivered to %d active client(s)", n)}
}
}
if p.im == nil {
return PushResult{Pushed: false, Route: RouteNone, Detail: "no active client or IM target"}
}
return p.pushIM(ctx, msg)
}
// pushActive delivers only to the active web/native client.
func (p *pusher) pushActive(ctx context.Context, msg adapter.UnifiedMessage) PushResult {
if p.active != nil {
+48 -14
View File
@@ -9,14 +9,39 @@ import (
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/session"
)
func TestPusher_ActiveFirst(t *testing.T) {
func TestPusher_AutoRoutesIM(t *testing.T) {
t.Parallel()
active := &mockActive{n: 2}
// The owner mandate: a default (auto) push reaches ONE channel over the IM
// bridge (the bridge picks her [渠道:...] choice, then her most recent platform,
// then the whitelist default) — not the active web client by default.
active := &mockActive{n: 2} // a web client is online but is NOT the default target
im := &mockIMAdapter{}
p := newPusher(active, im, &mockGate{allow: true}, discardLog())
res := p.Push(context.Background(), PushRequest{Message: adapter.UnifiedMessage{}})
if !res.Pushed {
t.Fatalf("Pushed = false, want true")
}
if res.Route != RouteIMBridge {
t.Fatalf("Route = %q, want %q", res.Route, RouteIMBridge)
}
if im.count() != 1 {
t.Fatalf("im calls = %d, want 1 (single IM target)", im.count())
}
if active.calls != 0 {
t.Fatalf("active calls = %d, want 0 (web is not the default target)", active.calls)
}
}
func TestPusher_WebHintRoutesActive(t *testing.T) {
t.Parallel()
active := &mockActive{n: 1}
im := &mockIMAdapter{}
p := newPusher(active, im, &mockGate{allow: true}, discardLog())
res := p.Push(context.Background(), PushRequest{ChannelHint: channelWeb, Message: adapter.UnifiedMessage{}})
if !res.Pushed {
t.Fatalf("Pushed = false, want true")
}
@@ -27,17 +52,19 @@ func TestPusher_ActiveFirst(t *testing.T) {
t.Fatalf("active calls = %d, want 1", active.calls)
}
if im.count() != 0 {
t.Fatalf("im calls = %d, want 0 (active should be preferred)", im.count())
t.Fatalf("im calls = %d, want 0 (web hint targets only the active client)", im.count())
}
}
func TestPusher_IMFallback_NoActive(t *testing.T) {
func TestPusher_ConcreteHintRoutesIM_SingleTarget(t *testing.T) {
t.Parallel()
active := &mockActive{n: 0} // no active client online
// A concrete decision channel is honored over the IM bridge, and exactly ONE
// target is used (the IM bridge carries it; the active client is not touched).
active := &mockActive{n: 2}
im := &mockIMAdapter{}
p := newPusher(active, im, &mockGate{allow: true}, discardLog())
res := p.Push(context.Background(), PushRequest{Message: adapter.UnifiedMessage{}})
res := p.Push(context.Background(), PushRequest{ChannelHint: "kook", Message: adapter.UnifiedMessage{}})
if !res.Pushed {
t.Fatalf("Pushed = false, want true")
@@ -48,24 +75,31 @@ func TestPusher_IMFallback_NoActive(t *testing.T) {
if im.count() != 1 {
t.Fatalf("im calls = %d, want 1", im.count())
}
if active.calls != 0 {
t.Fatalf("active calls = %d, want 0 (a concrete hint targets only the IM bridge)", active.calls)
}
if im.last.Platform != "kook" {
t.Fatalf("im platform = %q, want kook", im.last.Platform)
}
}
func TestPusher_IMFallback_ActiveError(t *testing.T) {
func TestPusher_NoIMSink_DegradesToActive(t *testing.T) {
t.Parallel()
active := &mockActive{err: context.DeadlineExceeded}
im := &mockIMAdapter{}
p := newPusher(active, im, &mockGate{allow: true}, discardLog())
// With no IM sink wired (backthink IM seam absent) the push degrades to the
// active web client so the owner is still reached rather than dropped.
active := &mockActive{n: 1}
p := newPusher(active, nil, &mockGate{allow: true}, discardLog())
res := p.Push(context.Background(), PushRequest{Message: adapter.UnifiedMessage{}})
if !res.Pushed {
t.Fatalf("Pushed = false, want true")
}
if res.Route != RouteIMBridge {
t.Fatalf("Route = %q, want %q", res.Route, RouteIMBridge)
if res.Route != RouteActiveClient {
t.Fatalf("Route = %q, want %q", res.Route, RouteActiveClient)
}
if im.count() != 1 {
t.Fatalf("im calls = %d, want 1", im.count())
if active.calls != 1 {
t.Fatalf("active calls = %d, want 1", active.calls)
}
}
@@ -179,6 +179,10 @@ type Bridge struct {
started bool
closed bool
factory PlatformFactory
// proactiveCursor is the rotation cursor for the proactive-push no-signal
// fallback (channelbridge/proactive.go), so the default channel is not always
// the first whitelisted owner channel. Guarded by mu.
proactiveCursor int
// gateMu guards the per-adapter flow gates (design/12 §6 策略三/四). They are
// built lazily on the first inbound message per account and are independent of
+152 -25
View File
@@ -7,6 +7,7 @@ import (
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
"git.yeij.top/AskaEth/Cyrene_v2/internal/user"
)
// proactiveTarget is the owner's IM address (platform + account id) resolved for
@@ -16,20 +17,30 @@ type proactiveTarget struct {
accountID string
}
// proactiveRecentCount is how many of the most recent main-session messages the
// proactive target selection scans to find "where the owner last talked", so a
// push lands on the channel she is actually using. Compile-time so no magic number
// appears in the run path.
const proactiveRecentCount = 20
// SendProactive pushes msg to the owner's IM channel via the registered adapter
// for that platform. It is the backthink IMAdapter seam (design/12 §3 fallback).
// The target account is chosen by msg.Platform when it names one of the owner's
// whitelisted channels, otherwise the first whitelisted owner channel is used.
// When the owner profile has no whitelisted account (or none carries an account
// id) it returns a clear error so the caller records the reason rather than
// for that platform. It is the backthink IMAdapter seam (design/12 §3 fallback) and
// delivers to exactly ONE owner channel, chosen by the single-target selection in
// proactiveTarget: her explicit [渠道:...] choice first, then the platform she last
// used, then the whitelist default (rotating so it is not always the same channel).
// WeChat is a first-class candidate (it is whitelisted and, when connected, the
// recent-active/fallback selection may pick it).
//
// When the owner profile has no whitelisted account that is backed by a connected
// adapter it returns a clear error so the caller records the reason rather than
// silently dropping the push.
func (b *Bridge) SendProactive(ctx context.Context, msg adapter.UnifiedMessage) error {
if err := ctx.Err(); err != nil {
return err
}
target, ok := b.proactiveTarget(msg)
target, ok := b.proactiveTarget(ctx, msg)
if !ok {
return fmt.Errorf("channelbridge: no owner IM channel for proactive push")
return fmt.Errorf("channelbridge: no connected owner IM channel for proactive push")
}
ad := b.adapterForPlatform(target.platform)
if ad == nil {
@@ -57,34 +68,150 @@ func (b *Bridge) SendProactive(ctx context.Context, msg adapter.UnifiedMessage)
return nil
}
// proactiveTarget resolves the owner account a proactive push should reach:
// msg.Platform, when it names one of the owner's whitelisted platforms, selects
// that account; otherwise the first whitelisted owner channel (with a non-empty
// account id) is used. A nil owner or an empty whitelist yields !ok.
func (b *Bridge) proactiveTarget(msg adapter.UnifiedMessage) (proactiveTarget, bool) {
if b.owner == nil {
return proactiveTarget{}, false
}
accounts := b.owner.Accounts
// proactiveTarget resolves the single owner account a proactive push should reach.
// The range is every whitelisted owner channel that is backed by a connected
// adapter (WeChat included), and the choice follows the backthink priority:
//
// 1. A concrete msg.Platform (her [渠道:...] choice) that is whitelisted AND
// connected selects that channel.
// 2. The channel she most recently used in the main session (an owner/dialog
// message on a whitelisted, connected platform) is preferred.
// 3. Otherwise the platform that the whitelist default selects, rotating from a
// cursor so the fallback is not always the same channel (e.g. always kook).
//
// A nil owner or an empty whitelist yields !ok, as does a whitelist with no
// connected adapter.
func (b *Bridge) proactiveTarget(ctx context.Context, msg adapter.UnifiedMessage) (proactiveTarget, bool) {
accounts := b.ownerAccounts()
if len(accounts) == 0 {
return proactiveTarget{}, false
}
platform := strings.ToLower(strings.TrimSpace(msg.Platform))
if platform != "" {
for _, acct := range accounts {
if acct.AccountID != "" && strings.EqualFold(acct.Platform, platform) {
return proactiveTarget{acct.Platform, acct.AccountID}, true
}
}
}
for _, acct := range accounts {
if acct.AccountID != "" {
if !isGenericProactivePlatform(platform) {
if acct, ok := matchOwnerAccount(accounts, platform); ok && b.hasConnectedAdapter(acct.Platform) {
return proactiveTarget{acct.Platform, acct.AccountID}, true
}
}
if acct, ok := b.recentActiveAccount(ctx, accounts); ok {
return proactiveTarget{acct.Platform, acct.AccountID}, true
}
if acct, ok := b.nextConnectedAccount(accounts); ok {
return proactiveTarget{acct.Platform, acct.AccountID}, true
}
return proactiveTarget{}, false
}
// ownerAccounts returns the owner's whitelisted accounts that carry an account id,
// in whitelist order. A nil owner or an empty whitelist yields nil.
func (b *Bridge) ownerAccounts() []user.OwnerAccount {
if b.owner == nil {
return nil
}
out := make([]user.OwnerAccount, 0, len(b.owner.Accounts))
for _, a := range b.owner.Accounts {
if a.AccountID != "" {
out = append(out, a)
}
}
if len(out) == 0 {
return nil
}
return out
}
// matchOwnerAccount returns the owner account whose platform equals platform,
// case-insensitively.
func matchOwnerAccount(accounts []user.OwnerAccount, platform string) (user.OwnerAccount, bool) {
for _, a := range accounts {
if strings.EqualFold(a.Platform, platform) {
return a, true
}
}
return user.OwnerAccount{}, false
}
// recentActiveAccount returns the owner account for the most recent main-session
// message whose platform is a whitelisted, connected owner channel — the "she is
// active there" signal. A nil history store, a failed read or an empty tail yields
// ok=false so selection falls through to the default rather than guessing.
func (b *Bridge) recentActiveAccount(ctx context.Context, accounts []user.OwnerAccount) (user.OwnerAccount, bool) {
if b.history == nil {
return user.OwnerAccount{}, false
}
recent, err := b.history.Recent(ctx, history.MainSessionID, proactiveRecentCount)
if err != nil || len(recent) == 0 {
return user.OwnerAccount{}, false
}
// Recent is oldest-first; walk newest-first so the most recent channel wins.
for i := len(recent) - 1; i >= 0; i-- {
p := strings.ToLower(strings.TrimSpace(recent[i].Platform))
if p == "" || isGenericProactivePlatform(p) {
continue
}
if acct, ok := matchOwnerAccount(accounts, p); ok && b.hasConnectedAdapter(acct.Platform) {
return acct, true
}
}
return user.OwnerAccount{}, false
}
// nextConnectedAccount returns the next whitelisted owner account with a connected
// adapter, advancing a cursor so the no-signal fallback rotates instead of always
// landing on the first whitelisted channel (e.g. always kook). It holds the bridge
// lock to read the adapter map and update the cursor atomically.
func (b *Bridge) nextConnectedAccount(accounts []user.OwnerAccount) (user.OwnerAccount, bool) {
b.mu.Lock()
defer b.mu.Unlock()
n := len(accounts)
for i := 0; i < n; i++ {
idx := (b.proactiveCursor + i) % n
a := accounts[idx]
if b.hasConnectedAdapterLocked(a.Platform) {
b.proactiveCursor = (idx + 1) % n
return a, true
}
}
return user.OwnerAccount{}, false
}
// hasConnectedAdapter reports whether a registered adapter with this base platform
// is currently connected, so a channel is only ever selected when it can actually
// deliver a message.
func (b *Bridge) hasConnectedAdapter(platform string) bool {
b.mu.RLock()
defer b.mu.RUnlock()
return b.hasConnectedAdapterLocked(platform)
}
// hasConnectedAdapterLocked is hasConnectedAdapter without taking the lock; the
// caller must hold b.mu (read or write).
func (b *Bridge) hasConnectedAdapterLocked(platform string) bool {
for name, a := range b.adapters {
if strings.EqualFold(basePlatform(name), platform) && a.IsConnected() {
return true
}
}
return false
}
// isGenericProactivePlatform reports whether platform is a routing keyword rather
// than a concrete channel id. Only these fall through to the recent-active / default
// selection; a concrete id must resolve to a whitelisted, connected channel before
// it is honored, so an explicit channel choice is never silently replaced by a
// different channel.
func isGenericProactivePlatform(platform string) bool {
switch platform {
case "", "cyrene-backthink":
return true
default:
return false
}
}
// adapterForPlatform returns a registered adapter whose base platform matches
// platform (multi-account names like "kook:3be..." resolve to their bare base),
// preferring a connected one so a dead account is only tried when it is the only
+169 -19
View File
@@ -8,26 +8,36 @@ import (
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/session"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/loop"
"git.yeij.top/AskaEth/Cyrene_v2/internal/user"
)
func newProactiveBridge(t *testing.T, owner *user.OwnerProfile, ad *fakeAdapter) *Bridge {
func newProactiveBridge(t *testing.T, owner *user.OwnerProfile, ads ...*fakeAdapter) *Bridge {
t.Helper()
return newProactiveBridgeHist(t, owner, nil, ads...)
}
// newProactiveBridgeHist is newProactiveBridge with a history store injected, so a
// test can supply a recent window for the "she was last active here" selection.
func newProactiveBridgeHist(t *testing.T, owner *user.OwnerProfile, hist history.HistoryStore, ads ...*fakeAdapter) *Bridge {
t.Helper()
chat := &stubChatter{res: &loop.Result{Text: "hi"}}
sess := &stubSessions{sess: session.Session{SessionID: "sess-1", Owner: true, MemWritable: true}}
b, err := New(Options{Loop: chat, Sessions: sess, Owner: owner})
b, err := New(Options{Loop: chat, Sessions: sess, Owner: owner, History: hist})
if err != nil {
t.Fatalf("new bridge: %v", err)
}
if ad != nil {
b.Add(ad)
for _, ad := range ads {
if ad != nil {
b.Add(ad)
}
}
return b
}
// proactiveMsg builds a minimal autonomous proactive message as backthink's
// buildProactiveMessage would (no channel targeting yet).
// buildProactiveMessage would for a no-channel decision (the generic sentinel).
func proactiveMsg(content string) adapter.UnifiedMessage {
return adapter.UnifiedMessage{
Platform: "cyrene-backthink",
@@ -38,9 +48,9 @@ func proactiveMsg(content string) adapter.UnifiedMessage {
}
}
// TestBridge_SendProactive_OwnerChannel verifies a proactive push lands on the
// owner's IM channel: the adapter for the owner's platform is selected and the
// owner account id is threaded as the DM peer.
// TestBridge_SendProactive_OwnerChannel verifies a proactive push with no signal
// falls back to a whitelisted owner channel: the adapter for the owner's platform
// is selected and the owner account id is threaded as the DM peer.
func TestBridge_SendProactive_OwnerChannel(t *testing.T) {
ad := &fakeAdapter{name: "telegram", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{{Platform: "telegram", AccountID: "100"}}}
@@ -68,7 +78,8 @@ func TestBridge_SendProactive_OwnerChannel(t *testing.T) {
}
// TestBridge_SendProactive_PlatformHintSelectsAccount verifies msg.Platform
// selects the matching owner account when one exists, rather than defaulting.
// selects the matching owner account when one exists and is connected, rather
// than defaulting to another channel.
func TestBridge_SendProactive_PlatformHintSelectsAccount(t *testing.T) {
ad := &fakeAdapter{name: "kook", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{
@@ -91,32 +102,171 @@ func TestBridge_SendProactive_PlatformHintSelectsAccount(t *testing.T) {
}
}
// TestBridge_SendProactive_NoOwnerChannel verifies a clearly-worded error when the
// owner profile has no whitelisted account, so the caller records the reason.
// TestBridge_SendProactive_DecisionHintPriority verifies a concrete [渠道:...]
// decision beats the recent-active platform: even though she last used WeChat, an
// explicit kook choice is honored (and still only one channel is used).
func TestBridge_SendProactive_DecisionHintPriority(t *testing.T) {
kook := &fakeAdapter{name: "kook", connected: true}
weixin := &fakeAdapter{name: "weixin-ilink", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{
{Platform: "telegram", AccountID: "100"},
{Platform: "weixin-ilink", AccountID: "o9cq802QPKPscBenJAp-SMZPBlnQ@im.wechat"},
{Platform: "kook", AccountID: "329284282"},
}}
hist := &contextHistory{recent: []history.Message{{Role: history.RoleUser, Platform: "weixin-ilink", Content: "hi", CreatedAt: 2}}}
b := newProactiveBridgeHist(t, owner, hist, kook, weixin)
msg := proactiveMsg("洗完了")
msg.Platform = "kook"
if err := b.SendProactive(context.Background(), msg); err != nil {
t.Fatalf("SendProactive err = %v", err)
}
if len(kook.sends) != 1 {
t.Fatalf("kook sends = %d, want 1 (explicit choice beats recent-active)", len(kook.sends))
}
if len(weixin.sends) != 0 {
t.Fatalf("weixin sends = %d, want 0 (only one channel per push)", len(weixin.sends))
}
if kook.sends[0].Platform != "kook" || kook.sends[0].SenderID != "329284282" {
t.Fatalf("target = %q/%q, want the kook owner account", kook.sends[0].Platform, kook.sends[0].SenderID)
}
}
// TestBridge_SendProactive_RecentActivePlatform verifies a no-decision push lands
// on the channel she used most recently, skipping the web session (web is not a
// whitelisted IM account) and honoring a whitelisted, connected IM channel.
func TestBridge_SendProactive_RecentActivePlatform(t *testing.T) {
kook := &fakeAdapter{name: "kook", connected: true}
weixin := &fakeAdapter{name: "weixin-ilink", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{
{Platform: "kook", AccountID: "329284282"},
{Platform: "weixin-ilink", AccountID: "o9cq802QPKPscBenJAp-SMZPBlnQ@im.wechat"},
}}
// Recent is oldest-first: the newest message is the web session, then WeChat,
// then kook. The web session is skipped (not whitelisted), so the most recent
// whitelisted, connected channel — WeChat — is chosen.
hist := &contextHistory{recent: []history.Message{
{Role: history.RoleUser, Platform: "kook", Content: "一早聊过", CreatedAt: 1},
{Role: history.RoleUser, Platform: "weixin-ilink", Content: "微信聊的", CreatedAt: 2},
{Role: history.RoleAssistant, Platform: "web", Content: "网页端", CreatedAt: 3},
}}
b := newProactiveBridgeHist(t, owner, hist, kook, weixin)
if err := b.SendProactive(context.Background(), proactiveMsg("记得喝水哦")); err != nil {
t.Fatalf("SendProactive err = %v", err)
}
if len(weixin.sends) != 1 {
t.Fatalf("weixin sends = %d, want 1 (recent-active picks WeChat)", len(weixin.sends))
}
if len(kook.sends) != 0 {
t.Fatalf("kook sends = %d, want 0", len(kook.sends))
}
if weixin.sends[0].Platform != "weixin-ilink" {
t.Fatalf("platform = %q, want weixin-ilink", weixin.sends[0].Platform)
}
}
// TestBridge_SendProactive_WeChatCanBeSelected verifies WeChat is a first-class
// proactive target: with a WeChat account whitelisted and its adapter connected, a
// no-signal push lands on it rather than always defaulting to kook.
func TestBridge_SendProactive_WeChatCanBeSelected(t *testing.T) {
weixin := &fakeAdapter{name: "weixin-ilink", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{{Platform: "weixin-ilink", AccountID: "o9cq802QPKPscBenJAp-SMZPBlnQ@im.wechat"}}}
b := newProactiveBridge(t, owner, weixin)
if err := b.SendProactive(context.Background(), proactiveMsg("记得喝水哦")); err != nil {
t.Fatalf("SendProactive err = %v", err)
}
if len(weixin.sends) != 1 {
t.Fatalf("sends = %d, want 1", len(weixin.sends))
}
if weixin.sends[0].Platform != "weixin-ilink" {
t.Fatalf("platform = %q, want weixin-ilink", weixin.sends[0].Platform)
}
if weixin.sends[0].Content != "记得喝水哦" {
t.Fatalf("content = %q, want the proactive text", weixin.sends[0].Content)
}
}
// TestBridge_SendProactive_NoSignalFallbackRotates verifies the no-signal fallback
// rotates across connected whitelisted channels (instead of always kook), and that
// each push reaches exactly one channel.
func TestBridge_SendProactive_NoSignalFallbackRotates(t *testing.T) {
kook := &fakeAdapter{name: "kook", connected: true}
weixin := &fakeAdapter{name: "weixin-ilink", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{
{Platform: "kook", AccountID: "329284282"},
{Platform: "weixin-ilink", AccountID: "o9cq802QPKPscBenJAp-SMZPBlnQ@im.wechat"},
}}
b := newProactiveBridge(t, owner, kook, weixin)
if err := b.SendProactive(context.Background(), proactiveMsg("第一次")); err != nil {
t.Fatalf("first SendProactive err = %v", err)
}
if err := b.SendProactive(context.Background(), proactiveMsg("第二次")); err != nil {
t.Fatalf("second SendProactive err = %v", err)
}
if len(kook.sends) != 1 || len(weixin.sends) != 1 {
t.Fatalf("sends = kook:%d weixin:%d, want 1 each (one channel per push, rotating)",
len(kook.sends), len(weixin.sends))
}
if kook.sends[0].Content != "第一次" {
t.Fatalf("kook content = %q, want '第一次'", kook.sends[0].Content)
}
if weixin.sends[0].Content != "第二次" {
t.Fatalf("weixin content = %q, want '第二次'", weixin.sends[0].Content)
}
}
// TestBridge_SendProactive_HintNotWhitelisted_FallsBackToWeChat verifies a concrete
// decision channel that is NOT whitelisted degrades to a whitelisted, connected
// owner channel rather than erroring or landing on a non-owner channel. This is
// how WeChat becomes reachable even though the old default never considered it.
func TestBridge_SendProactive_HintNotWhitelisted_FallsBackToWeChat(t *testing.T) {
weixin := &fakeAdapter{name: "weixin-ilink", connected: true}
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{{Platform: "weixin-ilink", AccountID: "o9cq802QPKPscBenJAp-SMZPBlnQ@im.wechat"}}}
b := newProactiveBridge(t, owner, weixin)
msg := proactiveMsg("记得喝水哦")
msg.Platform = "kook" // kook is not whitelisted for this owner
if err := b.SendProactive(context.Background(), msg); err != nil {
t.Fatalf("SendProactive err = %v (a non-whitelisted hint should fall back, not error)", err)
}
if len(weixin.sends) != 1 {
t.Fatalf("sends = %d, want 1 (fell back to the whitelisted WeChat channel)", len(weixin.sends))
}
if weixin.sends[0].Platform != "weixin-ilink" {
t.Fatalf("platform = %q, want weixin-ilink", weixin.sends[0].Platform)
}
}
// TestBridge_SendProactive_NoOwnerChannel verifies a clear error when the owner
// profile has no whitelisted account, so the caller records the reason.
func TestBridge_SendProactive_NoOwnerChannel(t *testing.T) {
b := newProactiveBridge(t, &user.OwnerProfile{}, nil)
b := newProactiveBridge(t, &user.OwnerProfile{})
err := b.SendProactive(context.Background(), proactiveMsg("hi"))
if err == nil {
t.Fatalf("expected an error for a missing owner channel, got nil")
}
if !strings.Contains(err.Error(), "no owner IM channel") {
t.Fatalf("error = %q, want a 'no owner IM channel' note", err)
if !strings.Contains(err.Error(), "no connected owner IM channel") {
t.Fatalf("error = %q, want a 'no connected owner IM channel' note", err)
}
}
// TestBridge_SendProactive_NoAdapter verifies the error names the platform when the
// owner has a whitelisted channel but no adapter is registered for it.
// TestBridge_SendProactive_NoAdapter verifies the error when the owner has a
// whitelisted channel but no adapter is registered/connected for it.
func TestBridge_SendProactive_NoAdapter(t *testing.T) {
owner := &user.OwnerProfile{Accounts: []user.OwnerAccount{{Platform: "kook", AccountID: "329284282"}}}
b := newProactiveBridge(t, owner, nil)
b := newProactiveBridge(t, owner)
err := b.SendProactive(context.Background(), proactiveMsg("hi"))
if err == nil {
t.Fatalf("expected an error for a missing adapter, got nil")
}
if !strings.Contains(err.Error(), "no adapter for owner platform") {
t.Fatalf("error = %q, want a 'no adapter for owner platform' note", err)
if !strings.Contains(err.Error(), "no connected owner IM channel") {
t.Fatalf("error = %q, want a 'no connected owner IM channel' note", err)
}
}