Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 手机点开伙伴推送进入伙伴聊天并清除未读 (#5070)
Chris Zhanga1e5ff3c3521
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.tsindex 9313b1ce44..7d5e753c92 100644--- a/apps/desktop/src/main/__tests__/notificationService.test.ts+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts@@ -473,6 +473,55 @@ describe('notificationService — channels 分发', () => {expect(markSessionNeedsAttention).toHaveBeenCalledWith('s1');});+ it('routes a teammate reply push to that teammate chat', async () => {+ const { initNotificationService } = await freshService();+ initNotificationService(baseDeps(makeFeishuIm('ou_owner')));+ readSessionNotificationPreview.mockImplementation(async (_id, includeReply = true) => ({+ teammateName: 'Cindy', teammateBotId: 'bot-1', eventId: 'turn:100:200',+ ...(includeReply ? { reply: { clientId: 'final-2', text: 'Done' } } : {}),+ }));+ await invokeHandler({ sessionId: 's1', title: 'Cindy', kind: 'done', channels: { desktop: false, feishu: false, mobile: true } });+ await flushAsync();+ expect(sendMobileSessionNotify).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 's1', teammateBotId: 'bot-1' }));+ });++ it('routes a teammate approval push to the teammate chat without changing its title or fallback', async () => {+ const { initNotificationService } = await freshService();+ initNotificationService(baseDeps(makeFeishuIm('ou_owner')));+ readSessionNotificationPreview.mockResolvedValue({ teammateName: 'Cindy', teammateBotId: 'bot-1' });+ await invokeHandler({ sessionId: 's1', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true } });+ await flushAsync();+ expect(sendMobileSessionNotify).toHaveBeenCalledWith({+ sessionId: 's1', title: 'Hello', kind: 'needs-reply', generation: 7, teammateBotId: 'bot-1',+ });+ // A failed identity read keeps the ordinary push.+ sendMobileSessionNotify.mockClear();+ readSessionNotificationPreview.mockRejectedValueOnce(new Error('read unavailable'));+ await invokeHandler({ sessionId: 's2', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true } });+ await flushAsync();+ expect(sendMobileSessionNotify).toHaveBeenCalledWith({ sessionId: 's2', title: 'Hello', kind: 'needs-reply', generation: 7 });+ });++ it('does not let a slow teammate lookup spend the approval push preview window', async () => {+ const { initNotificationService } = await freshService();+ initNotificationService(baseDeps(makeFeishuIm('ou_owner')));+ vi.useFakeTimers();+ readSessionNotificationPreview.mockReturnValueOnce(new Promise(() => {}));+ let releaseDrain!: () => void;+ drainPersistQueue.mockReturnValueOnce(new Promise<void>((resolve) => { releaseDrain = resolve; }));+ latestMessageText.mockResolvedValueOnce('要删除 build 目录吗?');+ await registeredHandlers.get('notification:show-session-event')!({}, {+ sessionId: 's1', title: 'Hello', kind: 'needs-reply', channels: { desktop: false, feishu: false, mobile: true },+ });+ // The reply read starts without waiting for the routing lookup.+ releaseDrain();+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sendMobileSessionNotify).toHaveBeenCalledTimes(1);+ expect(sendMobileSessionNotify).toHaveBeenCalledWith({+ sessionId: 's1', title: 'Hello', kind: 'needs-reply', generation: 7, detail: '要删除 build 目录吗?',+ });+ });+it('mobile 正文带最近 assistant 内容;error 终态不取(无可靠错误正文来源)', async () => {const { initNotificationService } = await freshService();initNotificationService(baseDeps(makeFeishuIm('ou_owner')));diff --git a/apps/desktop/src/main/__tests__/sessionNotificationPreview.test.ts b/apps/desktop/src/main/__tests__/sessionNotificationPreview.test.tsindex a96b5078b7..fd324b72ce 100644--- a/apps/desktop/src/main/__tests__/sessionNotificationPreview.test.ts+++ b/apps/desktop/src/main/__tests__/sessionNotificationPreview.test.ts@@ -28,15 +28,15 @@ function add(id: string, role: string, content: string, createdAt: number, meta}it('reads canonical teammate identity and this turn final from the durable transcript', async () => {add('final-2', 'assistant', '**完成**', 150, { turnCompleted: true, assistantPhase: 'final_answer' });- expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', reply: { clientId: 'final-2', text: '**完成**' }, eventId: 'turn:100:200' });+ expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', teammateBotId: 'bot-1', reply: { clientId: 'final-2', text: '**完成**' }, eventId: 'turn:100:200' });});it('suppresses an old idle event after a new input started', async () => {drizzle(sqlite).update(sessions).set({ activeTurnStartedAt: 300 }).run();- expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', suppress: true });+ expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', teammateBotId: 'bot-1', suppress: true });});it('does not reuse an older final in a tool-only completed turn', async () => {add('old', 'assistant', 'Old answer', 10, { turnCompleted: true });- expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', eventId: 'turn:100:200' });+ expect(await readSessionNotificationPreview('main')).toEqual({ teammateName: 'Cindy', teammateBotId: 'bot-1', eventId: 'turn:100:200' });});it('uses insertion order for a tool and final arriving in the same millisecond', async () => {add('z-tool', 'tool_result', 'tool output', 150);@@ -50,7 +50,7 @@ it('keeps completion identity stable before and after the final reply is persistconst before = await readSessionNotificationPreview('main', false);add('final-2', 'assistant', 'Finished', 150, { turnCompleted: true });const after = await readSessionNotificationPreview('main');- expect(before).toEqual({ teammateName: 'Cindy', eventId: 'turn:100:200' });+ expect(before).toEqual({ teammateName: 'Cindy', teammateBotId: 'bot-1', eventId: 'turn:100:200' });expect(after.eventId).toBe(before.eventId);expect(after.reply?.text).toBe('Finished');});diff --git a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.tsindex c06dc1b825..721caa276c 100644--- a/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mobileNotify.test.ts@@ -1,6 +1,6 @@import { createHash } from 'node:crypto';import { describe, expect, it } from 'vitest';-import { NOTIFY_TITLE_MAX_LENGTH, NOTIFY_BODY_MAX_LENGTH } from '@cindy/device-link';+import { NOTIFY_TITLE_MAX_LENGTH, NOTIFY_BODY_MAX_LENGTH, NOTIFY_DEEP_LINK_MAX_LENGTH } from '@cindy/device-link';import { MobileNotifyDeduper, buildSessionNotifyPayload } from '../mobileNotify';describe('buildSessionNotifyPayload', () => {@@ -67,6 +67,24 @@ describe('buildSessionNotifyPayload', () => {expect(long.title).toHaveLength(NOTIFY_TITLE_MAX_LENGTH);});+ it('opens a teammate main chat as that teammate, with the same params the roster uses', () => {+ const payload = buildSessionNotifyPayload({ ...base, teammateBotId: 'bot/1' });+ expect(payload.deepLink).toBe(+ '/sessions/session-1234?deviceId=desktop-abcd&resourceCollectionId=teammates&resourceId=bot%2F1&resourceKind=bot',+ );+ const query = new URLSearchParams(payload.deepLink.split('?')[1]);+ expect(Object.fromEntries(query)).toEqual({+ deviceId: 'desktop-abcd', resourceCollectionId: 'teammates', resourceId: 'bot/1', resourceKind: 'bot',+ });+ // Ordinary tasks keep the original link.+ expect(buildSessionNotifyPayload(base).deepLink).toBe('/sessions/session-1234?deviceId=desktop-abcd');+ });++ it('keeps the ordinary task link when the teammate link would exceed the protocol limit', () => {+ const payload = buildSessionNotifyPayload({ ...base, teammateBotId: 'b'.repeat(NOTIFY_DEEP_LINK_MAX_LENGTH) });+ expect(payload.deepLink).toBe('/sessions/session-1234?deviceId=desktop-abcd');+ });+it('deepLink 对特殊字符做 URL 编码', () => {const payload = buildSessionNotifyPayload({ ...base, sessionId: 'a/b?c' });expect(payload.deepLink).toBe('/sessions/a%2Fb%3Fc?deviceId=desktop-abcd');diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 8f74beaaf3..0c654e8d57 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1876,6 +1876,8 @@ export function sendMobileSessionNotify(payload: {detail?: string;fallbackBody?: string;eventId?: string;+ /** 伙伴主任务的 Bot id;让手机按伙伴聊天打开通知。 */+ teammateBotId?: string;/*** 发起时捕获的 getMobileNotifyGeneration()。调用路径里有 await(取正文/等* 其它通道)时必传:与当前代次不一致说明期间发生过登出/失去持有权,任务@@ -1908,6 +1910,7 @@ export function sendMobileSessionNotify(payload: {selfDeviceId,fallbackBody: payload.fallbackBody ?? getSessionNotificationBody(payload.kind),detail: payload.detail,+ ...(payload.teammateBotId ? { teammateBotId: payload.teammateBotId } : {}),}),);if (sent) {diff --git a/apps/desktop/src/main/device-link/mobileNotify.ts b/apps/desktop/src/main/device-link/mobileNotify.tsindex 5401f59ce7..b5bf76fe54 100644--- a/apps/desktop/src/main/device-link/mobileNotify.ts+++ b/apps/desktop/src/main/device-link/mobileNotify.ts@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';import { notificationPreview } from '../notificationPreview.js';import {NOTIFY_BODY_MAX_LENGTH,+ NOTIFY_DEEP_LINK_MAX_LENGTH,NOTIFY_TITLE_MAX_LENGTH,type NotifyCategory,type NotifyPayload,@@ -37,6 +38,11 @@ export function buildSessionNotifyPayload(opts: {fallbackBody: string;/** 内容摘要(可选):折叠空白后按协议上限截断 */detail?: string;+ /**+ * 伙伴主任务的 Bot id。带上后手机把通知打开为该伙伴的聊天(伙伴页头、抽屉与已读),+ * 而不是普通任务视图;参数与名册进入聊天时相同,旧手机同样识别,缺省保持原深链。+ */+ teammateBotId?: string;}): NotifyPayload {const safeTitle = (opts.title.trim() || opts.sessionId.slice(0, 8)).slice(0,@@ -47,7 +53,7 @@ export function buildSessionNotifyPayload(opts: {category: CATEGORY_BY_KIND[opts.kind],title: safeTitle,body: detail || opts.fallbackBody.slice(0, NOTIFY_BODY_MAX_LENGTH),- deepLink: `/sessions/${encodeURIComponent(opts.sessionId)}?deviceId=${encodeURIComponent(opts.selfDeviceId)}`,+ deepLink: sessionDeepLink(opts.sessionId, opts.selfDeviceId, opts.teammateBotId),// 同会话的通知在系统层合并(APNs collapse-id / thread-id);混入 srcDeviceId,// 多台桌面推同名会话时互不顶替。原样拼接不可行:deviceId 可能是 64 位// machineId,拼出 100+ 字符会被 APNs 的 64 字节 collapse-id 上限截断成@@ -60,6 +66,14 @@ export function buildSessionNotifyPayload(opts: {};}+function sessionDeepLink(sessionId: string, deviceId: string, teammateBotId?: string): string {+ const base = `/sessions/${encodeURIComponent(sessionId)}?deviceId=${encodeURIComponent(deviceId)}`;+ if (!teammateBotId) return base;+ const teammate = `${base}&resourceCollectionId=teammates&resourceId=${encodeURIComponent(teammateBotId)}&resourceKind=bot`;+ // An oversized link is rejected by the protocol; the ordinary task link still opens the chat.+ return teammate.length <= NOTIFY_DEEP_LINK_MAX_LENGTH ? teammate : base;+}+/*** 有回复标识时按同 session + 同 kind + 回复去重;不同回复不受时间窗口限制。* 无标识的调度事件保留短窗兜底,并与同轮的持久 turn 标识对账。覆盖 renderer 事件源的重复触发diff --git a/apps/desktop/src/main/localDb/sessionNotificationPreview.ts b/apps/desktop/src/main/localDb/sessionNotificationPreview.tsindex cb499a1992..3a6f0d88d4 100644--- a/apps/desktop/src/main/localDb/sessionNotificationPreview.ts+++ b/apps/desktop/src/main/localDb/sessionNotificationPreview.ts@@ -7,6 +7,8 @@ import { selectNotificationReply } from './sessionNotificationPreview.logic.js';export interface SessionNotificationPreview {teammateName?: string;+ /** The canonical Session's Bot, so remote controllers can open it as that teammate. */+ teammateBotId?: string;reply?: { clientId: string; text: string };eventId?: string;suppress?: boolean;@@ -18,19 +20,19 @@ export async function readSessionNotificationPreview(sessionId: string, includeRconst rows = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);const current = rows[0];if (!current) return {};- const profile = current.source === 'bot' ? await db.select({ name: botProfiles.displayName })+ const profile = current.source === 'bot' ? await db.select({ id: botProfiles.id, name: botProfiles.displayName }).from(botProfiles).innerJoin(botSessionLinks, eq(botSessionLinks.botId, botProfiles.id)).where(and(eq(botSessionLinks.sessionId, sessionId), eq(botSessionLinks.role, 'canonical'))).get() : undefined;- const teammateName = profile?.name;+ const teammate = profile ? { teammateName: profile.name, teammateBotId: profile.id } : {};// A delayed idle event may arrive after the next input has already started.// Do not notify that unfinished turn or reuse a pre-upgrade historical final.const startedAt = current.activeTurnStartedAt ?? 0;const endedAt = current.lastTurnEndedAt ?? 0;- if (startedAt > endedAt) return { teammateName, suppress: true };- if (startedAt <= 0) return { teammateName };+ if (startedAt > endedAt) return { ...teammate, suppress: true };+ if (startedAt <= 0) return teammate;// Stable across preview readiness: a retry after a fallback must not notify twice.const eventId = `turn:${startedAt}:${endedAt}`;- if (!includeReply) return { teammateName, eventId };+ if (!includeReply) return { ...teammate, eventId };const recent = await db.select().from(messages).where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt))).orderBy(desc(messages.createdAt), desc(sql`rowid`)).limit(100);const reply = selectNotificationReply(recent.map((row) => {@@ -42,5 +44,5 @@ export async function readSessionNotificationPreview(sessionId: string, includeRtopLevel: isTopLevelTitleAssistant(meta),};}), Math.max(startedAt, current.clearedAt ?? 0));- return { teammateName, reply, eventId };+ return { ...teammate, reply, eventId };}diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.tsindex 9fa7427426..a9688e9c98 100644--- a/apps/desktop/src/main/notificationService.ts+++ b/apps/desktop/src/main/notificationService.ts@@ -221,14 +221,23 @@ export function initNotificationService(deps: NotificationServiceDeps): void {// a timeout is not a dedupe window and never causes a second late toast.void (async () => {let preview: SessionNotificationPreview | undefined;+ // Only routes the phone to the teammate chat; titles and fallbacks stay per kind.+ let teammateBotId: string | undefined;let postDrainPreviewReady = false;let detail: string | undefined;if (kind === 'done' || (kind === 'needs-reply' && channels?.mobile === true)) {let finished = false;let timer: ReturnType<typeof setTimeout> | undefined;+ // Routing is optional: read it beside the reply so it never spends the+ // preview's wait window, and a failed identity read costs nothing.+ const routeRead = kind === 'needs-reply'+ ? readSessionNotificationPreview(sessionId, false).then(+ (identity) => { if (!finished) teammateBotId = identity.teammateBotId; },+ () => undefined)+ : undefined;try {await Promise.race([- (async () => {+ Promise.all([(async () => {if (kind === 'done') {// Read the teammate identity first so a blocked write still// has the correct fallback. This snapshot may predate the@@ -238,6 +247,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {// message broadcaster. Keep only the teammate name here;// an old event ID must never identify this completion.preview = { teammateName: identity.teammateName };+ teammateBotId = identity.teammateBotId;}if (finished || !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;await drainPersistQueue();@@ -250,7 +260,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {} else {detail = await latestMessageText(sessionId, 'assistant');}- })(),+ })(), routeRead]),new Promise<void>((resolve) => { timer = setTimeout(resolve, NOTIFICATION_PREVIEW_WAIT_MS); }),]);} catch (err) {@@ -284,6 +294,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {const mobileKey = replyNotificationKey(generation, sessionId, 'mobile');const feishuKey = replyNotificationKey(ownerKey, sessionId, 'feishu');const fallbackBody = teammate ? getTeammateNotificationFallback() : undefined;+ const mobileTeammateBotId = preview?.teammateBotId ?? teammateBotId;if (wantDesktop && kind === 'done' && !wasReplyNotified(desktopKey, eventId)) {try {const accepted = showDesktopSessionEvent(getWindow, {@@ -302,6 +313,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {const accepted = sendMobileSessionNotify({sessionId, title: notificationTitle, kind, generation, ...(detail ? { detail } : {}),...(fallbackBody ? { fallbackBody } : {}), ...(mobileEventId ? { eventId: mobileEventId } : {}),+ ...(mobileTeammateBotId ? { teammateBotId: mobileTeammateBotId } : {}),});if (kind === 'done' && accepted) {notifiedReplies.set(mobileKey, eventId ? { eventId } : { fallbackSentAt: Date.now() });diff --git a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts b/apps/mobile/src/__tests__/mobilePushRecovery.test.tsindex 6e1c8e1aed..5af228e07d 100644--- a/apps/mobile/src/__tests__/mobilePushRecovery.test.ts+++ b/apps/mobile/src/__tests__/mobilePushRecovery.test.ts@@ -306,6 +306,15 @@ describe('progressive push snapshots', () => {expect(route).toBe('/sessions/a?deviceId=d¬ificationResponse=id%3Apush%262#tail');expect(notificationRecoveryRoute('/sessions/a', '1')).toBe('/sessions/a?notificationResponse=1');});++ it('keeps the teammate resource params a host adds so the chat opens as that teammate', () => {+ const route = notificationRecoveryRoute(+ '/sessions/chat?deviceId=mac&resourceCollectionId=teammates&resourceId=bot%2F1&resourceKind=bot', 'id:1');+ const query = new URLSearchParams(route.split('?')[1]);+ expect(route.startsWith('/sessions/chat?')).toBe(true);+ expect(Object.fromEntries(query)).toEqual({ deviceId: 'mac', resourceCollectionId: 'teammates',+ resourceId: 'bot/1', resourceKind: 'bot', notificationResponse: 'id:1' });+ });});describe('superseded recovery reads', () => {diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 206cc7fd80..61c696c9f3 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -398,3 +398,12 @@ Seed 2.1 Pro 按火山方舟官方示例选择 Chat Completions 为 Cindy 的标`compacting` 是上述公开阶段的一员,由运行时 `Compacting...` / `Compacting context…`状态触发,`compact_boundary` 或恢复生成结束它;不读取压缩摘要。该阶段使用客户端固定的“正在整理对话…”本地化文案,不走模型润色,仍沿用原有文字切换节奏。++## 伙伴通知深链++手机推送 `deepLink` 仍是 `/sessions/<sessionId>?deviceId=<hostDeviceId>`。会话属于伙伴的+canonical 主任务时,宿主额外追加 `resourceCollectionId=teammates&resourceId=<botId>&resourceKind=bot`,+与伙伴名册打开聊天时的路由参数相同:手机据此按伙伴聊天呈现(伙伴页头、导航与已读),并继续做既有的+会话来源与主机校验;这些参数不授予任何权限。已发布的手机版本本来就识别这组参数,不需要升级;+不识别它们的旧控制端仍按普通任务打开。拼接后超过 `NOTIFY_DEEP_LINK_MAX_LENGTH` 时回退为原深链。+委派的独立 Session 任务和普通任务不带这组参数。不修改 notify 帧结构、relay 或协议版本。