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。

feat(agent-island): 灵动岛与桌面通知包含远程设备任务,范围跟随任务范围 (#5471)

Dash458648a07b95
diff --git a/apps/desktop/src/main/__tests__/notificationService.test.ts b/apps/desktop/src/main/__tests__/notificationService.test.ts
index 0b4da24a71..bd6b9a967b 100644
--- a/apps/desktop/src/main/__tests__/notificationService.test.ts
+++ b/apps/desktop/src/main/__tests__/notificationService.test.ts
@@ -294,6 +294,25 @@ describe('notificationService — channels 分发', () => {
expect(feishuIm.sendText).toHaveBeenCalledTimes(1);
});
+ it('skips the local badge mark for remote device tasks while keeping other channels', async () => {
+ const { initNotificationService } = await freshService();
+ initNotificationService(baseDeps(makeFeishuIm('ou_owner')));
+ markSessionNeedsAttention.mockClear();
+
+ await invokeHandler({
+ sessionId: 'remote-1',
+ title: 'Fix login',
+ kind: 'needs-reply',
+ markAttention: false,
+ channels: { desktop: false, feishu: false, mobile: true },
+ });
+
+ expect(markSessionNeedsAttention).not.toHaveBeenCalled();
+ expect(sendMobileSessionNotify).toHaveBeenCalled();
+ await expect(invokeHandler({ sessionId: 'remote-1', title: 'x', kind: 'done', markAttention: 'no' }))
+ .rejects.toThrow('invalid session event payload');
+ });
+
it('does not treat a pre-drain running snapshot as a reason to lose the completion fallback', async () => {
const { initNotificationService } = await freshService();
initNotificationService(baseDeps(makeFeishuIm('owner')));
diff --git a/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts b/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts
new file mode 100644
index 0000000000..589ead7c27
--- /dev/null
+++ b/apps/desktop/src/main/agent-island/__tests__/deviceSessions.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ parseAgentIslandRemoteSessions,
+ type AgentIslandRemoteSessionInput,
+} from '../../../shared/agentIsland.js';
+import {
+ acknowledgeAgentIslandSessionRead,
+ AGENT_ISLAND_UNREAD_TRANSIENT_TTL_MS,
+ buildAgentIslandDisplayState,
+ buildAllSessionActivitySnapshots,
+ createAgentIslandState,
+ isAgentIslandDeviceSession,
+ markAgentIslandSessionAttention,
+ pruneAgentIslandSessions,
+ setAgentIslandAppFocused,
+ setAgentIslandVisibleSession,
+ syncAgentIslandDeviceSessions,
+} from '../state.js';
+
+function remote(
+ phase: AgentIslandRemoteSessionInput['phase'],
+ overrides: Partial<AgentIslandRemoteSessionInput> = {},
+): AgentIslandRemoteSessionInput {
+ return {
+ sessionId: 'remote-1',
+ deviceId: 'device-a',
+ deviceName: 'Studio Mac',
+ title: 'Fix login',
+ workingDir: '/Users/me/code/cindy',
+ workspaceKind: 'project',
+ agentKind: 'codex',
+ phase,
+ detail: '',
+ ...overrides,
+ };
+}
+
+describe('Agent Island device sessions', () => {
+ it('shows a first-seen remote task without revealing it or emitting an event', () => {
+ const state = createAgentIslandState();
+ const result = syncAgentIslandDeviceSessions(state, [remote('completed')], 1_000);
+
+ expect(result.baselineSessionIds).toEqual(['remote-1']);
+ expect(result.events).toEqual([]);
+ const display = buildAgentIslandDisplayState(state, 1_000);
+ expect(display.mode).toBe('compact');
+ expect(display.sessions).toEqual([
+ expect.objectContaining({
+ sessionId: 'remote-1',
+ title: 'Fix login',
+ projectName: 'cindy · Studio Mac',
+ agentKind: 'codex',
+ phase: 'completed',
+ attention: true,
+ }),
+ ]);
+ });
+
+ it('lists a first-seen waiting remote task without expanding its card', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(
+ state,
+ [remote('needs-interaction', { interactionKind: 'ask_user_question' })],
+ 1_000,
+ );
+
+ const display = buildAgentIslandDisplayState(state, 1_000);
+ expect(display.mode).toBe('compact');
+ expect(display.sessions).toEqual([
+ expect.objectContaining({ sessionId: 'remote-1', phase: 'needs-interaction', attention: true }),
+ ]);
+ });
+
+ it('reveals and reports observed transitions', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('running', { detail: 'Reading files' })], 1_000);
+
+ const waiting = syncAgentIslandDeviceSessions(
+ state,
+ [remote('needs-interaction', { interactionKind: 'permission' })],
+ 2_000,
+ );
+ expect(waiting.events).toEqual([
+ { sessionId: 'remote-1', title: 'Fix login', deviceName: 'Studio Mac', kind: 'needs-reply' },
+ ]);
+ const waitingDisplay = buildAgentIslandDisplayState(state, 2_000);
+ expect(waitingDisplay.mode).toBe('expanded');
+ expect(waitingDisplay.displayPolicy).toBe('blocking');
+ // 远程审批不在本机执行,不给允许 / 拒绝按钮。
+ expect(waitingDisplay.sessions[0]?.permissionAction).toBeNull();
+
+ syncAgentIslandDeviceSessions(state, [remote('running')], 3_000);
+ const done = syncAgentIslandDeviceSessions(state, [remote('completed')], 4_000);
+ expect(done.events.map((event) => event.kind)).toEqual(['done']);
+ expect(buildAgentIslandDisplayState(state, 4_000)).toEqual(
+ expect.objectContaining({ mode: 'expanded', displayPolicy: 'transient' }),
+ );
+
+ syncAgentIslandDeviceSessions(state, [remote('running')], 5_000);
+ const failed = syncAgentIslandDeviceSessions(
+ state,
+ [remote('error', { detail: 'Quota exceeded' })],
+ 6_000,
+ );
+ expect(failed.events.map((event) => event.kind)).toEqual(['error']);
+ expect(buildAgentIslandDisplayState(state, 6_000).sessions[0]).toEqual(
+ expect.objectContaining({ phase: 'error', detail: 'Quota exceeded', attention: true }),
+ );
+ });
+
+ it('does not repeat events for an unchanged phase', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('running')], 1_000);
+ syncAgentIslandDeviceSessions(state, [remote('completed')], 2_000);
+
+ const repeated = syncAgentIslandDeviceSessions(state, [remote('completed')], 3_000);
+ expect(repeated.events).toEqual([]);
+ expect(repeated.changed).toBe(false);
+ });
+
+ it('keeps remote tasks out of this machine’s activity snapshots', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(
+ state,
+ [remote('running'), remote('completed', { sessionId: 'remote-2' })],
+ 1_000,
+ );
+
+ expect(buildAllSessionActivitySnapshots(state)).toEqual([]);
+ expect(state.remoteUnreadTerminals.size).toBe(0);
+ });
+
+ it('removes tasks that leave the synced list, including when they move devices', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(
+ state,
+ [remote('running'), remote('running', { sessionId: 'remote-2' })],
+ 1_000,
+ );
+
+ const result = syncAgentIslandDeviceSessions(
+ state,
+ [remote('running', { deviceId: 'device-b' })],
+ 2_000,
+ );
+
+ expect(result.changed).toBe(true);
+ expect(state.sessions.has('remote-2')).toBe(false);
+ // 换设备 = 新条目,不沿用旧设备的状态。
+ expect(result.baselineSessionIds).toEqual(['remote-1']);
+ expect(
+ buildAgentIslandDisplayState(state, 2_000).sessions.map((session) => session.sessionId),
+ ).toEqual(['remote-1']);
+ });
+
+ it('suppresses the reveal when the user is viewing that remote task', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('running')], 1_000);
+ setAgentIslandAppFocused(state, true, 1_000);
+ setAgentIslandVisibleSession(state, 'remote-1', 1_000);
+
+ syncAgentIslandDeviceSessions(state, [remote('completed')], 2_000);
+
+ const display = buildAgentIslandDisplayState(state, 2_000);
+ expect(display.mode).toBe('compact');
+ expect(display.sessions[0]?.attention).toBe(false);
+ });
+
+ it('keeps a read remote task hidden instead of re-adding it as unread', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('running')], 1_000);
+ syncAgentIslandDeviceSessions(state, [remote('completed')], 2_000);
+
+ expect(acknowledgeAgentIslandSessionRead(state, 'remote-1', 20_000)).toBe('cleared');
+ expect(isAgentIslandDeviceSession(state, 'remote-1')).toBe(true);
+
+ const result = syncAgentIslandDeviceSessions(state, [remote('completed')], 21_000);
+ expect(result.baselineSessionIds).toEqual([]);
+ expect(buildAgentIslandDisplayState(state, 21_000).sessions).toEqual([]);
+ });
+
+ it('does not prune expired remote tasks or mirror local app-badge attention onto them', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('completed')], 1_000);
+ const later = 1_000 + AGENT_ISLAND_UNREAD_TRANSIENT_TTL_MS + 1;
+
+ pruneAgentIslandSessions(state, later);
+ expect(state.sessions.has('remote-1')).toBe(true);
+ expect(buildAgentIslandDisplayState(state, later).sessions).toEqual([]);
+
+ syncAgentIslandDeviceSessions(state, [remote('running')], later);
+ expect(markAgentIslandSessionAttention(state, 'remote-1')).toBe(false);
+ });
+
+ it('never overrides a local task with the same id', () => {
+ const state = createAgentIslandState();
+ syncAgentIslandDeviceSessions(state, [remote('running')], 1_000);
+ const local = state.sessions.get('remote-1');
+ if (!local) throw new Error('missing session');
+ local.sourceDeviceId = null;
+
+ const result = syncAgentIslandDeviceSessions(state, [remote('completed')], 2_000);
+ expect(result.events).toEqual([]);
+ expect(state.sessions.get('remote-1')?.phase).toBe('running');
+ });
+});
+
+describe('parseAgentIslandRemoteSessions', () => {
+ it('drops invalid entries and duplicate ids', () => {
+ expect(
+ parseAgentIslandRemoteSessions([
+ remote('running'),
+ remote('completed'),
+ { ...remote('running', { sessionId: 'remote-2' }), phase: 'paused' },
+ { ...remote('running', { sessionId: 'remote-3' }), deviceId: '' },
+ { ...remote('needs-interaction', { sessionId: 'remote-4' }), interactionKind: 'unknown' },
+ null,
+ ]),
+ ).toEqual([remote('running'), { ...remote('needs-interaction', { sessionId: 'remote-4' }) }]);
+ });
+
+ it('rejects non-array and oversized payloads', () => {
+ expect(parseAgentIslandRemoteSessions({})).toBeNull();
+ expect(
+ parseAgentIslandRemoteSessions(Array.from({ length: 501 }, () => remote('running'))),
+ ).toBeNull();
+ });
+});
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 f1bb21e868..ca3cfbfbd3 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -13,6 +13,7 @@ import {
AGENT_ISLAND_PREVIEW_SOUND_CHANNEL,
AGENT_ISLAND_SET_DISPLAY_TARGET_CHANNEL,
AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,
+ AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,
AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,
AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,
DEFAULT_AGENT_ISLAND_SOUND_SETTINGS,
@@ -6113,3 +6114,107 @@ describe('会话关闭原因决定条目去留', () => {
}
});
});
+
+describe('Agent Island device sessions', () => {
+ function deviceSession(
+ phase: 'running' | 'needs-interaction' | 'completed' | 'error',
+ sessionId = 'remote-1',
+ ) {
+ return {
+ sessionId,
+ deviceId: 'device-a',
+ deviceName: 'Studio Mac',
+ title: 'Fix login',
+ workingDir: '/Users/me/code/cindy',
+ workspaceKind: 'project',
+ agentKind: 'codex',
+ phase,
+ detail: '',
+ };
+ }
+
+ it('stays silent for first-seen remote tasks and sounds on observed completion', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn(() => true);
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const onDeviceSessionEvent = vi.fn();
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ onDeviceSessionEvent,
+ });
+ syncEnabledForTest(service, publish);
+
+ service.setDeviceSessions([deviceSession('running'), deviceSession('completed', 'remote-2')]);
+ expect(publish).toHaveBeenCalled();
+ expect(playSound).not.toHaveBeenCalled();
+
+ service.setDeviceSessions([deviceSession('completed'), deviceSession('completed', 'remote-2')]);
+ expect(playSound).toHaveBeenCalledWith(DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds.complete);
+ // 岛面开启时由岛展示,不再另发桌面通知。
+ expect(onDeviceSessionEvent).not.toHaveBeenCalled();
+ // 不进入本机活动快照,也就不会被 relay 回推给控制端。
+ expect(service.getSessionActivitySnapshots()).toEqual([]);
+ expect(mocks.tapWindowBroadcast).not.toHaveBeenCalledWith(
+ SESSION_ACTIVITY_CHANNEL,
+ expect.objectContaining({ sessionId: 'remote-1' }),
+ );
+ });
+
+ it('keeps first-seen remote tasks silent when they arrive before the island setting syncs', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn(() => true);
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+
+ service.setDeviceSessions([deviceSession('running'), deviceSession('completed', 'remote-2')]);
+ service.setEnabled(true);
+ expect(playSound).not.toHaveBeenCalled();
+
+ service.setDeviceSessions([deviceSession('completed'), deviceSession('completed', 'remote-2')]);
+ expect(playSound).toHaveBeenCalledWith(DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds.complete);
+ });
+
+ it('registers the remote-session channel on platforms without the native island', async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform');
+ Object.defineProperty(process, 'platform', { value: 'linux' });
+ try {
+ const { initAgentIslandService } = await import('../service.js');
+ initAgentIslandService({ getMainWindow: () => null });
+ } finally {
+ if (platform) Object.defineProperty(process, 'platform', platform);
+ }
+
+ const channels = mocks.ipcHandle.mock.calls.map(([channel]) => channel);
+ expect(channels).toContain(AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL);
+ // 原生岛面专属的 IPC 仍只在支持的平台注册。
+ expect(channels).not.toContain(AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL);
+ });
+
+ it('hands observed transitions to desktop notifications when the island is off', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn(() => true);
+ const onDeviceSessionEvent = vi.fn();
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish },
+ onDeviceSessionEvent,
+ });
+ service.setEnabled(false);
+
+ service.setDeviceSessions([deviceSession('running')]);
+ expect(onDeviceSessionEvent).not.toHaveBeenCalled();
+
+ service.setDeviceSessions([deviceSession('completed')]);
+ expect(onDeviceSessionEvent).toHaveBeenCalledTimes(1);
+ expect(onDeviceSessionEvent).toHaveBeenCalledWith({
+ sessionId: 'remote-1',
+ title: 'Fix login',
+ deviceName: 'Studio Mac',
+ kind: 'done',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 7ba015912e..d51af9630f 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -32,6 +32,7 @@ import {
AGENT_ISLAND_SET_DISPLAY_TARGET_CHANNEL,
AGENT_ISLAND_SET_ENABLED_CHANNEL,
AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,
+ AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,
AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,
AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,
AGENT_ISLAND_SELECT_SOUND_FILE_CHANNEL,
@@ -52,11 +53,13 @@ import {
normalizeAgentIslandDisplayTarget,
normalizeAgentIslandSoundChoice,
normalizeAgentIslandSoundSettings,
+ parseAgentIslandRemoteSessions,
snapAgentIslandCompactHardwareContentWidth,
AGENT_ISLAND_SESSION_SNAPSHOTS_CHANNEL,
type AgentIslandDisplayOption,
type AgentIslandDisplayState,
type AgentIslandPillSnapshot,
+ type AgentIslandRemoteSessionInput,
type AgentIslandSessionActivity,
type AgentIslandSessionSnapshot,
type AgentIslandDisplayTarget,
@@ -86,6 +89,7 @@ import {
dismissAgentIslandActiveReveal,
getNextAgentIslandTimerAt,
hasAgentIslandSessionAttention,
+ isAgentIslandDeviceSession,
isAgentIslandPendingFocusAck,
markAgentIslandSessionAttention,
requestAgentIslandManualCollapse,
@@ -102,6 +106,8 @@ import {
setAgentIslandStrings,
setAgentIslandToolWording,
setAgentIslandVisibleSession,
+ syncAgentIslandDeviceSessions,
+ type AgentIslandDeviceSessionEvent,
type AgentIslandUserPromptRollbackToken,
} from './state.js';
import { createLocalizedToolRowWording } from './toolWording.js';
@@ -124,6 +130,7 @@ import {
writeAgentIslandLayoutPreferences,
} from './layoutPreferenceStore.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';
import {
beginProtectedFolderCheck,
@@ -174,6 +181,8 @@ export interface AgentIslandServiceDeps {
isPlannedRemoteDaemonClose?: (sessionId: string) => boolean;
/** Optional process-local consumer for task activity, such as hardware status lighting. */
onSessionActivityChange?: (activity: readonly AgentIslandSessionActivity[]) => void;
+ /** 其它设备任务的状态跃迁。灵动岛开启时由岛面展示;关闭时才交给这里发桌面通知。 */
+ onDeviceSessionEvent?: (event: AgentIslandDeviceSessionEvent) => void;
}
interface AgentIslandNativeRenderer {
@@ -215,6 +224,8 @@ export function initAgentIslandService(deps: AgentIslandServiceDeps): AgentIslan
...deps,
nativeHost: deps.nativeHost ?? (supportsNativeIsland ? undefined : HEADLESS_AGENT_ISLAND_NATIVE_HOST),
});
+ // 远程任务同步与原生岛面无关:无原生岛的平台也要靠它发桌面通知。
+ serviceSingleton.registerDeviceSessionIpc();
if (supportsNativeIsland) {
serviceSingleton.registerIpc();
} else {
@@ -315,6 +326,8 @@ export class AgentIslandService {
private readonly silencedRunHadAttention = new Map<string, boolean>();
private readonly silencedRunClearTimers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly mutedCompletionSoundSessionIds = new Set<string>();
+ /** 本轮同步首次出现的其它设备任务:进列表但不响铃。publish 后清空。 */
+ private readonly baselineSoundSessionIds = new Set<string>();
private readonly stoppedSessionIds = new Set<string>();
private readonly replacementTurnPendingSessionIds = new Set<string>();
private readonly replacementTurnDispatchingSessionIds = new Set<string>();
@@ -480,6 +493,24 @@ export class AgentIslandService {
this.handleInteractionDismissed(entry.sessionId, requestId);
}
+ /** 各平台都注册(含无原生岛的 headless):灵动岛关闭时远程任务靠它发桌面通知。 */
+ registerDeviceSessionIpc(): void {
+ ipcMain.handle(AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL, (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ // 只认主窗:副窗也挂侧栏,多份输入会让跃迁判定来回抖动。
+ const mainWindow = this.deps.getMainWindow();
+ if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents !== event.sender) {
+ return { ok: true };
+ }
+ const inputs = parseAgentIslandRemoteSessions(raw);
+ if (!inputs) {
+ throwIpcError('INVALID_PARAMS', 'remote sessions payload is invalid');
+ }
+ this.setDeviceSessions(inputs);
+ return { ok: true };
+ });
+ }
+
registerIpc(): void {
ipcMain.handle(AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL, (event, sessionId: unknown) => {
const sourceWindow = BrowserWindow.fromWebContents(event.sender);
@@ -627,6 +658,28 @@ export class AgentIslandService {
this.publish();
}
+ /**
+ * 覆盖岛上的其它设备任务(renderer 已按侧栏「任务范围」裁剪)。这些条目不进入
+ * 本机活动快照,也就不会被 relay 当作本机任务再推给控制端。
+ */
+ setDeviceSessions(inputs: readonly AgentIslandRemoteSessionInput[]): void {
+ setAgentIslandStrings(this.state, buildAgentIslandStrings());
+ const result = syncAgentIslandDeviceSessions(this.state, inputs, Date.now());
+ for (const sessionId of result.baselineSessionIds) this.baselineSoundSessionIds.add(sessionId);
+ if (result.changed) this.publish();
+ if (this.isEnabled()) return;
+ for (const event of result.events) {
+ try {
+ this.deps.onDeviceSessionEvent?.(event);
+ } catch (error) {
+ log.warn('device session event consumer failed', {
+ sessionId: event.sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+
resetRuntimeState(): void {
this.clearPublishTimer();
this.clearStreamingPreviewPublishTimer();
@@ -645,6 +698,7 @@ export class AgentIslandService {
this.silencedSessionRunIds.clear();
this.silencedRunHadAttention.clear();
this.mutedCompletionSoundSessionIds.clear();
+ this.baselineSoundSessionIds.clear();
this.stoppedSessionIds.clear();
this.replacementTurnPendingSessionIds.clear();
this.replacementTurnDispatchingSessionIds.clear();
@@ -1173,6 +1227,13 @@ export class AgentIslandService {
* pending-alerts 派生收敛)显式带 'explicit' 才能清掉未处理的报错。
*/
handleSessionAttentionCleared(sessionId: string, source: 'explicit' | 'passive' = 'passive'): void {
+ if (isAgentIslandDeviceSession(this.state, sessionId)) {
+ // 其它设备的任务:只收本机岛面的未读,本机 relay 账本与它无关。
+ if (acknowledgeAgentIslandSessionRead(this.state, sessionId, Date.now(), { source }) === 'cleared') {
+ this.publish();
+ }
+ return;
+ }
const ack = acknowledgeAgentIslandSessionRead(this.state, sessionId, Date.now(), { source });
// 未读 error 对 passive 免疫:state / 独立账本都未动,也**不能**给远端发收尾包。
if (ack === 'error-immune') return;
@@ -1356,9 +1417,12 @@ export class AgentIslandService {
now: number,
): void {
if (!next.visible || next.smartSuppressed) return;
+ const baseline = this.baselineSoundSessionIds;
const event = getAgentIslandSoundEventForTransition(
previous,
- next,
+ baseline.size > 0
+ ? { ...next, sessions: next.sessions.filter((session) => !baseline.has(session.sessionId)) }
+ : next,
this.mutedCompletionSoundSessionIds,
new Set(this.silencedSessionRunIds.keys()),
);
@@ -1576,12 +1640,14 @@ export class AgentIslandService {
const now = Date.now();
if (!this.enabledSynced) {
this.mutedCompletionSoundSessionIds.clear();
+ // 开关尚未同步时没有上一帧可比:首次出现的设备任务保留静音,等第一次真正 publish。
this.clearStreamingPreviewPublishTimer();
this.clearPublishTimer();
return;
}
if (!this.enabled) {
this.mutedCompletionSoundSessionIds.clear();
+ this.baselineSoundSessionIds.clear();
this.clearStreamingPreviewPublishTimer();
this.lastSoundDisplayState = withAgentIslandConfig(
buildAgentIslandDisplayState(this.state, now),
@@ -1616,6 +1682,7 @@ export class AgentIslandService {
this.scheduleNextPublish(now);
this.playSoundForDisplayTransition(this.lastSoundDisplayState, displayState, now);
this.mutedCompletionSoundSessionIds.clear();
+ this.baselineSoundSessionIds.clear();
this.lastSoundDisplayState = displayState;
if (this.nativeHost.failed) {
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 3738a9c140..2d7f966fdd 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -1,5 +1,11 @@
import { isSubagentParentToolUseId } from '@cindy/maker-shared/message-render';
-import { isCompactingWorkingStatus, publicToolPhase, publicToolResultPhase, type WorkingPhase } from '@cindy/maker-shared';
+import {
+ isCompactingWorkingStatus,
+ publicToolPhase,
+ publicToolResultPhase,
+ readWorkingPhase,
+ type WorkingPhase,
+} from '@cindy/maker-shared';
import {
parseReconnectAttemptMessage,
type AgentEvent,
@@ -8,6 +14,7 @@ import {
import { DEFAULT_TOOL_ROW_WORDING, type ToolRowWording } from '@cindy/maker-shared/message-presentation';
import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation';
+import { dbToMakerAgentKind } from '../../shared/agentKindConversion';
import { LIVE_TASK_PRIORITY, liveTaskPriorityRank } from '../../shared/liveTaskPriority';
import { stripTrailingPathSeparators } from '../../shared/pathText';
@@ -32,6 +39,7 @@ import {
type AgentIslandLayoutMode,
type AgentIslandNotchStatus,
type AgentIslandPillSnapshot,
+ type AgentIslandRemoteSessionInput,
type AgentIslandStrings,
type AgentIslandSessionPhase,
type AgentIslandSessionSnapshot,
@@ -164,6 +172,11 @@ interface AgentIslandSessionState {
*/
sortActivityAt: number;
lastActivityAt: number;
+ /**
+ * 非 null = 镜像另一台设备(device-link「我控制它」)上运行的任务,生命周期由
+ * {@link syncAgentIslandDeviceSessions} 的输入决定;本机 Maker 事件不会触达它。
+ */
+ sourceDeviceId: string | null;
}
export interface AgentIslandUserPromptRollbackToken {
@@ -978,7 +991,8 @@ export function acknowledgeAgentIslandSessionRead(
if (session.phase === 'completed') session.completedUntil = null;
if (session.phase === 'error') session.errorUntil = null;
- if (!isSessionVisible(session, now)) {
+ // 其它设备的任务只随同步输入增删;这里删掉的话,下一次同步会把它当作新条目重新挂回未读。
+ if (session.sourceDeviceId === null && !isSessionVisible(session, now)) {
state.sessions.delete(sessionId);
return 'cleared';
}
@@ -1023,7 +1037,7 @@ export function markAgentIslandSessionAttention(
sessionId: string,
): boolean {
const session = state.sessions.get(sessionId);
- if (!session || session.unread) return false;
+ if (!session || session.unread || session.sourceDeviceId !== null) return false;
session.unread = true;
syncRemoteUnreadTerminal(state, session);
return true;
@@ -1056,6 +1070,187 @@ export function removeAgentIslandSession(state: AgentIslandState, sessionId: str
forgetAgentIslandSession(state, sessionId);
}
+export type AgentIslandDeviceSessionEventKind = 'done' | 'error' | 'needs-reply';
+
+export interface AgentIslandDeviceSessionEvent {
+ sessionId: string;
+ title: string | null;
+ deviceName: string | null;
+ kind: AgentIslandDeviceSessionEventKind;
+}
+
+export interface AgentIslandDeviceSessionSyncResult {
+ changed: boolean;
+ /** 本次首次出现的条目(连接时补发 / 范围刚扩大):只进列表,不弹出、不响铃。 */
+ baselineSessionIds: string[];
+ /** 本次观察到的真实状态跃迁,供关闭灵动岛时的桌面通知使用。 */
+ events: AgentIslandDeviceSessionEvent[];
+}
+
+const DEVICE_SESSION_INTERACTION_ID = 'device-session-interaction';
+
+export function isAgentIslandDeviceSession(state: AgentIslandState, sessionId: string): boolean {
+ return (state.sessions.get(sessionId)?.sourceDeviceId ?? null) !== null;
+}
+
+/**
+ * 用其它设备任务的完整镜像覆盖岛上的设备条目(输入已按侧栏「任务范围」裁剪)。
+ *
+ * 只有观察到的跃迁(running / needs-interaction → completed / error,或进入
+ * needs-interaction)才弹出并产出通知事件;首次出现的条目按当前状态静默挂上,
+ * 避免连接设备或切换范围时把对方已有的未读一次性弹出来。
+ */
+export function syncAgentIslandDeviceSessions(
+ state: AgentIslandState,
+ inputs: readonly AgentIslandRemoteSessionInput[],
+ now: number,
+): AgentIslandDeviceSessionSyncResult {
+ const result: AgentIslandDeviceSessionSyncResult = { changed: false, baselineSessionIds: [], events: [] };
+ const incoming = new Map(inputs.map((input) => [input.sessionId, input]));
+ for (const [sessionId, session] of [...state.sessions]) {
+ if (session.sourceDeviceId === null) continue;
+ if (incoming.get(sessionId)?.deviceId === session.sourceDeviceId) continue;
+ forgetAgentIslandSession(state, sessionId);
+ result.changed = true;
+ }
+ for (const input of inputs) {
+ const existing = state.sessions.get(input.sessionId);
+ // 同一 id 已是本机任务时以本机事件流为准。
+ if (existing && existing.sourceDeviceId === null) continue;
+ const previous = existing ? existing.phase : null;
+ const session = existing ?? getOrCreateSession(state, { sessionId: input.sessionId }, now);
+ if (!existing) {
+ session.sourceDeviceId = input.deviceId;
+ result.baselineSessionIds.push(input.sessionId);
+ result.changed = true;
+ }
+ if (applyDeviceSessionMeta(session, input)) result.changed = true;
+ const transition = applyDeviceSessionPhase(state, session, input, previous, now);
+ if (transition.changed) result.changed = true;
+ if (transition.event) {
+ result.events.push({
+ sessionId: input.sessionId,
+ title: input.title,
+ deviceName: input.deviceName,
+ kind: transition.event,
+ });
+ }
+ }
+ return result;
+}
+
+function applyDeviceSessionMeta(
+ session: AgentIslandSessionState,
+ input: AgentIslandRemoteSessionInput,
+): boolean {
+ const project = projectNameFromWorkingDir(input.workingDir, input.workspaceKind);
+ const projectName = [project, input.deviceName].filter(Boolean).join(' · ') || null;
+ const agentKind = dbToMakerAgentKind(input.agentKind);
+ const changed = session.title !== input.title
+ || session.projectName !== projectName
+ || session.agentKind !== agentKind;
+ session.title = input.title;
+ session.projectName = projectName;
+ session.agentKind = agentKind;
+ return changed;
+}
+
+function applyDeviceSessionPhase(
+ state: AgentIslandState,
+ session: AgentIslandSessionState,
+ input: AgentIslandRemoteSessionInput,
+ previous: AgentIslandSessionPhase | null,
+ now: number,
+): { changed: boolean; event: AgentIslandDeviceSessionEventKind | null } {
+ const observed = previous === 'running' || previous === 'needs-interaction';
+ switch (input.phase) {
+ case 'running': {
+ const workingPhase = readWorkingPhase(input.workingPhase) ?? 'thinking';
+ const entering = previous !== 'running' || !session.running;
+ if (entering) {
+ clearDeviceSessionInteraction(session);
+ markSessionRunning(state, session, now);
+ session.phase = 'running';
+ session.sortActivityAt = now;
+ }
+ const changed = entering || session.detail !== input.detail || session.workingPhase !== workingPhase;
+ session.workingPhase = workingPhase;
+ session.detail = input.detail;
+ session.detailSource = input.detail ? 'status' : null;
+ if (changed) session.lastActivityAt = now;
+ return { changed, event: null };
+ }
+ case 'needs-interaction': {
+ const entering = previous !== 'needs-interaction';
+ if (entering) {
+ clearDeviceSessionInteraction(session);
+ markSessionRunning(state, session, now);
+ session.pendingInteractionIds.add(DEVICE_SESSION_INTERACTION_ID);
+ session.phase = 'needs-interaction';
+ session.lastActivityAt = now;
+ if (previous !== null) {
+ deferActiveTransientReveal(state, 'queued');
+ requestAttentionReveal(state, session, now, AGENT_ISLAND_REVEAL_DWELL_MS);
+ } else {
+ // 首次出现时已在等待:按「已收起」挂进列表,不自动展开交互卡。
+ session.interactionRevealDismissed = true;
+ }
+ }
+ const changed = entering
+ || session.interactionKind !== input.interactionKind
+ || session.detail !== input.detail;
+ session.interactionKind = input.interactionKind;
+ session.detail = input.detail;
+ session.detailSource = 'interaction';
+ if (entering) syncVisibleInteractionSuppression(state, now);
+ return { changed, event: entering && previous !== null ? 'needs-reply' : null };
+ }
+ case 'completed': {
+ if (previous === 'completed') return { changed: false, event: null };
+ clearDeviceSessionInteraction(session);
+ session.running = false;
+ session.lastActivityAt = now;
+ // 对方设备已经仲裁过终态,这里不再套本机「报错后的配对 done」保护。
+ session.completionAllowedAfterTerminalError = true;
+ completeAgentIslandSession(state, session, now, observed
+ ? { suppressAttention: false, preserveAttention: false }
+ : { suppressAttention: true, preserveAttention: true });
+ return { changed: true, event: observed ? 'done' : null };
+ }
+ case 'error': {
+ if (previous === 'error') return { changed: false, event: null };
+ clearDeviceSessionInteraction(session);
+ session.running = false;
+ session.phase = 'error';
+ session.detail = input.detail;
+ session.detailSource = input.detail ? 'status' : null;
+ session.completedUntil = null;
+ session.lastActivityAt = now;
+ if (observed) {
+ session.errorUntil = now + AGENT_ISLAND_ERROR_DWELL_MS;
+ requestAttentionReveal(state, session, now, AGENT_ISLAND_ERROR_REVEAL_DWELL_MS, { forceUnread: true });
+ } else {
+ session.unread = true;
+ }
+ return { changed: true, event: observed ? 'error' : null };
+ }
+ }
+}
+
+function clearDeviceSessionInteraction(session: AgentIslandSessionState): void {
+ // 与本机交互撤销同口径:等待交互的注意力随交互结束一起放下。
+ if (session.pendingInteractionIds.size > 0) session.unread = false;
+ session.pendingInteractionIds.clear();
+ clearPendingInteractionMetadata(session);
+ session.interactionKind = undefined;
+ session.visibleInteractionSuppressedUntil = null;
+ session.interactionRevealDismissed = false;
+ if (session.detailSource === 'interaction') {
+ session.detail = '';
+ session.detailSource = null;
+ }
+}
+
/**
* 会话**进程**关闭:落下运行态,但保留仍需展示的通知条目。
*
@@ -1211,6 +1406,9 @@ export function pruneAgentIslandSessions(state: AgentIslandState, now: number):
updateFocusVerificationLifecycle(state, now);
const preserveExpiredTransient = isPointerInsideIsland(state) || state.hoverExpanded || isCollapsePending(state, now);
for (const [sessionId, session] of state.sessions.entries()) {
+ // 其它设备的任务不按岛面 TTL 删除:展示面已按 isSessionVisible 隐藏,删掉反而会在
+ // 下一次同步时被当作新条目重新出现。
+ if (session.sourceDeviceId !== null) continue;
if (isSessionVisible(session, now, preserveExpiredTransient)) continue;
// 过了岛面 TTL 的未读终态先写入独立账本,再删岛 state。远程绿/红点订账本,
// 不再跟完整 AgentIslandSessionState(含活动文本)绑在一起。
@@ -1299,7 +1497,10 @@ export function buildAgentIslandDisplayState(
export function buildAllSessionActivitySnapshots(
state: AgentIslandState,
): AgentIslandSessionSnapshot[] {
- const snapshots = Array.from(state.sessions.values()).map((session) => toSnapshot(session));
+ // 其它设备的任务不进入本机活动快照:否则会被 relay 当作本机任务再推给控制端。
+ const snapshots = Array.from(state.sessions.values())
+ .filter((session) => session.sourceDeviceId === null)
+ .map((session) => toSnapshot(session));
const seen = new Set(snapshots.map((snapshot) => snapshot.sessionId));
for (const unread of state.remoteUnreadTerminals.values()) {
if (seen.has(unread.sessionId)) continue;
@@ -2267,6 +2468,7 @@ function getOrCreateSession(
startedAt: now,
sortActivityAt: now,
lastActivityAt: now,
+ sourceDeviceId: null,
};
state.sessions.set(meta.sessionId, session);
return session;
@@ -2396,6 +2598,8 @@ function isUnreadTerminalLedger(
}
function syncRemoteUnreadTerminal(state: AgentIslandState, session: AgentIslandSessionState): void {
+ // 账本只服务本机任务的对外 relay;其它设备的任务由它自己的设备负责未读。
+ if (session.sourceDeviceId !== null) return;
if (isUnreadTerminalLedger(session)) {
state.remoteUnreadTerminals.set(session.sessionId, {
sessionId: session.sessionId,
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index d26abb7cac..9ce3f158d0 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -558,7 +558,7 @@ import {
clearAllSessionAttention,
refreshWindowsAppBadge,
} from './appBadgeService';
-import { initNotificationService } from './notificationService';
+import { initNotificationService, showDeviceSessionDesktopEvent } from './notificationService';
import { initWecomGroupNotificationIpc } from './wecomGroupNotification';
import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';
import { attachWorkLouderCodexWindowReveal } from './worklouder-codex/index.js';
@@ -4498,6 +4498,11 @@ const registerIpcHandlers = () => {
onSessionActivityChange: (activity) => {
updateInputDeviceSessionActivity(activity);
},
+ onDeviceSessionEvent: (event) => {
+ // 与本机任务同口径:Cindy 在前台时不弹系统通知。
+ if (hasFocusedAppWindow()) return;
+ showDeviceSessionDesktopEvent(() => getWindow() ?? null, event);
+ },
})?.setAppFocused(hasFocusedAppWindow());
// 定向 replay:快照只补发给刚完成 sessions 订阅的那一台控制端。若沿默认广播
// 通道扇出,每次 subscribe 都会把 O(会话数) 的帧重复灌给其它所有控制端,
diff --git a/apps/desktop/src/main/notificationService.ts b/apps/desktop/src/main/notificationService.ts
index 9d888db692..f8509ddd33 100644
--- a/apps/desktop/src/main/notificationService.ts
+++ b/apps/desktop/src/main/notificationService.ts
@@ -86,6 +86,8 @@ interface ShowSessionEventPayload {
* 发送侧的防打扰(远程正在看该会话 / 短窗去重)在 device-link 模块内收口。
*/
channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ /** 其它设备的任务传 false:未读归属那台设备,不记本机 Dock 角标。 */
+ markAttention?: boolean;
}
/**
@@ -163,14 +165,36 @@ function focusWindow(getWindow: () => BrowserWindow | null, sessionId: string):
*/
export function showDesktopSessionEvent(
getWindow: () => BrowserWindow | null,
- payload: Pick<ShowSessionEventPayload, 'sessionId' | 'title' | 'kind'> & { body?: string; teammate?: boolean },
+ payload: Pick<ShowSessionEventPayload, 'sessionId' | 'title' | 'kind'> & {
+ body?: string;
+ teammate?: boolean;
+ /** 其它设备的任务传 false:未读归属那台设备,本机 Dock 角标不跟着记。 */
+ markAttention?: boolean;
+ },
): boolean {
const { sessionId, title, kind } = payload;
- if (sessionId) markSessionNeedsAttention(sessionId);
+ if (sessionId && payload.markAttention !== false) markSessionNeedsAttention(sessionId);
const safeTitle = title?.trim() || sessionId.slice(0, 8) || getSessionNotificationUntitled();
return showDesktopToast(safeTitle, kind, () => focusWindow(getWindow, sessionId), payload.body, payload.teammate);
}
+/**
+ * 其它设备(device-link)任务的桌面通知,只在本机灵动岛关闭时由岛服务转交过来。
+ * 正文没有本机记录可读,沿用各 kind 的通用文案;未读归属那台设备,不记本机角标。
+ */
+export function showDeviceSessionDesktopEvent(
+ getWindow: () => BrowserWindow | null,
+ event: { sessionId: string; title: string | null; deviceName: string | null; kind: SessionEventKind },
+): void {
+ if (!desktopNotificationsEnabled) return;
+ showDesktopSessionEvent(getWindow, {
+ sessionId: event.sessionId,
+ title: [event.title ?? getSessionNotificationUntitled(), event.deviceName].filter(Boolean).join(' · '),
+ kind: event.kind,
+ markAttention: false,
+ });
+}
+
export interface NotificationServiceDeps {
getWindow: () => BrowserWindow | null;
/**
@@ -200,6 +224,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
// 去重与「被远程观看则不推」收口。
assertValidSessionEventPayload(payload);
const { sessionId, title, kind, channels } = payload;
+ const markAttention = payload.markAttention !== false;
const generation = getMobileNotifyGeneration();
// Capture at IPC arrival, not after the asynchronous preview: a newer
// turn can begin while the current completion waits on persistence.
@@ -211,11 +236,11 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
const safeTitle = title.trim() || sessionId.slice(0, 8);
const wantDesktop = channels?.desktop ?? true;
const wantFeishu = channels?.feishu === true;
- markSessionNeedsAttention(sessionId);
+ if (markAttention) markSessionNeedsAttention(sessionId);
// Action/error desktop notices have no transcript preview and must be immediate.
if (wantDesktop && kind !== 'done') {
- showDesktopSessionEvent(getWindow, { sessionId, title: safeTitle, kind });
+ showDesktopSessionEvent(getWindow, { sessionId, title: safeTitle, kind, markAttention });
}
// Content is read from main's transcript. Bound only enrichment, not delivery;
// a timeout is not a dedupe window and never causes a second late toast.
@@ -298,7 +323,7 @@ export function initNotificationService(deps: NotificationServiceDeps): void {
if (wantDesktop && kind === 'done' && !wasReplyNotified(desktopKey, eventId)) {
try {
const accepted = showDesktopSessionEvent(getWindow, {
- sessionId, title: notificationTitle, kind, teammate,
+ sessionId, title: notificationTitle, kind, teammate, markAttention,
body: teammate ? notificationPreview(detail ?? '') || fallbackBody : undefined,
});
if (accepted) {
@@ -368,7 +393,8 @@ function assertValidSessionEventPayload(
p.title.length > SESSION_TITLE_MAX_LENGTH ||
typeof p.kind !== 'string' ||
!SESSION_EVENT_KINDS.has(p.kind) ||
- (p.channels !== undefined && (typeof p.channels !== 'object' || p.channels === null))
+ (p.channels !== undefined && (typeof p.channels !== 'object' || p.channels === null)) ||
+ (p.markAttention !== undefined && typeof p.markAttention !== 'boolean')
) {
throw new TypeError('invalid session event payload');
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 200f18d23c..0cc2c75475 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -57,11 +57,13 @@ import {
AGENT_ISLAND_SET_DISPLAY_TARGET_CHANNEL,
AGENT_ISLAND_SET_ENABLED_CHANNEL,
AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,
+ AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,
AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,
AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,
type AgentIslandDisplayOption,
type AgentIslandDisplayTarget,
type AgentIslandMascotSkin,
+ type AgentIslandRemoteSessionInput,
type AgentIslandSessionActivity,
type AgentIslandSoundChoice,
type AgentIslandSoundSettings,
@@ -2008,6 +2010,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke(AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL, sessionId),
setEnabled: (enabled: boolean): Promise<{ ok: true }> =>
ipcRenderer.invoke(AGENT_ISLAND_SET_ENABLED_CHANNEL, enabled),
+ /** 按侧栏「任务范围」筛过的远程设备任务活动(灵动岛 / 桌面通知用)。 */
+ setRemoteSessions: (sessions: AgentIslandRemoteSessionInput[]): Promise<{ ok: true }> =>
+ ipcRenderer.invoke(AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL, sessions),
setSoundSettings: (settings: AgentIslandSoundSettings): Promise<{ ok: true }> =>
ipcRenderer.invoke(AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL, settings),
setMascotSkin: (skin: AgentIslandMascotSkin): Promise<{ ok: true }> =>
@@ -3665,6 +3670,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
title: string;
kind: 'done' | 'error' | 'needs-reply';
channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ markAttention?: boolean;
}): Promise<void> => ipcRenderer.invoke('notification:show-session-event', payload),
notificationSetDesktopEnabled: (enabled: boolean): Promise<{ ok: true }> =>
ipcRenderer.invoke('notification:set-desktop-enabled', enabled),
diff --git a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
index a7bfc4df7a..9e5ac1a20b 100644
--- a/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionEventNotification.test.ts
@@ -75,6 +75,21 @@ describe('shared session event notifications', () => {
);
});
+ it('leaves the desktop toast of a remote device task to the main-process scope filter', () => {
+ gates.feishu = true;
+
+ sendSessionEventNotification('remote-1', 'Fix login', 'done', { remoteDevice: true });
+
+ // 未读归属那台设备:本机 Dock 角标两条标记路径都不记。
+ expect(markAttention).not.toHaveBeenCalled();
+ expect(showSessionEvent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ markAttention: false,
+ channels: { desktop: false, feishu: true, mobile: true },
+ }),
+ );
+ });
+
it('does not send external notifications while the user is already looking at Cindy', () => {
vi.mocked(document.hasFocus).mockReturnValue(true);
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 8745ddbba7..816a331f1d 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -33,6 +33,7 @@ import { SessionShareImportWizard } from '@/components/settings/SessionShareImpo
import { ControlledBanner } from '@/features/remote-device/ControlledBanner';
import { CredentialStoreBanner } from '@/components/layout/CredentialStoreBanner';
import { useDeviceLinkRemoteProjects } from '@/features/device-link/useDeviceLinkRemoteProjects';
+import { useAgentIslandRemoteSessionsSync } from '@/features/device-link/agentIslandRemoteSessions';
import { pluginScheduleNavigationState } from '@/features/scheduler/lib/pluginScheduleCreateIntent';
import { ScheduleSessionIndexOwner } from '@/features/scheduler/components/ScheduleSessionIndexOwner';
import { AppBadgeAttentionSync } from '@/components/layout/AppBadgeAttentionSync';
@@ -486,6 +487,8 @@ export function MainLayout() {
usePluginRemovalNoticeToast();
// device-link 跨设备远程控制:同账号在线 + 开了被控的设备,其项目自动并入侧边栏
useDeviceLinkRemoteProjects();
+ // 范围内的远程任务进本机灵动岛 / 桌面通知(main 只认主窗的这份输入)。
+ useAgentIslandRemoteSessionsSync();
// 系统通知点击回调:主进程把窗口拉到前台后广播 sessionId,这里跳路由。
// 挂在 MainLayout 而不是 App 顶层——这里在 ProtectedRoute + LocalDbGate 之内,
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 2d656377dc..0be0d2d026 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -1096,7 +1096,9 @@ function ExpandedView({
if (session && isOrcaWorkerSession(session)) return;
if (session) {
const title = projectDraftSessionTitle(session.title, unnamedLabelRef.current);
- sendSessionEventNotification(sessionId, title, kind);
+ sendSessionEventNotification(sessionId, title, kind, {
+ remoteDevice: !!session.deviceLinkDeviceId,
+ });
return;
}
void botOwnedSessionNotificationTitle(sessionId).then((botTitle) => {
diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts
new file mode 100644
index 0000000000..fbe90d39b9
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Session } from '@/lib/ccAgent.types';
+import { buildAgentIslandRemoteSessionInputs } from '../agentIslandRemoteSessions';
+import type { RemoteSessionActivity } from '../remoteSessionActivityStore';
+import { MACHINE_ALL, MACHINE_LOCAL } from '../selectedMachineStore';
+
+function remoteSession(id: string, deviceId: string, overrides: Partial<Session> = {}): Session {
+ return {
+ id,
+ title: `Task ${id}`,
+ workingDir: '/Users/me/code/cindy',
+ workspaceKind: 'project',
+ agentKind: 'cc',
+ deviceLinkDeviceId: deviceId,
+ deviceLinkDeviceName: `Mac ${deviceId}`,
+ deviceLinkConnectionStatus: 'connected',
+ ...overrides,
+ } as Session;
+}
+
+const activities = new Map<string, RemoteSessionActivity>([
+ [
+ 'a-1',
+ {
+ sessionId: 'a-1',
+ phase: 'running',
+ compactDetail: 'Reading files',
+ workingPhase: 'reading-file',
+ attention: false,
+ },
+ ],
+ [
+ 'b-1',
+ {
+ sessionId: 'b-1',
+ phase: 'needs-interaction',
+ compactDetail: '',
+ interactionKind: 'permission',
+ attention: true,
+ },
+ ],
+ ['b-2', { sessionId: 'b-2', phase: 'completed', compactDetail: '', attention: true }],
+]);
+const readActivity = (sessionId: string): RemoteSessionActivity | undefined =>
+ activities.get(sessionId);
+
+describe('buildAgentIslandRemoteSessionInputs', () => {
+ const sessions = [
+ remoteSession('a-1', 'device-a'),
+ remoteSession('a-idle', 'device-a'),
+ remoteSession('b-1', 'device-b'),
+ remoteSession('b-2', 'device-b', { title: ' ' }),
+ ];
+
+ it('includes every remote task with live activity under the "all" scope', () => {
+ expect(buildAgentIslandRemoteSessionInputs(sessions, MACHINE_ALL, readActivity)).toEqual([
+ {
+ sessionId: 'a-1',
+ deviceId: 'device-a',
+ deviceName: 'Mac device-a',
+ title: 'Task a-1',
+ workingDir: '/Users/me/code/cindy',
+ workspaceKind: 'project',
+ agentKind: 'cc',
+ phase: 'running',
+ detail: 'Reading files',
+ workingPhase: 'reading-file',
+ },
+ expect.objectContaining({
+ sessionId: 'b-1',
+ phase: 'needs-interaction',
+ interactionKind: 'permission',
+ }),
+ expect.objectContaining({ sessionId: 'b-2', phase: 'completed', title: null }),
+ ]);
+ });
+
+ it('follows the sidebar task scope', () => {
+ expect(
+ buildAgentIslandRemoteSessionInputs(sessions, ['device-b'], readActivity).map(
+ (input) => input.sessionId,
+ ),
+ ).toEqual(['b-1', 'b-2']);
+ expect(buildAgentIslandRemoteSessionInputs(sessions, [MACHINE_LOCAL], readActivity)).toEqual(
+ [],
+ );
+ });
+
+ it('skips Bot tasks and disconnected devices', () => {
+ expect(
+ buildAgentIslandRemoteSessionInputs(
+ [
+ remoteSession('a-1', 'device-a', { source: 'bot' }),
+ remoteSession('b-1', 'device-b', { deviceLinkConnectionStatus: 'disconnected' }),
+ ],
+ MACHINE_ALL,
+ readActivity,
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts
new file mode 100644
index 0000000000..93ffdca488
--- /dev/null
+++ b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts
@@ -0,0 +1,77 @@
+/**
+ * 把其它设备(device-link「我控制它」)任务的实时活动同步给 main,供本机灵动岛与
+ * 桌面通知使用。
+ * ---------------------------------------------------------------------------
+ * 范围跟侧栏「任务范围」走:只同步当前范围内、侧栏会展示的远程任务;断线设备的快照
+ * 可能停在旧状态,不同步。状态跃迁的判定(何时弹出 / 响铃 / 发通知)在 main 的岛状态机。
+ */
+
+import { useEffect, useRef } from 'react';
+import type { AgentIslandRemoteSessionInput } from '../../../shared/agentIsland';
+import type { Session } from '@/lib/ccAgent.types';
+import { useRemoteProjectSessions } from './remoteProjectsStore';
+import {
+ getRemoteSessionActivity,
+ useRemoteSessionActivityRevision,
+ type RemoteSessionActivity,
+} from './remoteSessionActivityStore';
+import { selectVisibleSessions, type MachineSelection } from './selectedMachineStore';
+import { useEffectiveSelectedMachineId } from './useMachineSwitcher';
+
+export function buildAgentIslandRemoteSessionInputs(
+ remoteSessions: Session[],
+ selection: MachineSelection,
+ readActivity: (sessionId: string, deviceId: string) => RemoteSessionActivity | undefined,
+): AgentIslandRemoteSessionInput[] {
+ const inputs: AgentIslandRemoteSessionInput[] = [];
+ for (const session of selectVisibleSessions([], remoteSessions, selection)) {
+ const deviceId = session.deviceLinkDeviceId;
+ if (!deviceId || session.deviceLinkConnectionStatus === 'disconnected') continue;
+ const activity = readActivity(session.id, deviceId);
+ if (!activity) continue;
+ inputs.push({
+ sessionId: session.id,
+ deviceId,
+ deviceName: session.deviceLinkDeviceName ?? null,
+ title: session.title?.trim() || null,
+ workingDir: session.workingDir,
+ workspaceKind: session.workspaceKind,
+ agentKind: session.agentKind,
+ phase: activity.phase,
+ detail: activity.compactDetail,
+ ...(activity.workingPhase ? { workingPhase: activity.workingPhase } : {}),
+ ...(activity.interactionKind
+ ? {
+ interactionKind:
+ activity.interactionKind as AgentIslandRemoteSessionInput['interactionKind'],
+ }
+ : {}),
+ });
+ }
+ return inputs;
+}
+
+/** 主窗常驻挂载一次(MainLayout)。内容未变时不发 IPC。 */
+export function useAgentIslandRemoteSessionsSync(): void {
+ const remoteSessions = useRemoteProjectSessions();
+ const selection = useEffectiveSelectedMachineId();
+ const activityRevision = useRemoteSessionActivityRevision();
+ const lastSignatureRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ const setRemoteSessions = window.electronAPI?.agentIsland?.setRemoteSessions;
+ if (!setRemoteSessions) return;
+ const inputs = buildAgentIslandRemoteSessionInputs(
+ remoteSessions,
+ selection,
+ getRemoteSessionActivity,
+ );
+ const signature = JSON.stringify(inputs);
+ if (signature === lastSignatureRef.current) return;
+ lastSignatureRef.current = signature;
+ void setRemoteSessions(inputs).catch(() => {
+ // 下一次变化时重发完整列表。
+ lastSignatureRef.current = null;
+ });
+ }, [remoteSessions, selection, activityRevision]);
+}
diff --git a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
index 2dd2529b31..e2c8a11f75 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
@@ -12,7 +12,8 @@
* 会重发 attention=false 的收尾包)
* - 其余(已读收尾包)→ 删除条目,行回落时间显示
*
- * 不喂系统级 attention(dock 角标 / 通知)—— 通知职责归被控端本机,控制端只做行内可视。
+ * 不喂 dock 角标——未读归被控端。灵动岛与桌面通知由 agentIslandRemoteSessions 按侧栏
+ * 「任务范围」裁剪后另行同步给 main。
*
* ⚠️ 性能不变量(与 sessionAttentionStore 同款):SessionItem 逐行挂载,订阅必须是
* 按 deviceId + sessionId 的稳定引用精准订阅(条目对象未替换时快照引用不变),禁止整表订阅。
diff --git a/apps/desktop/src/renderer/lib/sessionEventNotification.ts b/apps/desktop/src/renderer/lib/sessionEventNotification.ts
index 521524ad8e..ef7e0bac89 100644
--- a/apps/desktop/src/renderer/lib/sessionEventNotification.ts
+++ b/apps/desktop/src/renderer/lib/sessionEventNotification.ts
@@ -71,19 +71,28 @@ export function sendSessionEventNotification(
sessionId: string,
title: string,
kind: SessionEventNotificationKind,
+ options: {
+ /**
+ * 其它设备的任务:桌面通知 / 灵动岛由 main 按「任务范围」统一发
+ * (agentIslandRemoteSessions),这里不再弹;未读归属那台设备,不记本机 Dock 角标。
+ */
+ remoteDevice?: boolean;
+ } = {},
): void {
// The user is already looking at Cindy. In-app attention remains available,
// but an OS/external notification would be duplicate noise.
if (typeof document !== 'undefined' && document.hasFocus()) return;
const islandActive = isAgentIslandSupported() && getAgentIslandEnabled();
- void window.electronAPI.notificationMarkSessionAttention(sessionId);
+ const remoteDevice = options.remoteDevice === true;
+ if (!remoteDevice) void window.electronAPI.notificationMarkSessionAttention(sessionId);
void window.electronAPI.notificationShowSessionEvent({
sessionId,
title,
kind,
+ ...(remoteDevice ? { markAttention: false } : {}),
channels: {
- desktop: getNotificationsEnabled() && !islandActive,
+ desktop: !remoteDevice && getNotificationsEnabled() && !islandActive,
feishu: getFeishuNotificationsEnabled(),
// Mobile owns registration/unregistration of its push token. There is
// deliberately no second desktop setting for the same channel.
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index bc2fd8fc01..2dfd79dc43 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1125,6 +1125,7 @@ type AgentIslandMascotSkin = import('../shared/agentIsland').AgentIslandMascotSk
type AgentIslandSoundChoice = import('../shared/agentIsland').AgentIslandSoundChoice;
type AgentIslandSoundSettings = import('../shared/agentIsland').AgentIslandSoundSettings;
type AgentIslandSessionActivity = import('../shared/agentIsland').AgentIslandSessionActivity;
+type AgentIslandRemoteSessionInput = import('../shared/agentIsland').AgentIslandRemoteSessionInput;
/** 会话内 /goal 状态扁平 payload(main goal-host → renderer)。 */
interface GoalStatusPayload {
@@ -2109,6 +2110,7 @@ interface ElectronAPI {
agentIsland: {
setVisibleSession: (sessionId: string | string[] | null) => Promise<{ ok: true }>;
setEnabled: (enabled: boolean) => Promise<{ ok: true }>;
+ setRemoteSessions: (sessions: AgentIslandRemoteSessionInput[]) => Promise<{ ok: true }>;
setSoundSettings: (settings: AgentIslandSoundSettings) => Promise<{ ok: true }>;
setMascotSkin: (skin: AgentIslandMascotSkin) => Promise<{ ok: true }>;
setDisplayTarget: (target: AgentIslandDisplayTarget) => Promise<{ ok: true }>;
@@ -2840,6 +2842,8 @@ interface ElectronAPI {
* 发送侧防打扰在 main 的 device-link 模块收口,renderer 恒传 true。
*/
channels?: { desktop?: boolean; feishu?: boolean; mobile?: boolean };
+ /** 其它设备的任务传 false:未读归属那台设备,不记本机 Dock 角标。 */
+ markAttention?: boolean;
}) => Promise<void>;
/** Sync the renderer-owned global desktop-notification preference to main. */
notificationSetDesktopEnabled?: (enabled: boolean) => Promise<{ ok: true }>;
diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.ts
index f7cbb4bdc0..544fcb39e7 100644
--- a/apps/desktop/src/shared/agentIsland.ts
+++ b/apps/desktop/src/shared/agentIsland.ts
@@ -745,3 +745,82 @@ export const AGENT_ISLAND_SET_DISPLAY_TARGET_CHANNEL = 'agent-island:set-display
export const AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL = 'agent-island:get-display-options';
export const AGENT_ISLAND_PREVIEW_SOUND_CHANNEL = 'agent-island:preview-sound';
export const AGENT_ISLAND_SELECT_SOUND_FILE_CHANNEL = 'agent-island:select-sound-file';
+/** renderer(主窗)→ main:按侧栏「任务范围」筛过的远程设备任务活动。 */
+export const AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL = 'agent-island:set-remote-sessions';
+
+/**
+ * 远程设备(device-link「我控制它」)任务的活动镜像,供本机灵动岛与桌面通知使用。
+ * 只含 running / needs-interaction / 未读终态;范围由 renderer 按侧栏「任务范围」裁剪。
+ */
+export interface AgentIslandRemoteSessionInput {
+ sessionId: string;
+ deviceId: string;
+ deviceName: string | null;
+ title: string | null;
+ workingDir: string | null;
+ workspaceKind: string | null;
+ /** DB 形态('cc' | 'codex' | 'pi')。 */
+ agentKind: string | null;
+ phase: AgentIslandSessionPhase;
+ detail: string;
+ workingPhase?: string;
+ interactionKind?: AgentIslandInteractionKind;
+}
+
+const AGENT_ISLAND_REMOTE_SESSIONS_MAX = 500;
+const AGENT_ISLAND_REMOTE_ID_MAX_LENGTH = 256;
+const AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH = 1024;
+const AGENT_ISLAND_SESSION_PHASES: readonly AgentIslandSessionPhase[] = [
+ 'running',
+ 'needs-interaction',
+ 'completed',
+ 'error',
+];
+const AGENT_ISLAND_INTERACTION_KINDS: readonly AgentIslandInteractionKind[] = [
+ 'permission',
+ 'ask_user_question',
+ 'plan_review',
+ 'plugin_setup',
+];
+
+/** renderer payload 的运行时校验:整体形状非法返回 null,单条非法条目丢弃。 */
+export function parseAgentIslandRemoteSessions(raw: unknown): AgentIslandRemoteSessionInput[] | null {
+ if (!Array.isArray(raw) || raw.length > AGENT_ISLAND_REMOTE_SESSIONS_MAX) return null;
+ const out: AgentIslandRemoteSessionInput[] = [];
+ const seen = new Set<string>();
+ for (const item of raw) {
+ if (typeof item !== 'object' || item === null) continue;
+ const record = item as Record<string, unknown>;
+ const sessionId = readBoundedString(record.sessionId, AGENT_ISLAND_REMOTE_ID_MAX_LENGTH);
+ const deviceId = readBoundedString(record.deviceId, AGENT_ISLAND_REMOTE_ID_MAX_LENGTH);
+ const phase = record.phase;
+ if (!sessionId || !deviceId || seen.has(sessionId)) continue;
+ if (!(AGENT_ISLAND_SESSION_PHASES as readonly unknown[]).includes(phase)) continue;
+ seen.add(sessionId);
+ const interactionKind = (AGENT_ISLAND_INTERACTION_KINDS as readonly unknown[]).includes(record.interactionKind)
+ ? record.interactionKind as AgentIslandInteractionKind
+ : undefined;
+ const workingPhase = readBoundedString(record.workingPhase, 64);
+ out.push({
+ sessionId,
+ deviceId,
+ deviceName: readBoundedString(record.deviceName, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH),
+ title: readBoundedString(record.title, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH),
+ workingDir: readBoundedString(record.workingDir, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH * 4),
+ workspaceKind: readBoundedString(record.workspaceKind, 64),
+ agentKind: readBoundedString(record.agentKind, 64),
+ phase: phase as AgentIslandSessionPhase,
+ detail: readBoundedString(record.detail, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH) ?? '',
+ ...(workingPhase ? { workingPhase } : {}),
+ ...(interactionKind ? { interactionKind } : {}),
+ });
+ }
+ return out;
+}
+
+function readBoundedString(value: unknown, maxLength: number): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ if (!trimmed) return null;
+ return trimmed.length > maxLength ? trimmed.slice(0, maxLength) : trimmed;
+}
diff --git a/docs/product-rules/sidebar-redesign-plan.md b/docs/product-rules/sidebar-redesign-plan.md
index 7287fadac3..cfc4c7ab89 100644
--- a/docs/product-rules/sidebar-redesign-plan.md
+++ b/docs/product-rules/sidebar-redesign-plan.md
@@ -49,6 +49,12 @@
与筛选不同,置顶区豁免筛选但不豁免范围(否则被排除设备的置顶任务会赖着不走)。
范围选择器位于置顶区下方而作用及于上方的空间错位,由标题文字的状态表达兜底
(用户裁决:接受,不搬置顶区)。
+- **本机灵动岛与桌面通知包含远程设备的任务,范围跟随这里**(2026-10-05 用户定稿):
+ 范围内、侧栏会展示的远程任务进入灵动岛;灵动岛关闭时改发桌面通知。范围只裁剪
+ 远程任务,本机任务的通知不受范围影响。首次出现的远程任务(连接时补发 / 范围刚
+ 扩大)只静默进列表;只有观察到的「运行中 → 完成 / 出错」或「进入等待交互」才弹出、
+ 响铃、发通知。远程审批不在本机执行,岛上不给允许 / 拒绝按钮,点开任务处理。
+ 未读仍归被控设备,不计入本机 Dock 角标。
「按日期分组」模式删除(`DateGroupedSessionsSection` 及 `groupBy === 'date'` 分支)。