Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(agent-island): 修复群提醒恢复、停留和原生回退

Dash72141f89f7df
diff --git a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
index 6d6fbcca47..d442fab548 100644
--- a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
+++ b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
@@ -176,6 +176,11 @@ export class MacAgentIslandNativeHost {
return this.permanentlyFailed;
}
+ /** A buffered publish during startup is not delivery to a native window. */
+ get available(): boolean {
+ return this.ready && this.child !== null && !this.permanentlyFailed;
+ }
+
publish(
state: AgentIslandDisplayState,
frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[],
diff --git a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
index 7dcb7f6324..8e27ec8982 100644
--- a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
@@ -154,13 +154,16 @@ describe('MacAgentIslandNativeHost', () => {
const host = new MacAgentIslandNativeHost(createOptions());
expect(host.publish(createDisplayState(), createFrame())).toBe(true);
+ expect(host.available).toBe(false);
await vi.advanceTimersByTimeAsync(0);
expect(h.spawn).toHaveBeenCalledTimes(1);
(children[0].stdout as PassThrough).write(`${JSON.stringify({ type: 'ready' })}\n`);
await vi.advanceTimersByTimeAsync(0);
+ expect(host.available).toBe(true);
children[0].stdin.emit('error', new Error('write EPIPE'));
+ expect(host.available).toBe(false);
expect(children[0].kill).toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(999);
expect(h.spawn).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index 7be2aee736..70237cebea 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -581,13 +581,16 @@ describe('AgentIslandService native publishing', () => {
takePendingDeepLink();
const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);
const playSound = vi.fn();
- const nativeHost = { failed: false, publish, playSound, suspend: () => undefined };
+ const nativeHost = { failed: false, available: false, publish, playSound, suspend: () => undefined };
const service = new AgentIslandService({ getMainWindow: () => null, nativeHost });
syncEnabledForTest(service, publish);
const input = { groupId: 'group', name: 'Product', messageId: 'message', threadRootId: 'topic',
mentioned: true, preview: 'Chris: hello', lastMessageAt: 1, members: [] };
service.setGroupChat(input.groupId, input);
expect(publish.mock.calls.at(-1)![0].mode).toBe('compact');
+ expect(service.notifyGroupChat(input.groupId)).toBe(false);
+ expect(publish.mock.calls.at(-1)![0].mode).toBe('compact');
+ nativeHost.available = true;
expect(service.notifyGroupChat(input.groupId)).toBe(true);
expect(publish.mock.calls.at(-1)![0].displayPolicy).toBe('transient');
expect(playSound).not.toHaveBeenCalled();
@@ -656,6 +659,35 @@ describe('AgentIslandService native publishing', () => {
service.resetRuntimeState();
});
+ // #7307 review: accepted group input provenance exists before the avatar/identity read.
+ // Unit: done arriving during that read must never emit completion attention or sound.
+ it('silences a fast group reply before companion identity finishes loading', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ let finishIdentity!: (identity: AgentIslandCompanionIdentity | null) => void;
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', title: 'Chris', userSendAt: null,
+ workingDir: '/home', workspaceKind: null, source: 'bot' });
+ mocks.readAgentIslandCompanion.mockReturnValueOnce(new Promise(resolve => { finishIdentity = resolve; }));
+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);
+ const playSound = vi.fn();
+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish, playSound } });
+ syncEnabledForTest(service, publish);
+ service.handleUserPrompt({ sessionId: 'fast-lane' }, 'please help');
+ await vi.waitFor(() => expect(finishIdentity).toBeTypeOf('function'));
+ playSound.mockClear();
+ service.handleAgentEvent({ sessionId: 'fast-lane' }, { type: 'done', source: 'codex',
+ agentMeta: { botGroupLane: true }, data: { result: 'done' } });
+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);
+ expect(service.getSessionActivitySnapshot('fast-lane')).toBeNull();
+ expect(playSound).not.toHaveBeenCalled();
+ finishIdentity({ botId: 'bot', groupId: 'group', companion: { name: 'Chris', groupName: 'Product', hue: 'blue', glyph: 'C', glyphIsInitial: true } });
+ await vi.waitFor(() => expect((service as unknown as {
+ metadataCache: Map<string, { companion?: AgentIslandCompanionIdentity | null }>;
+ }).metadataCache.get('fast-lane')?.companion?.groupId).toBe('group'));
+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);
+ expect(playSound).not.toHaveBeenCalled();
+ service.resetRuntimeState();
+ });
+
// Old unread has no runtime event after restart. Verify the real IPC -> native -> read
// route, including owner fencing and stale-card rejection; existing event tests miss this (unit).
it('restores companion chats from the owner snapshot and reads offline chats locally', async () => {
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index a034fb4fc9..a008d949d2 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -132,13 +132,13 @@ describe('group message cards', () => {
expect(buildAgentIslandDisplayState(state, now + 1).pillSnapshot.attentionCount).toBe(0);
});
- it('coalesces a burst in place, does not extend its dwell, and lets a new mention alert', () => {
+ it.each([false, true])('coalesces a burst without extending its dwell (mention during dwell: %s)', mentionDuringDwell => {
const state = createAgentIslandState();
sync(state);
revealAgentIslandGroupChat(state, input.groupId, 100);
expect(buildAgentIslandDisplayState(state, 100).displayPolicy).toBe('transient');
const until = state.sessions.get('chat-group:group')!.revealUntil!;
- sync(state, { messageId: 'next', preview: 'Sam: next' }, 200);
+ sync(state, { messageId: 'next', preview: 'Sam: next', mentioned: mentionDuringDwell }, 200);
revealAgentIslandGroupChat(state, input.groupId, 200);
expect(state.sessions.get('chat-group:group')!.revealUntil).toBe(until);
expect(buildAgentIslandDisplayState(state, 200).sessions).toHaveLength(1);
@@ -146,7 +146,7 @@ describe('group message cards', () => {
sync(state, { mentioned: true }, until + 2);
revealAgentIslandGroupChat(state, input.groupId, until + 2);
expect(buildAgentIslandDisplayState(state, until + 2).sessions[0].groupChat?.mentionLabel).toBe('@you');
- expect(buildAgentIslandDisplayState(state, until + 2).displayPolicy).toBe('transient');
+ expect(buildAgentIslandDisplayState(state, until + 2).mode).toBe(mentionDuringDwell ? 'compact' : 'expanded');
});
it('keeps a pending approval above mentions, and pins existing rows under the pointer', () => {
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index cc5a80c3bf..be9e82026e 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -233,6 +233,7 @@ export interface AgentIslandServiceDeps {
interface AgentIslandNativeRenderer {
readonly failed: boolean;
+ readonly available?: boolean;
readonly headless?: boolean;
prepare?(): void;
publish(
@@ -863,7 +864,7 @@ export class AgentIslandService {
/** True means this surface owns the alert; otherwise the caller uses the OS notification. */
notifyGroupChat(groupId: string): boolean {
- if (!this.isEnabled() || this.headless || this.nativeHost.failed) return false;
+ if (!this.isEnabled() || this.headless || this.nativeHost.failed || this.nativeHost.available === false) return false;
const chat = this.state.sessions.get(groupChatIslandId(groupId))?.groupChat;
if (!chat) return false;
const window = this.deps.getMainWindow();
@@ -1105,7 +1106,7 @@ export class AgentIslandService {
suppressCompletionAttention,
// Direct IM sends bypass handleUserPrompt. Running preserves unread in the
// live state/ledger, so use that state (including any intervening read ack).
- preserveCompletionAttention: suppressCompletionAttention && !this.metadataCache.get(hydrated.sessionId)?.companion?.groupId && (
+ preserveCompletionAttention: suppressCompletionAttention && !this.isGroupLaneEvent(hydrated.sessionId, event) && (
event.turnOrigin?.surface === 'im'
? hasAgentIslandSessionAttention(this.state, hydrated.sessionId)
: this.hadAttentionBeforeSilencedCompletion(hydrated.sessionId)
@@ -1803,10 +1804,15 @@ export class AgentIslandService {
private isCompletionEventSilenced(sessionId: string, event: AgentEvent): boolean {
if (!isCompletionDoneEvent(event)) return false;
return event.agentMeta?.botTaskCoordination === true
- || !!this.metadataCache.get(sessionId)?.companion?.groupId
+ || this.isGroupLaneEvent(sessionId, event)
|| event.turnOrigin?.surface === 'im' || this.silencedSessionRunIds.has(sessionId);
}
+ private isGroupLaneEvent(sessionId: string, event: AgentEvent): boolean {
+ // Accepted-input provenance reaches this event independently of avatar loading.
+ return event.agentMeta?.botGroupLane === true || !!this.metadataCache.get(sessionId)?.companion?.groupId;
+ }
+
private hadAttentionBeforeSilencedRun(sessionId: string): boolean {
const runId = this.silencedSessionRunIds.get(sessionId);
return runId ? this.silencedRunHadAttention.get(runId) === true : false;
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index a17759bda1..919fa6883a 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -1650,6 +1650,8 @@ export function revealAgentIslandGroupChat(state: AgentIslandState, groupId: str
&& (!chat.input.mentioned || chat.lastAlertMention)) return;
chat.lastAlertAt = now;
chat.lastAlertMention = chat.input.mentioned;
+ // An @ replaces the content of a visible group card without restarting its dwell.
+ if (state.activeTransientSessionId === session.sessionId && session.revealUntil !== null && session.revealUntil > now) return;
// A pointer already on the island must not receive a surprise automatic reveal later.
if (!isPointerInsideIsland(state) && !state.hoverExpanded) enqueueTransientReveal(state, session, now, AGENT_ISLAND_REVEAL_DWELL_MS);
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 56624a16ad..f0c34f7b5d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -225,7 +225,9 @@ describe('Chat Server result delivery and refresh', () => {
await vi.advanceTimersByTimeAsync(150);
expect(attention.mock.calls.at(-1)?.[1]).toBeNull();
snapshot.reads[0].muted = false;
- await service.getGroup(roomId);
+ readChanged();
+ await vi.advanceTimersByTimeAsync(150);
+ expect(attention.mock.calls.at(-1)?.[1]).toMatchObject({ messageId: message('3').id, mentioned: false });
const received = (seq: string) => socket.emit('message', JSON.stringify({ type: 'changes', scope: `conversation:${roomId}`, cursor: seq,
changes: [{ type: 'message.created', entityId: message(seq).id }] }));
received('3');
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 3397da2b1d..a7885050fb 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -588,7 +588,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
pendingChanges.set(roomId, setTimeout(() => {
pendingChanges.delete(roomId);
if (!current()) return;
- if (roomId && attentionGroups.has(roomId)) void refreshGroupAttention(roomId);
+ if (roomId && deps.onChatGroupAttention && rooms.has(roomId)) void refreshGroupAttention(roomId);
deps.onChanged?.({ groupId: roomId, change: 'messages' }, scope);
// A restored route may still contain the local ID until the user navigates.
for (const [sourceId, targetId] of upgradedGroups)
@@ -1132,7 +1132,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}
function publishGroupAttention(s: Snapshot): void {
- if (!current() || !isGroupRoom(s.room)) return;
+ if (!current() || (!deps.onChatGroupAttention && !deps.onChatMessageNotification) || !isGroupRoom(s.room)) return;
if (!notificationBaselines.has(s.room.id)) notificationBaselines.set(s.room.id,
s.messages.reduce((max, message) => BigInt(message.seq) > max ? BigInt(message.seq) : max, 0n));
if (!deps.onChatGroupAttention) return;
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index 65d6251589..9eeb132f75 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -818,7 +818,7 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;
### 收到消息后的注意、定位与回应
-- 桌面运行时由 Chat Server 实时事件触发提醒:灵动岛开启且可用时由岛面承接群消息,关闭、无原生岛或原生发布失败时回退系统通知,
+- 桌面运行时由 Chat Server 实时事件触发提醒:灵动岛开启且原生窗口已就绪时由岛面承接群消息,关闭、启动/重启未就绪或原生发布失败时回退系统通知,
同一条消息不同时发两份横幅;手机由 Chat Server 直接发 APNs/FCM,不依赖电脑在线。
桌面完全退出后没有常驻接收进程,不承诺继续弹窗。伙伴私聊的任务回复继续复用原有任务通知链。
- **灵动岛群消息**:一个群一张两行卡,第一行群名及可选「@你」,第二行发送者与摘要;话题回复标明话题,头像复用侧栏前五位成员的聚拢顺序。
@@ -826,8 +826,10 @@ Desktop 群聊与话题之间的分隔线支持左右拖拽和方向键调宽;
同一群 30 秒内不反复展开、不延长已展示卡的停留时间;普通提醒后新到的 @ 可以提前提醒,群消息不播放任务完成音。
自动提示收起后,未读卡仍保留在展开列表。点击沿用群/消息/话题深链,不清空读位、不提供任务归档或已读滑动动作。
服务端读位推进后,已读的 @ 消退;若还有其他符合提醒规则的未读消息,原卡显示它,否则移除。
- 静音、隐藏、归档、离群和撤权同步收起。启动/重连用本次连接的第一份群快照序号作静默基线,只恢复未读,不重弹旧消息。
- 群专线的成功回复由群消息提醒承接,不再同时留下任务完成提醒;运行、审批和报错仍按原任务状态展示。
+ 静音、隐藏、归档、离群和撤权同步收起;已订阅群取消静音或关注变化时重新计算未读,不要求先打开群列表。
+ 启动/重连用本次连接的第一份群快照序号作静默基线,只恢复未读,不重弹旧消息。
+ 群专线的成功回复由群消息提醒承接,不再同时留下任务完成提醒;接受的群输入标记先于身份/头像读取判定,极快回复也不重复提示。
+ 运行、审批和报错仍按原任务状态展示。
实现与回归:`chatMessageNotifications.ts`、`chatServer.ts` 及对应测试,`agent-island/{state,service}.ts`、`deviceSessions.test.ts`。
- 主时间线未读来自服务器精确序号,只计别人发来的可见消息;列表同时显示 @。最新快照窗口最多 100 条,
计数为该窗口中的未读数。系统事件、已删除、导入与自己的消息不提醒。话题只提醒点名或主动关注的回复。