Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(menubar): 恢复伙伴未读并显示远控设备与设置入口
Dash54519fc41170
diff --git a/apps/desktop/native/menubar/macos-menubar-helper.swift b/apps/desktop/native/menubar/macos-menubar-helper.swiftindex a9d9eac0ce..f133322f49 100644--- a/apps/desktop/native/menubar/macos-menubar-helper.swift+++ b/apps/desktop/native/menubar/macos-menubar-helper.swift@@ -137,6 +137,9 @@ struct MBView: Decodable, Equatable {let moneySymbol: Stringlet strings: [String: String]let statusTextByMode: [String: String?]+ let attentionCount: Int?+ let remotelyControlled: Bool?+ let remoteControllerNames: [String]?let updatedAtMs: Double?let headlinePrimary: Stringlet headlineSecondary: String?@@ -151,6 +154,14 @@ struct MBView: Decodable, Equatable {let settings: MBSettings/// "sign-in" until the user signs in or skips sign-in; nothing was read.let gate: String?++ /// The real item and its settings preview always use the same text.+ var statusTitle: String {+ guard gate == nil else { return "" }+ let usage = (statusTextByMode[settings.statusText] ?? nil) ?? ""+ guard let count = attentionCount, count > 0 else { return usage }+ return usage.isEmpty ? String(count) : "\(count) · \(usage)"+ }}struct MBIncoming: Decodable {@@ -238,6 +249,10 @@ enum Palette {/// Red of the Cindy logo's ">" mark (the logo red, not a state color).static let brand = Color(nsColor: hex(0xF70121))static let warn = Color(nsColor: hex(0xEA6B17))+ /// Shared by the menu-bar dot and its explanation inside the panel.+ private static let remoteControlValue: UInt32 = 0xFF9F0A+ static let remoteControlHex = String(format: "#%06X", remoteControlValue)+ static let remoteControl = Color(nsColor: hex(remoteControlValue))static let error = Color(nsColor: hex(0xD91F37))static let focus = Color(nsColor: hex(0x417CDD))static let claude = Color(nsColor: hex(0xD97757))@@ -389,14 +404,17 @@ enum Logos {/// Opaque silhouette with tonal, tapered strands and a larger, left-shifted earring./// Fit the mark to the 18pt status canvas; other brand surfaces keep their original mark.- static func statusIcon(dark: Bool) -> NSImage? {- dark ? darkStatusIcon : lightStatusIcon+ static func statusIcon(dark: Bool, controlled: Bool = false) -> NSImage? {+ if controlled { return dark ? darkControlledStatusIcon : lightControlledStatusIcon }+ return dark ? darkStatusIcon : lightStatusIcon}private static let lightStatusIcon = makeStatusIcon(dark: false)private static let darkStatusIcon = makeStatusIcon(dark: true)+ private static let lightControlledStatusIcon = makeStatusIcon(dark: false, controlled: true)+ private static let darkControlledStatusIcon = makeStatusIcon(dark: true, controlled: true)- private static func makeStatusIcon(dark: Bool) -> NSImage? {+ private static func makeStatusIcon(dark: Bool, controlled: Bool = false) -> NSImage? {let silhouette = dark ? "#ffffff" : "#000000"let strand = dark ? "#686868" : "#bdbdbd"let earring = "M 10.22879,11.96118 L 13.40721,13.91787 L 13.40721,14.65125 L 10.22879,16.60782 L 10.22879,15.50708 L 12.30648,14.28390 L 10.22879,13.06192 L 10.22879,11.96118 Z"@@ -459,12 +477,20 @@ enum Logos {L 17.346,7.646 L 17.475,7.644 L 17.604,7.649 L 17.735,7.660 L 17.866,7.678 L 18.000,7.700 Z"/>"""+ // Brighter orange for this small menu-bar indicator. The clear rim lets+ // wallpaper show through and keeps the 5pt dot distinct from the silhouette.let svg = """<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">+ <defs><mask id="control-dot-cutout"><rect width="18" height="18" fill="white"/>+ \(controlled ? "<circle cx=\"4.5\" cy=\"4.5\" r=\"3.25\" fill=\"black\"/>" : "")+ </mask></defs>+ <g mask="url(#control-dot-cutout)"><g transform="translate(-0.765 -0.445) scale(0.8157)"><path fill="\(silhouette)" fill-rule="evenodd" d="\(cindySilhouettePath) \(earring)"/>\(hairStrands)</g>+ </g>+ \(controlled ? "<circle cx=\"4.5\" cy=\"4.5\" r=\"2.5\" fill=\"\(Palette.remoteControlHex)\"/>" : "")</svg>"""guard let data = svg.data(using: .utf8), let image = NSImage(data: data) else { return nil }@@ -722,10 +748,9 @@ final class StatusController: NSObject, NSWindowDelegate {super.init()if let button = statusItem.button {// Wallpaper can give the menu bar a different appearance from the app.- statusAppearanceObservation = button.observe(\.effectiveAppearance, options: [.initial, .new]) { button, _ in+ statusAppearanceObservation = button.observe(\.effectiveAppearance, options: [.initial, .new]) { [weak self] _, _ inMainActor.assumeIsolated {- let dark = button.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua- button.image = Logos.statusIcon(dark: dark)+ self?.updateStatusIcon()}}button.imagePosition = .imageLeading@@ -788,17 +813,17 @@ final class StatusController: NSObject, NSWindowDelegate {private func updateStatusTitle() {guard let button = statusItem.button else { return }- let mode = store.view?.settings.statusText ?? "icon"- let text = (store.view?.statusTextByMode[mode] ?? nil) ?? ""+ updateStatusIcon()+ let text = store.view?.statusTitle ?? ""if text.isEmpty {button.attributedTitle = NSAttributedString(string: "")button.imagePosition = .imageOnly} else {button.imagePosition = .imageLeadingbutton.attributedTitle = NSAttributedString(- string: " " + text,+ string: "\u{2009}" + text,attributes: [- .font: NSFont.monospacedDigitSystemFont(ofSize: 12.5, weight: .semibold),+ .font: NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .regular),.baselineOffset: 0,])@@ -809,6 +834,13 @@ final class StatusController: NSObject, NSWindowDelegate {}}+ private func updateStatusIcon() {+ guard let button = statusItem.button else { return }+ let dark = button.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua+ let controlled = store.view?.remotelyControlled == true+ button.image = Logos.statusIcon(dark: dark, controlled: controlled)+ }+@objc func toggle() {if let at = closedByStatusPressAt {closedByStatusPressAt = nil@@ -1684,6 +1716,60 @@ struct HatchPattern: Shape {// MARK: - Main page+/// A quiet status strip, tied to the same state and color as the menu-bar dot.+struct RemoteControlStatus: View {+ let title: String+ let detail: String+ let names: [String]+ let actionLabel: String+ let action: () -> Void+ @State private var hovering = false++ private var description: String { names.isEmpty ? detail : names.joined(separator: " · ") }++ var body: some View {+ Button(action: action) {+ HStack(alignment: .center, spacing: 10) {+ Image(systemName: "desktopcomputer")+ .font(.system(size: 16, weight: .regular))+ .foregroundStyle(Palette.ink2)+ .frame(width: 32, height: 32)+ .background(Circle().fill(Palette.ink5))+ .overlay(alignment: .topTrailing) {+ Circle().fill(Palette.remoteControl)+ .frame(width: 6, height: 6)+ .offset(x: -1, y: 1)+ }+ .accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 3) {+ Text(title)+ .font(.system(size: 13, weight: .medium))+ .foregroundStyle(Palette.ink)+ Text(description)+ .font(.system(size: 11))+ .foregroundStyle(Palette.ink2)+ .lineSpacing(2)+ .lineLimit(2)+ }+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ Image(systemName: "chevron.right")+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(hovering ? Palette.ink2 : Palette.ink3)+ .accessibilityHidden(true)+ }+ .padding(10)+ .background(RoundedRectangle(cornerRadius: 14, style: .circular).fill(hovering ? Palette.ink5 : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(PressScaleStyle())+ .onHover { value in withAnimation(Motion.quick) { hovering = value } }+ .help(description + "\n" + actionLabel)+ .accessibilityLabel(title + ", " + description)+ .accessibilityHint(actionLabel)+ }+}+struct MainPage: View {@ObservedObject var store: MenubarStorelet view: MBView@@ -1719,19 +1805,29 @@ struct MainPage: View {}private var topBar: some View {- HStack(spacing: 0) {- Wordmark().frame(height: 13)- TimelineView(.periodic(from: .now, by: 15)) { context in- Text(updatedText(now: context.date))- .font(.system(size: 11))- .foregroundStyle(Palette.ink3)- .lineLimit(1)- .padding(.leading, 8)+ VStack(spacing: 0) {+ HStack(spacing: 0) {+ Wordmark().frame(height: 13)+ TimelineView(.periodic(from: .now, by: 15)) { context in+ Text(updatedText(now: context.date))+ .font(.system(size: 11))+ .foregroundStyle(Palette.ink3)+ .lineLimit(1)+ .padding(.leading, 8)+ }+ Spacer(minLength: 0)+ RefreshButton(store: store)+ }+ .padding(EdgeInsets(top: 14, leading: 18, bottom: 4, trailing: 12))+ if view.remotelyControlled == true {+ RemoteControlStatus(+ title: store.s("remoteControlTitle"), detail: store.s("remoteControlBody"),+ names: view.remoteControllerNames ?? [], actionLabel: store.s("settings")+ ) { controller.emitAndClose(["type": "open-remote-control-settings"]) }+ .padding(EdgeInsets(top: 0, leading: 8, bottom: 4, trailing: 8))+ Hairline().padding(.horizontal, 18)}- Spacer(minLength: 0)- RefreshButton(store: store)}- .padding(EdgeInsets(top: 14, leading: 18, bottom: 4, trailing: 12))}private func updatedText(now: Date) -> String {@@ -1805,6 +1901,15 @@ struct GatePage: View {Wordmark().frame(height: 13).padding(EdgeInsets(top: 18, leading: 18, bottom: 0, trailing: 18))+ if store.view?.remotelyControlled == true {+ RemoteControlStatus(+ title: store.s("remoteControlTitle"), detail: store.s("remoteControlBody"),+ names: store.view?.remoteControllerNames ?? [], actionLabel: store.s("settings")+ ) { controller.emitAndClose(["type": "open-remote-control-settings"]) }+ .padding(EdgeInsets(top: 8, leading: 8, bottom: 4, trailing: 8))+ Hairline().padding(.horizontal, 18)+ }+Image(systemName: "person.crop.circle").font(.system(size: 26, weight: .regular)).foregroundStyle(Palette.ink3)@@ -3535,7 +3640,7 @@ struct StatusPreview: View {@Environment(\.colorScheme) private var colorSchemevar body: some View {- let text = (view.statusTextByMode[view.settings.statusText] ?? nil) ?? ""+ let text = view.statusTitlelet dark = colorScheme == .darkZStack(alignment: .topLeading) {wallpaper(dark: dark)@@ -3543,11 +3648,11 @@ struct StatusPreview: View {Spacer()Image(systemName: "wifi").font(.system(size: 12, weight: .semibold)).opacity(0.5).padding(.horizontal, 6)HStack(spacing: 5) {- if let icon = Logos.statusIcon(dark: dark) {- Image(nsImage: icon).renderingMode(.original).resizable().frame(width: 16, height: 16)+ if let icon = Logos.statusIcon(dark: dark, controlled: view.remotelyControlled == true) {+ Image(nsImage: icon).renderingMode(.original).resizable().frame(width: 18, height: 18)}if !text.isEmpty {- Text(text).font(.system(size: 12, weight: .semibold)).monospacedDigit().lineLimit(1).fixedSize()+ Text(text).font(.system(size: 13, weight: .regular)).monospacedDigit().lineLimit(1).fixedSize()}}.padding(.horizontal, 7)diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.tsindex 515a4f32a9..1da7e334b7 100644--- a/apps/desktop/src/main/__tests__/deepLink.test.ts+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts@@ -39,6 +39,7 @@ import {focusMainWindow,handleIncomingDeepLink,openMainWindowVoiceSettings,+ openMainWindowRemoteControlSettings,setDeepLinkMainWindow,takePendingDeepLink,takePendingDeepLinkFromRenderer,@@ -189,7 +190,7 @@ describe('user-initiated main-window focus', () => {});describe('internal main-window navigation', () => {- it('focuses the main window and routes voice settings to the requested tab', () => {+ it.each(['providers', 'remote-control'] as const)('focuses the main window and routes settings to %s', (tab) => {const send = vi.fn();const mainWindow = {isDestroyed: () => false,@@ -207,7 +208,8 @@ describe('internal main-window navigation', () => {};setDeepLinkMainWindow(mainWindow as unknown as BrowserWindow);- openMainWindowVoiceSettings('providers');+ if (tab === 'remote-control') openMainWindowRemoteControlSettings();+ else openMainWindowVoiceSettings(tab);expect(mainWindow.show).toHaveBeenCalledOnce();expect(mainWindow.restore).toHaveBeenCalledOnce();@@ -221,7 +223,7 @@ describe('internal main-window navigation', () => {}expect(send).toHaveBeenCalledWith('deep-link:navigate', {type: 'settings',- tab: 'providers',+ tab,});setDeepLinkMainWindow(null);});diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex 94cfde3325..4b178b3cba 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -17,6 +17,8 @@ import {AGENT_ISLAND_SET_DISPLAY_TARGET_CHANNEL,AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,+ AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL,+ AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL,AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,DEFAULT_AGENT_ISLAND_SOUND_SETTINGS,@@ -567,6 +569,110 @@ describe('AgentIslandService native publishing', () => {// Load after the outer mock setup, outside the first behavior test's budget.// Cold Vite transforms can otherwise consume its entire 5-second timeout.await import('../service.js');+ }, 60_000);++ // 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 () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);+ const send = vi.fn();+ const mainWindow = { webContents: { send }, isDestroyed: () => false } as unknown as BrowserWindow;+ const service = new AgentIslandService({ getMainWindow: () => mainWindow,+ nativeHost: { failed: false, publish, suspend: () => undefined } });+ syncEnabledForTest(service, publish);+ service.registerDeviceSessionIpc();+ const sync = registeredIpcHandler(AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL);+ const chat = { sessionId: 'offline-chat', botId: 'remote-bot', deviceId: 'offline-home',+ companion: { name: 'Cindy', avatar: 'cindy://avatar/preset/cindy', avatarColor: 'blue' }, visible: true, unread: true,+ lastMessageAt: 1, preview: 'Unread reply' };+ const snapshot = { dataOwnerId: 'test-owner', ownerGeneration: 1, chats: [chat] };+ sync({ sender: mainWindow.webContents }, { ...snapshot, ownerGeneration: 0 });+ expect(publish).not.toHaveBeenCalled();+ sync({ sender: {} }, snapshot);+ expect(publish).not.toHaveBeenCalled();+ sync({ sender: mainWindow.webContents }, snapshot);+ const display = publish.mock.calls.at(-1)![0];+ expect(display.pillSnapshot.attentionCount).toBe(1);+ expect(service.getSessionActivitySnapshot(chat.sessionId)).toBeNull();+ const token = display.sessions[0].completionToken!;+ await Promise.resolve();+ mocks.companionAvatarThumbnail.mockResolvedValueOnce('restored-avatar');+ sync({ sender: mainWindow.webContents }, snapshot);+ await Promise.resolve();+ expect(publish.mock.calls.at(-1)![0].sessions[0].companion?.imageJpeg).toBe('restored-avatar');+ expect(publish.mock.calls.at(-1)![0].sessions[0].completionToken).toBe(token);+ expect(await service.handleCompletionAction(chat.sessionId, 'archive', token)).toBe(false);+ expect(await service.handleCompletionAction(chat.sessionId, 'mark-read', token)).toBe(true);+ expect(send).toHaveBeenCalledWith(AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL,+ { ...chat, readThroughAt: chat.lastMessageAt }, { dataOwnerId: 'test-owner', ownerGeneration: 1 });+ expect(mocks.remoteInvoke).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(0);+ sync({ sender: mainWindow.webContents }, { ...snapshot, chats: [{ ...chat, lastMessageAt: 2 }] });+ expect(await service.handleCompletionAction(chat.sessionId, 'mark-read', token)).toBe(false);+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(1);+ service.resetRuntimeState();+ service.setEnabled(true);+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(0);+ });++ it('keeps fresh completion sounds and clears local runtime attention when the chat is explicitly read', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);+ const playSound = vi.fn(() => true);+ const mainWindow = { webContents: { send: vi.fn() }, isDestroyed: () => false } as unknown as BrowserWindow;+ const service = new AgentIslandService({ getMainWindow: () => mainWindow,+ nativeHost: { failed: false, publish, playSound, suspend: () => undefined } });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({ enabled: true, sounds: { ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ complete: customSound('complete.wav') } });+ const input = { sessionId: 'local-chat', botId: 'local-bot', deviceId: null,+ companion: { name: 'Cindy', avatar: '', avatarColor: 'blue' }, visible: true, unread: false,+ lastMessageAt: 1, preview: '' };+ service.setCompanionChats([input]);+ service.handleUserPrompt({ sessionId: input.sessionId }, 'hello');+ playSound.mockClear();+ service.handleAgentEvent({ sessionId: input.sessionId }, doneEvent());+ const runtimeToken = (service.getSessionActivitySnapshot(input.sessionId) as AgentIslandSessionActivity).completionToken!;+ service.setCompanionChats([{ ...input, unread: true, lastMessageAt: Date.now(), preview: 'Reply' }]);+ expect(playSound).toHaveBeenCalledWith(customSound('complete.wav'));+ expect(await service.handleCompletionAction(input.sessionId, 'mark-read', runtimeToken)).toBe(false);+ const token = publish.mock.calls.at(-1)![0].sessions[0].completionToken!;+ expect(await service.handleCompletionAction(input.sessionId, 'mark-read', token)).toBe(true);+ expect(service.getSessionActivitySnapshot(input.sessionId)?.attention ?? false).toBe(false);+ expect(publish.mock.calls.at(-1)![0].pillSnapshot.attentionCount).toBe(0);+ service.resetRuntimeState();+ });++ // Unit: the menu bar must observe the final chat projection even with the island hidden.+ it.each([true, false])('publishes shared attention counts with island enabled=%s', async (enabled) => {+ const { AgentIslandService } = await import('../service.js');+ const service = new AgentIslandService({ getMainWindow: () => null,+ nativeHost: { failed: false, publish: () => true, suspend: () => undefined } });+ service.setEnabled(enabled);+ const counts = vi.fn();+ const unsubscribe = service.subscribeAttentionCount(counts);+ const chat = { sessionId: 'unread-chat', botId: 'bot', deviceId: 'offline-home',+ companion: { name: 'Cindy', avatar: '', avatarColor: 'blue' }, visible: true, unread: true,+ lastMessageAt: 1, preview: 'Unread reply' };+ service.handleUserPrompt({ sessionId: 'running-task' }, 'work');+ expect(service.getAttentionCount()).toBe(0);+ service.setCompanionChats([chat]);+ expect(service.getAttentionCount()).toBe(1);+ expect(counts.mock.calls).toEqual([[1]]);+ service.setCompanionChats([chat]);+ expect(counts).toHaveBeenCalledTimes(1);+ service.setCompanionChats([{ ...chat, unread: false }]);+ expect(counts.mock.calls).toEqual([[1], [0]]);+ service.setCompanionChats([chat]);+ service.resetRuntimeState();+ expect(service.getAttentionCount()).toBe(0);+ expect(counts.mock.calls).toEqual([[1], [0], [1], [0]]);+ unsubscribe();+ service.setEnabled(enabled);+ service.setCompanionChats([chat]);+ expect(counts).toHaveBeenCalledTimes(4);+ service.resetRuntimeState();});it.each([true, false])('waits across status Done → native done for the shared local/remote completion decision (%s)', async handled => {diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.tsindex 02a2c1e962..72cf99bd7e 100644--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts@@ -33,8 +33,55 @@ import {setAgentIslandLayoutDragActive,setAgentIslandPointerZones,setAgentIslandVisibleSession,+ type AgentIslandCompanionChatProjection,} from '../state.js';+// Regression: a chat can be unread after runtime expiry/restart; existing tests only supplied+// runtime events. Exercise the public display builder with one old unread chat (unit tier).+describe('companion chat unread projection', () => {+ const chat: AgentIslandCompanionChatProjection = {+ sessionId: 'companion-chat', deviceId: null, visible: true, unread: true,+ lastMessageAt: 1, preview: 'Reply waiting to be read', token: 'chat-token',+ companion: { name: 'Cindy', hue: 'blue', glyph: 'C', glyphIsInitial: true },+ };+ it.each([null, 'offline-home'])('restores old unread without runtime activity or notifications (%s)', deviceId => {+ const state = createAgentIslandState();+ const now = AGENT_ISLAND_UNREAD_TRANSIENT_TTL_MS * 2;+ const display = buildAgentIslandDisplayState(state, now, [{ ...chat, deviceId }]);+ expect(display.pillSnapshot.attentionCount).toBe(1);+ expect(display.mode).toBe('compact');+ expect(display.sessions[0]).toMatchObject({ phase: 'completed', attention: true,+ completionToken: 'chat-token', completionNotification: 'silent', companion: { name: 'Cindy' } });+ expect(buildAllSessionActivitySnapshots(state)).toEqual([]);+ expect(buildAgentIslandDisplayState(state, now, [{ ...chat, unread: false }]).sessions).toEqual([]);+ expect(buildAgentIslandDisplayState(state, now, [{ ...chat, visible: false }]).sessions).toEqual([]);+ });++ it('deduplicates live activity, retains running and waiting, and removes a read completion immediately', () => {+ const state = createAgentIslandState();+ const meta = { sessionId: chat.sessionId };+ applyAgentIslandUserPrompt(state, meta, 'continue', 100);+ let display = buildAgentIslandDisplayState(state, 101, [chat]);+ expect(display.sessions).toHaveLength(1);+ expect(display.sessions[0].phase).toBe('running');+ expect(display.pillSnapshot).toMatchObject({ attentionCount: 1, runningSessionCount: 0 });+ display = buildAgentIslandDisplayState(state, 102, [{ ...chat, unread: false }]);+ expect(display.pillSnapshot).toMatchObject({ attentionCount: 0, runningSessionCount: 1 });+ applyAgentIslandInteractionRequest(state, meta, { kind: 'ask_user_question', requestId: 'question', questions: [] }, 103);+ display = buildAgentIslandDisplayState(state, 104, [{ ...chat, unread: false }]);+ expect(display.sessions[0]).toMatchObject({ phase: 'needs-interaction', attention: true });+ applyAgentIslandInteractionDismissed(state, chat.sessionId, 'question', 105);+ applyAgentIslandEvent(state, meta, doneEvent(), 106);+ display = buildAgentIslandDisplayState(state, 107, [chat]);+ expect(display.sessions[0].completionToken).toBe('chat-token');+ expect(buildAgentIslandDisplayState(state, 108, [{ ...chat, unread: false }]).sessions).toEqual([]);+ // Reading chat replies must not suppress an independent terminal error.+ applyAgentIslandEvent(state, meta, terminalErrorEvent('failed'), 109);+ expect(buildAgentIslandDisplayState(state, 110, [{ ...chat, unread: false }]).sessions[0])+ .toMatchObject({ phase: 'error', attention: true });+ });+});+const REMOTE_DAEMON_CLOSED_REASON = 'remote_daemon_closed';type PermissionInteractionRequest = Extract<InteractionRequest, { kind: 'permission' }>;diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 092940b447..1df2824713 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -1,5 +1,6 @@import { dialog, ipcMain, screen, BrowserWindow, type Display, type OpenDialogOptions } from 'electron';import path from 'node:path';+import { randomUUID } from 'node:crypto';import { release as getOsRelease } from 'node:os';import { SESSION_ACTIVITY_CHANNEL, type SessionActivityPayload } from '@cindy/device-link';import {@@ -37,6 +38,10 @@ import {AGENT_ISLAND_SET_ENABLED_CHANNEL,AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,+ AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL,+ AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL,+ parseAgentIslandCompanionChats,+ type AgentIslandCompanionChatInput,AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,AGENT_ISLAND_SELECT_SOUND_FILE_CHANNEL,@@ -150,6 +155,8 @@ import {writeAgentIslandLayoutPreferences,} from './layoutPreferenceStore.js';import { throwIpcError } from '../utils/ipcValidate.js';+import { getActiveAppSession } from '../appSessionState.js';+import { isDataOwnerPushStamp } from '../../shared/dataOwnerPush.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { isDeviceLinkInvoke } from '../device-link/invoke-context.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';@@ -334,11 +341,18 @@ function canonicalSessionActivity(* tracking while TypeScript owns product state and session prioritization.*/export class AgentIslandService {+ private attentionCount = 0;+ private readonly attentionCountListeners = new Set<(count: number) => void>();private readonly sessionActivityListeners = new Set<(transition: SessionActivityTransition) => void>();private sessionActivitySubscriptionCursor = new Map<string, AgentIslandSessionActivity>();private readonly state = createAgentIslandState();+ private companionChats = new Map<string, {+ input: AgentIslandCompanionChatInput;+ companion: AgentIslandCompanionSnapshot;+ token: string;+ }>();private readonly nativeHost: AgentIslandNativeRenderer;private readonly headless: boolean;private publishTimer: ReturnType<typeof setTimeout> | null = null;@@ -549,6 +563,20 @@ export class AgentIslandService {/** 各平台都注册(含无原生岛的 headless):灵动岛关闭时远程任务靠它发桌面通知。 */registerDeviceSessionIpc(): void {+ ipcMain.handle(AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL, (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (event.sender !== this.deps.getMainWindow()?.webContents) return { ok: true };+ if (!isDataOwnerPushStamp(raw)) throwIpcError('INVALID_PARAMS', 'Companion chats require an owner stamp');+ const owner = getActiveAppSession();+ if (!owner.dataOwnerId || raw.dataOwnerId !== owner.dataOwnerId || raw.ownerGeneration !== owner.generation) return { ok: true };+ const payload = raw as typeof raw & { chats?: unknown };+ const chats = parseAgentIslandCompanionChats(payload.chats);+ if (!chats) {+ throwIpcError('INVALID_PARAMS', 'Invalid companion chat snapshot');+ }+ this.setCompanionChats(chats);+ return { ok: true };+ });ipcMain.handle('agent-island:completion-action', (event, sessionId: unknown, action: unknown, token: unknown) => {if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);if (typeof sessionId !== 'string' || !sessionId || (action !== 'archive' && action !== 'mark-read')@@ -776,6 +804,38 @@ export class AgentIslandService {}}+ /** Mirror existing chat read positions, without publishing synthetic runtime activity. */+ setCompanionChats(inputs: readonly AgentIslandCompanionChatInput[]): void {+ const previous = this.companionChats;+ this.companionChats = new Map(inputs.map((input) => {+ const old = previous.get(input.sessionId);+ const entry = old && JSON.stringify(old.input) === JSON.stringify(input) ? old : {+ input, token: randomUUID(),+ companion: old && old.input.deviceId === input.deviceId+ && JSON.stringify(old.input.companion) === JSON.stringify(input.companion)+ ? old.companion : companionSnapshotWithoutArtwork(input.companion),+ };+ const live = this.state.sessions.get(input.sessionId);+ // Restoring history is silent; a just-completed runtime turn still gets its configured sound+ // when the chat query catches up with the terminal event.+ if (!live?.revealUntil || live.revealUntil <= Date.now()) this.baselineSoundSessionIds.add(input.sessionId);+ return [input.sessionId, entry];+ }));+ for (const [id, entry] of this.companionChats) {+ if (entry.companion.imageJpeg || !entry.input.visible || !companionAvatarHasArtwork(entry.input.companion.avatar)) continue;+ void companionAvatarThumbnail(entry.input.companion.avatar, entry.input.deviceId).then((imageJpeg) => {+ if (!imageJpeg || this.companionChats.get(id) !== entry) return;+ entry.companion = { ...entry.companion, imageJpeg };+ this.publish();+ });+ }+ this.publish();+ }++ private companionChatProjections() {+ return [...this.companionChats.values()].map(({ input, companion, token }) => ({ ...input, companion, token }));+ }+/*** A remote companion's identity is drawn at once with its tint and glyph; its artwork is* read through this computer's avatar copy and swapped in when ready. One object per@@ -835,6 +895,8 @@ export class AgentIslandService {this.clearSilencedRunTimer(runId);}resetAgentIslandState(this.state);+ this.companionChats.clear();+ this.publishAttentionCount(0);this.islandEntryAlert = null;this.emitSessionActivityTransitions([], Date.now());this.metadataCache.clear();@@ -1830,6 +1892,30 @@ export class AgentIslandService {return () => this.sessionActivityListeners.delete(listener);}+ /** The island's final attention projection, including restored companion chats. */+ getAttentionCount(): number {+ return this.attentionCount;+ }++ subscribeAttentionCount(listener: (count: number) => void): () => void {+ this.attentionCountListeners.add(listener);+ return () => this.attentionCountListeners.delete(listener);+ }++ private publishAttentionCount(count: number): void {+ if (count === this.attentionCount) return;+ this.attentionCount = count;+ for (const listener of this.attentionCountListeners) {+ try {+ listener(count);+ } catch (error) {+ log.warn('attention count listener failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }+private emitSessionActivityTransitions(list: readonly AgentIslandSessionActivity[],changedAtMs: number,@@ -1901,10 +1987,11 @@ export class AgentIslandService {this.baselineSoundSessionIds.clear();this.clearStreamingPreviewPublishTimer();this.lastSoundDisplayState = withAgentIslandConfig(- buildAgentIslandDisplayState(this.state, now),+ buildAgentIslandDisplayState(this.state, now, this.companionChatProjections()),this.soundSettings,this.mascotSkin,);+ this.publishAttentionCount(this.lastSoundDisplayState.pillSnapshot.attentionCount);// 侧栏卡片的逐步活动不依赖灵动岛开关:即便岛 UI 关闭,状态机仍累积,照常广播给 renderer。this.emitSessionActivityToRenderer();// Windows / headless / 用户关掉岛面时,仍要按 TTL 把完整会话迁到轻量未读账本。@@ -1924,11 +2011,12 @@ export class AgentIslandService {this.hiddenPublished = false;const displayState = this.localizeDisplayState(withAgentIslandConfig(- buildAgentIslandDisplayState(this.state, now),+ buildAgentIslandDisplayState(this.state, now, this.companionChatProjections()),this.soundSettings,this.mascotSkin,),);+ this.publishAttentionCount(displayState.pillSnapshot.attentionCount);this.emitSessionActivityToRenderer();this.scheduleNextPublish(now);this.playSoundForDisplayTransition(this.lastSoundDisplayState, displayState, now);@@ -2673,6 +2761,25 @@ export class AgentIslandService {private readonly completionActionsPending = new Set<string>();async handleCompletionAction(sessionId: string, action: 'mark-read' | 'archive', token: string): Promise<boolean> {+ const chat = this.companionChats.get(sessionId);+ if (chat) {+ const live = this.state.sessions.get(sessionId);+ const window = this.deps.getMainWindow();+ if (token !== chat.token || action !== 'mark-read' || !chat.input.visible || !chat.input.unread || !window || window.isDestroyed()+ || (live && live.phase !== 'completed')) return false;+ const owner = getActiveAppSession();+ window.webContents.send(AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL,+ { ...chat.input, readThroughAt: chat.input.lastMessageAt },+ { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation });+ chat.input = { ...chat.input, unread: false };+ if (live && !chat.input.deviceId) {+ clearAppBadgeSessionAttention(sessionId, 'explicit');+ this.handleSessionAttentionCleared(sessionId, 'explicit');+ }+ // This computer's chat read position owns the action, even for an offline remote home.+ this.publish();+ return true;+ }const session = this.state.sessions.get(sessionId);if (!session || !token || agentIslandCompletionToken(session) !== token || this.completionActionsPending.has(sessionId)) return false;// Companion main tasks have their own lifecycle; only their notification may be read here.diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex e552ab03c7..7b71d3e8bb 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -188,12 +188,15 @@ interface AgentIslandSessionState {*/sourceDeviceId: string | null;sourceCompletionToken?: string;+ /** Display-only chat projection; never written into the activity/relay state. */+ companionChat?: { unread: boolean; token: string };}const completionTokenEpoch = randomUUID();export function agentIslandCompletionToken(session: AgentIslandSessionState): string | undefined {if (session.phase !== 'completed') return undefined;+ if (session.companionChat) return session.companionChat.unread ? session.companionChat.token : undefined;return session.sourceDeviceId ? session.sourceCompletionToken: `${completionTokenEpoch}:${session.activityGeneration}`;}@@ -1521,6 +1524,7 @@ export function pruneAgentIslandSessions(state: AgentIslandState, now: number):export function buildAgentIslandDisplayState(state: AgentIslandState,now: number,+ companionChats: readonly AgentIslandCompanionChatProjection[] = [],): AgentIslandDisplayState {pruneAgentIslandSessions(state, now);updateHoverLifecycle(state, now);@@ -1530,7 +1534,7 @@ export function buildAgentIslandDisplayState(&& (state.isMouseInExpandedPanel || isCollapsePending(state, now)));promoteNextTransientReveal(state, now, manualExpanded);- const sortedSessions = Array.from(state.sessions.values())+ const sortedSessions = projectCompanionChats(state, companionChats).filter((session) => shouldDisplaySession(state,session,@@ -1580,6 +1584,56 @@ export function buildAgentIslandDisplayState(};}+export interface AgentIslandCompanionChatProjection {+ sessionId: string;+ deviceId: string | null;+ companion: AgentIslandCompanionSnapshot;+ visible: boolean;+ unread: boolean;+ lastMessageAt: number;+ preview: string;+ token: string;+}++/** Chat read positions own reply attention; the runtime still owns errors and interactions.+ * Reconstruct only the display, so old replies never become new completions, sounds or relay events.+ */+function projectCompanionChats(+ state: AgentIslandState,+ chats: readonly AgentIslandCompanionChatProjection[],+): AgentIslandSessionState[] {+ const sessions = new Map(state.sessions);+ for (const chat of chats) {+ const live = sessions.get(chat.sessionId);+ if (!chat.visible) {+ sessions.delete(chat.sessionId);+ continue;+ }+ if (!live && !chat.unread) continue;+ const session = live ? { ...live } : createSession({ sessionId: chat.sessionId }, chat.lastMessageAt);+ if (!live) {+ session.phase = 'completed';+ session.sourceDeviceId = chat.deviceId;+ session.detail = chat.preview;+ session.detailSource = null;+ session.completionNotification = 'silent';+ }+ session.companion = chat.companion;+ session.title = chat.companion.name;+ session.companionChat = { unread: chat.unread, token: chat.token };+ if (session.phase === 'completed') {+ session.unread = chat.unread;+ // A read chat leaves the island immediately, including the old completion dwell.+ if (!chat.unread) {+ sessions.delete(chat.sessionId);+ continue;+ }+ }+ sessions.set(chat.sessionId, session);+ }+ return [...sessions.values()];+}+/*** 侧栏活动广播专用:对**全部**已跟踪 session 生成 per-session 活动快照,不经灵动岛* 展示面(getDisplaySessionsForSurface)过滤。@@ -2155,6 +2209,7 @@ function orderSessionsForAutomaticReveal(activeTransient: AgentIslandSessionState | null,manualExpanded: boolean,): AgentIslandSessionState[] {+ activeTransient = sortedSessions.find(session => session.sessionId === activeTransient?.sessionId) ?? null;if (manualExpanded || !activeTransient || sortedSessions.some(isBlockingSession)) return sortedSessions;return [activeTransient,@@ -2207,7 +2262,8 @@ function buildDisplayDecision(};}- const activeTransient = getActiveTransientSession(state, now);+ const activeId = getActiveTransientSession(state, now)?.sessionId;+ const activeTransient = orderedSessions.find(session => session.sessionId === activeId);if (activeTransient && !shouldSmartSuppressSession(state, activeTransient)) {return {intent: { kind: 'transient', sessionId: activeTransient.sessionId },@@ -2307,7 +2363,7 @@ function getDisplaySessionsForSurface(// 徽标里「运行中」与「需要关注」互斥:等用户回答的任务只算需要关注,不重复计入运行中。function isBadgeRunningSession(session: AgentIslandSessionState): boolean {- return session.phase === 'running' && !isBlockingSession(session);+ return session.phase === 'running' && !isAttentionSession(session);}function isBlockingSession(session: AgentIslandSessionState): boolean {@@ -2541,7 +2597,13 @@ function getOrCreateSession(): AgentIslandSessionState {let session = state.sessions.get(meta.sessionId);if (session) return session;- session = {+ session = createSession(meta, now);+ state.sessions.set(meta.sessionId, session);+ return session;+}++function createSession(meta: AgentIslandSessionMeta, now: number): AgentIslandSessionState {+ return {sessionId: meta.sessionId,title: meta.title?.trim() || null,companion: null,@@ -2584,8 +2646,6 @@ function getOrCreateSession(activityGeneration: nextActivityGeneration(),sourceDeviceId: null,};- state.sessions.set(meta.sessionId, session);- return session;}function cloneSession(session: AgentIslandSessionState): AgentIslandSessionState {@@ -2688,6 +2748,7 @@ function toSnapshot(session: AgentIslandSessionState): AgentIslandSessionSnapsho}function isAttentionSession(session: AgentIslandSessionState): boolean {+ if (session.companionChat?.unread) return true;if (session.pendingInteractionIds.size > 0 || session.phase === 'needs-interaction') return true;return session.unread && (session.phase === 'completed' || session.phase === 'error');}@@ -2775,6 +2836,7 @@ function isUnreadTerminalWithinIslandTtl(session: AgentIslandSessionState, now:}function isSessionVisible(session: AgentIslandSessionState, now: number, preserveExpiredTransient = false): boolean {+ if (session.companionChat?.unread) return true;if (session.pendingInteractionIds.size > 0) return true;if (session.running) return true;// 岛面只在 TTL 内展示未读终态;过了 TTL prune 会把岛 state 删掉,未读迁到diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 49fcc60c39..ff84acb352 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -8,7 +8,7 @@ import { registerFilePeerIpc } from './device-link/filePeer';import { registerTaskMigrationIpc } from './task-migration/service';import { registerLoginItemIpc } from './login-item-ipc.js';import { registerMenubarIpc } from './menubar/ipc.js';-import { initMenubarService, refreshMenubarLocalization, stopMenubarService } from './menubar/service.js';+import { initMenubarService, refreshMenubarControlState, refreshMenubarLocalization, stopMenubarService } from './menubar/service.js';import {createLatestSourceVersionReader,sourceChannel,@@ -9924,6 +9924,7 @@ app.on('ready', async () => {// 设备互联(跨设备远程控制):登录后连 relay,登出即断;开关与设备列表 IPC 一并注册let updateRelaunchRemoteBusy = false;initDeviceLinkService({+ onControlledStateChanged: refreshMenubarControlState,onUpdateRelaunchBusyChanged: (busy) => {const transition = decideUpdateRelaunchBusyTransition(updateRelaunchRemoteBusy, busy);updateRelaunchRemoteBusy = transition.nextBusy;diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.tsindex 9140f41326..ed466bf6b0 100644--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@ -96,7 +96,7 @@ export type DeepLinkPayload =* 供应商接入流程)。URL 域只开放 tab=providers;connect 是可选的内置* provider / preset id,经白名单校验后透传给 renderer 已有的消费逻辑。*/- | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' }+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' }/*** 纯"把窗口拉回前台"意图,不携带导航语义 (典型来源:OAuth 授权成功页的* "打开 xdt-maker" 按钮 / 自动唤起)。main 进程内消化,不发给 renderer、@@ -418,6 +418,11 @@ export function openMainWindowVoiceSettings(tab: 'voice-input' | 'providers'): vdispatchDeepLink({ type: 'settings', tab });}+/** Internal menu-bar entry; reuse the existing main-window navigation queue. */+export function openMainWindowRemoteControlSettings(): void {+ dispatchDeepLink({ type: 'settings', tab: 'remote-control' });+}+/** 主进程内部入口(菜单栏余量面板)打开账单页的充值流程;URL 深链不开放这个 tab。 */export function openMainWindowBillingTopUp(): void {dispatchDeepLink({ type: 'settings', tab: 'billing', intent: 'topup' });diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex efb626682b..24eefd31af 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -686,6 +686,8 @@ function wsUrl(): string {/** Host integrations that consume device-link lifecycle state. */export interface DeviceLinkServiceOptions {onUpdateRelaunchBusyChanged?: (busy: boolean) => void;+ /** Host chrome follows the same controller set as CONTROLLED_STATE. */+ onControlledStateChanged?: () => void;}let stopNetworkWatch: (() => void) | null = null;@@ -1016,6 +1018,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 先注册远程活动监听,再接线入站帧;否则首个 subscribe / invoke 可能落在空窗期。setControllersChangedListener((controllers, updateRelaunchControllers) => {broadcast(DEVICE_LINK_PUSH.CONTROLLED_STATE, { controllers });+ options.onControlledStateChanged?.();updateRelaunchControllersBusy = updateRelaunchControllers.length > 0;notifyUpdateRelaunchBusy();});diff --git a/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts b/apps/desktop/src/main/menubar/MacMenubarNativeHost.tsindex d424f8c347..c9cbeaa34f 100644--- a/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts+++ b/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts@@ -349,6 +349,7 @@ export function parseHelperMessage(input: unknown): MenubarHelperMessage | nullcase 'refresh':case 'open-app':case 'open-provider-settings':+ case 'open-remote-control-settings':return { type: value.type };case 'error':return { type: 'error', message: typeof value.message === 'string' ? value.message.slice(0, 500) : '' };diff --git a/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts b/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.tsindex f4ec4e4fc8..b93ce44e7b 100644--- a/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts+++ b/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts@@ -9,6 +9,7 @@ describe('parseHelperMessage', () => {expect(parseHelperMessage({ type: 'panel', open: true })).toEqual({ type: 'panel', open: true });expect(parseHelperMessage({ type: 'open-session', sessionId: 's1' })).toEqual({ type: 'open-session', sessionId: 's1' });expect(parseHelperMessage({ type: 'refresh', extra: 1 })).toEqual({ type: 'refresh' });+ expect(parseHelperMessage({ type: 'open-remote-control-settings' })).toEqual({ type: 'open-remote-control-settings' });});it('rejects malformed or unknown messages', () => {diff --git a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.tsindex d672e49cce..06728d2cb7 100644--- a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts+++ b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts@@ -1,21 +1,34 @@import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { DEFAULT_MENUBAR_SETTINGS, type MenubarHelperMessage } from '../../../shared/menubarQuota';+import { emptyMenubarInputs } from '../collect';+import * as subscriptions from '../../device-link/subscriptions';const mocks = vi.hoisted(() => ({auth: { mode: 'cloud', dataOwnerId: 'owner', ownerGeneration: 1, user: { id: 'member', membershipKind: 'org' } },revision: 0, listeners: new Set<() => void>(), refresh: vi.fn(), collect: vi.fn(),quota: null as null | { spend: number; maxBudget: number; currency: string; fetchedAt: number; todaySpend: null },+ attentionCount: 0, attentionListeners: new Set<(count: number) => void>(), publish: vi.fn(),+ openRemoteSettings: vi.fn(), onHelperMessage: null as null | ((message: MenubarHelperMessage) => void),}));-vi.mock('electron', () => ({ app: {}, Notification: class {} }));-vi.mock('../../agent-island/service.js', () => ({ getAgentIslandService: () => null }));+vi.mock('electron', () => ({ app: { isPackaged: true }, Notification: class {} }));+vi.mock('../../agent-island/service.js', () => ({ getAgentIslandService: () => ({+ getAttentionCount: () => mocks.attentionCount,+ subscribeAttentionCount: (listener: (count: number) => void) => {+ mocks.attentionListeners.add(listener);+ return () => mocks.attentionListeners.delete(listener);+ },+ subscribeSessionActivity: () => () => {},+}) }));vi.mock('../../appCapabilities.js', () => ({ getAppCapabilities: () => ({ canUseCindyAccountServices: true }) }));vi.mock('../../appSessionState.js', () => ({ getActiveAppSession: () => ({ dataOwnerId: 'owner', mode: 'cloud', generation: mocks.auth.ownerGeneration }), isAppSessionBoundaryPending: () => false }));vi.mock('../../authManager.js', () => ({ getAuthState: () => mocks.auth, onAuthStateChange: () => () => {} }));vi.mock('../../billing/projection.js', () => ({}));vi.mock('../../clientEndpointsService.js', () => ({}));-vi.mock('../../deepLink.js', () => ({}));+vi.mock('../../deepLink.js', () => ({ openMainWindowRemoteControlSettings: mocks.openRemoteSettings }));vi.mock('../../device-link/index.js', () => ({}));+vi.mock('../../device-link/dispatch.js', () => ({ getActiveControllers: () => subscriptions.getControlControllers() }));vi.mock('../../device-link/ipc.js', () => ({}));vi.mock('../../device-link/deviceName.js', () => ({ deviceName: () => 'Fixture' }));-vi.mock('../../i18n.js', () => ({}));+vi.mock('../../i18n.js', () => ({ getResolvedMainLocale: () => 'en', mainStringKeysUnder: () => [], rawMainString: (key: string) => key }));vi.mock('../../localDb/ipc/sessions.js', () => ({}));vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn(), info: vi.fn() }) }));vi.mock('../../maker-host/createDesktopProviderService.js', () => ({}));@@ -25,19 +38,85 @@ vi.mock('../../maker-ipc/usage.js', () => ({}));vi.mock('../../notificationService.js', () => ({}));vi.mock('../../serverApiClient.js', () => ({}));vi.mock('../../usage/claudeAccountUsage.js', () => ({ readClaudeAccountUsageRevision: () => mocks.revision, observeClaudeAccountUsage: (listener: () => void) => { mocks.listeners.add(listener); return () => { mocks.listeners.delete(listener); }; }, triggerClaudeAccountUsageRefresh: () => mocks.refresh(), readClaudeAccountUsageSnapshot: () => mocks.quota }));-vi.mock('../../usage/ledgerCurrency.js', () => ({}));+vi.mock('../../usage/ledgerCurrency.js', () => ({ currentLedgerCurrency: () => 'USD' }));vi.mock('../../usage/usageHistory.js', () => ({}));vi.mock('../../usageBroadcaster.js', () => ({ observeUsageChanges: () => () => {} }));-vi.mock('../settingsStore.js', () => ({ readMenubarSettings: () => ({ enabled: true }), writeMenubarSettings: (value: unknown) => value }));-vi.mock('../MacMenubarNativeHost.js', () => ({ MacMenubarNativeHost: class { resetFailure() {} prepare() {} suspend() {} stop() {} } }));+vi.mock('../settingsStore.js', () => ({ readMenubarSettings: () => ({ ...DEFAULT_MENUBAR_SETTINGS }), writeMenubarSettings: (value: unknown) => value }));+vi.mock('../MacMenubarNativeHost.js', () => ({ MacMenubarNativeHost: class {+ constructor(options: { onMessage: (message: MenubarHelperMessage) => void }) { mocks.onHelperMessage = options.onMessage; }+ resetFailure() {} prepare() {} suspend() {} stop() {} publish(view: unknown) { mocks.publish(view); }+} }));vi.mock('../creditSamples.js', () => ({ CreditSampleStore: class { record() { return []; } }, estimateDailyBurn: () => null }));-vi.mock('../collect.js', () => ({ collectMenubarInputs: (...args: unknown[]) => mocks.collect(...args) }));+vi.mock('../collect.js', async (importOriginal) => ({ ...await importOriginal<typeof import('../collect')>(), collectMenubarInputs: (...args: unknown[]) => mocks.collect(...args) }));import { MenubarService } from '../service';beforeEach(() => {vi.useFakeTimers(); mocks.revision = 0; mocks.listeners.clear(); mocks.refresh.mockReset(); mocks.collect.mockReset();+ mocks.attentionCount = 0; mocks.attentionListeners.clear(); mocks.publish.mockReset();+ mocks.openRemoteSettings.mockReset(); mocks.onHelperMessage = null;+ subscriptions.__testing.reset();mocks.quota = { spend: 2, maxBudget: 10, currency: 'CNY', fetchedAt: Date.now(), todaySpend: null };});afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });++// Unit: unread updates bypass slow usage collection, survive rebuilds and detach on stop.+it('updates the native count immediately while a usage rebuild is still pending', async () => {+ const service = new MenubarService({ openNewTask() {} });+ const collected = emptyMenubarInputs(Date.now(), 'Fixture');+ mocks.attentionCount = 2;+ subscriptions.subscribe('phone', ['session:chat']);+ mocks.collect.mockResolvedValue(collected);+ service.init();+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ attentionCount: 2, remotelyControlled: true }));+ let resolve!: (value: typeof collected) => void;+ mocks.collect.mockImplementationOnce(() => new Promise(done => { resolve = done; }));+ service.refreshLocalization();+ await vi.advanceTimersByTimeAsync(0);+ mocks.attentionCount = 0;+ for (const listener of mocks.attentionListeners) listener(0);+ subscriptions.clearAll();+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ attentionCount: 0, remotelyControlled: false }));+ resolve(collected);+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ attentionCount: 0, remotelyControlled: false }));+ service.stop();+ expect(mocks.attentionListeners.size).toBe(0);+});++// Unit: the menu-bar dot uses the actual banner predicate, not mere device presence.+it('lights only for active task controllers and clears after the last controller leaves', async () => {+ const service = new MenubarService({ openNewTask() {} });+ mocks.collect.mockResolvedValue(emptyMenubarInputs(Date.now(), 'Fixture'));+ subscriptions.subscribe('phone', ['sessions', 'fs-watch:/repo']);+ service.init();+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remotelyControlled: false }));+ subscriptions.subscribe('phone', ['session:chat']);+ subscriptions.updateControllerMetadata('phone', 'Dash’s iPhone');+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remotelyControlled: true, remoteControllerNames: ['Dash’s iPhone'] }));+ subscriptions.updateControllerMetadata('phone', 'Travel iPhone');+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remoteControllerNames: ['Travel iPhone'] }));+ mocks.onHelperMessage?.({ type: 'open-remote-control-settings' });+ expect(mocks.openRemoteSettings).toHaveBeenCalledOnce();+ mocks.publish.mockClear();+ subscriptions.subscribe('mac', ['*']);+ subscriptions.updateControllerMetadata('mac', 'MacBook Air');+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remoteControllerNames: ['Travel iPhone', 'MacBook Air'] }));+ subscriptions.clearController('phone');+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remotelyControlled: true, remoteControllerNames: ['MacBook Air'] }));+ mocks.publish.mockClear();+ service.refreshControlState();+ expect(mocks.publish).not.toHaveBeenCalled();+ subscriptions.clearController('mac');+ service.refreshControlState();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ remotelyControlled: false, remoteControllerNames: [] }));+ service.stop();+});function clearQuota() {mocks.quota = null; mocks.revision++;for (const listener of mocks.listeners) listener();diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.tsindex fbba18cf19..0abbf2c4d5 100644--- a/apps/desktop/src/main/menubar/service.ts+++ b/apps/desktop/src/main/menubar/service.ts@@ -37,9 +37,11 @@ import {focusMainWindow,openMainWindowBillingTopUp,openMainWindowSession,+ openMainWindowRemoteControlSettings,openMainWindowVoiceSettings,} from '../deepLink.js';import { remoteBackgroundInvoke } from '../device-link/index.js';+import { getActiveControllers } from '../device-link/dispatch.js';import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';import { deviceName } from '../device-link/deviceName.js';import { getResolvedMainLocale, mainStringKeysUnder, rawMainString } from '../i18n.js';@@ -190,6 +192,27 @@ export class MenubarService {if (this.started) this.scheduleRebuild(0);}+ /** Remote activity updates the icon immediately, independently of usage collection. */+ refreshControlState(): void {+ if (!this.started || !this.lastView || this.lastView.gate) return;+ const control = this.controlState();+ if (+ this.lastView.remotelyControlled === control.remotelyControlled+ && JSON.stringify(this.lastView.remoteControllerNames) === JSON.stringify(control.remoteControllerNames)+ ) return;+ this.lastView = { ...this.lastView, ...control };+ this.host.publish(this.lastView);+ }++ private controlState(gate?: MenubarGate): Pick<MenubarView, 'remotelyControlled' | 'remoteControllerNames'> {+ const controllers = gate ? [] : getActiveControllers();+ return {+ // Keep the indicator visible in dev for tuning without inventing a connected device.+ remotelyControlled: !app.isPackaged || controllers.length > 0,+ remoteControllerNames: controllers.map(controller => controller.name),+ };+ }+/** Opens the panel under the status item. */openPanel(): void {if (!this.started) return;@@ -231,6 +254,7 @@ export class MenubarService {const island = getAgentIslandService();if (island) {this.disposers.push(+ island.subscribeAttentionCount((count) => this.publishAttentionCount(count)),island.subscribeSessionActivity(({ previous, current }) => {const wasRunning = previous ? isSessionActivityRunning(previous) : false;const isRunning = current ? isSessionActivityRunning(current) : false;@@ -454,6 +478,8 @@ export class MenubarService {...(gate ? { gate } : {}),};const view = buildMenubarView(input);+ view.attentionCount = gate ? 0 : (getAgentIslandService()?.getAttentionCount() ?? 0);+ Object.assign(view, this.controlState(gate));this.lastView = view;this.host.publish(view);if (gate) {@@ -464,6 +490,14 @@ export class MenubarService {this.updateLowAlert(isLowOnEverything(input), input);}+ /** Unread changes must not wait for quota/history/network reads to finish. */+ private publishAttentionCount(count: number): void {+ if (!this.started || !this.lastView || this.lastView.gate) return;+ if (this.lastView.attentionCount === count) return;+ this.lastView = { ...this.lastView, attentionCount: count };+ this.host.publish(this.lastView);+ }+// ── Low alert ──────────────────────────────────────────────────────────────/** Notifies once when everything usable drops to nearly empty; never on the first build. */@@ -635,6 +669,9 @@ export class MenubarService {case 'open-provider-settings':openMainWindowVoiceSettings('providers');return;+ case 'open-remote-control-settings':+ openMainWindowRemoteControlSettings();+ return;case 'settings':this.applySettingsPatch(message.patch);return;@@ -733,6 +770,10 @@ export function refreshMenubarLocalization(): void {service?.refreshLocalization();}+export function refreshMenubarControlState(): void {+ service?.refreshControlState();+}+export function stopMenubarService(): void {service?.stop();}diff --git a/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts b/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.tsindex b7d0bde04b..18acd00eee 100644--- a/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts+++ b/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts@@ -3,7 +3,7 @@ import ts from 'typescript';import { afterEach, describe, expect, it, vi } from 'vitest';import type { BrowserWindow } from 'electron';-import { handleIncomingDeepLink, openMainWindowSession, setDeepLinkMainWindow, takePendingDeepLink } from '../../main/deepLink';+import { handleIncomingDeepLink, openMainWindowRemoteControlSettings, openMainWindowSession, setDeepLinkMainWindow, takePendingDeepLink } from '../../main/deepLink';vi.mock('electron', () => ({ app: { focus: vi.fn() }, BrowserWindow: class {} }));vi.mock('../../main/logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), debug: vi.fn() }) }));@@ -46,6 +46,22 @@ function connect() {afterEach(() => setDeepLinkMainWindow(null));+// Unit regression: a menu-bar click focused the app but preload silently dropped+// the new settings tab. Exercise the real main dispatch and production bridge.+it('delivers remote-control settings through the live bridge and cold-start buffer', () => {+ const { received, deliver } = connect();+ openMainWindowRemoteControlSettings();+ const expected = { type: 'settings', tab: 'remote-control' };+ expect(received).toEqual([expected]);+ deliver({ type: 'settings', tab: 'unknown' });+ deliver({ type: 'settings', tab: 'remote-control', connect: 'codex' });+ expect(received).toEqual([expected]);+ setDeepLinkMainWindow(null);+ openMainWindowRemoteControlSettings();+ expect(takePendingDeepLink()).toEqual(expected);+ expect(takePendingDeepLink()).toBeNull();+});+describe('Agent Island click id across the preload deep-link bridge', () => {// External links must keep their owning computer through both the live bridge// and the cold-start buffer; otherwise a same-id local task wins.diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b7258cbbd4..b89d19b397 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -77,6 +77,10 @@ import {AGENT_ISLAND_SET_ENABLED_CHANNEL,AGENT_ISLAND_SET_MASCOT_SKIN_CHANNEL,AGENT_ISLAND_SET_REMOTE_SESSIONS_CHANNEL,+ AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL,+ AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL,+ type AgentIslandCompanionChatsInput,+ type AgentIslandCompanionChatRead,AGENT_ISLAND_SET_SOUND_SETTINGS_CHANNEL,AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL,type AgentIslandDisplayOption,@@ -2114,6 +2118,15 @@ contextBridge.exposeInMainWorld('electronAPI', {},agentIsland: {+ setCompanionChats: (snapshot: AgentIslandCompanionChatsInput): Promise<{ ok: true }> =>+ ipcRenderer.invoke(AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL, snapshot),+ onCompanionChatRead: (cb: (chat: AgentIslandCompanionChatRead, stamp: DataOwnerPushStamp) => void): (() => void) => {+ const handler = (_event: unknown, chat: AgentIslandCompanionChatRead, stamp: DataOwnerPushStamp) => {+ if (isDataOwnerPushStamp(stamp)) cb(chat, stamp);+ };+ ipcRenderer.on(AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL, handler);+ return () => ipcRenderer.removeListener(AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL, handler);+ },setVisibleSession: (sessionId: string | string[] | null): Promise<{ ok: true }> =>ipcRenderer.invoke(AGENT_ISLAND_SET_VISIBLE_SESSION_CHANNEL, sessionId),setEnabled: (enabled: boolean): Promise<{ ok: true }> =>@@ -4006,7 +4019,7 @@ contextBridge.exposeInMainWorld('electronAPI', {| { type: 'provider-share-join'; link: string }| { type: 'chat-invite'; token: string }| { type: 'chat-invite-malformed' }- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'remote-control'; connect?: string },) => void,): (() => void) =>fanOutDeepLinkNavigate((payload) => {@@ -4049,7 +4062,7 @@ contextBridge.exposeInMainWorld('electronAPI', {&& [p.groupId, p.messageId, ...(p.threadRootId === undefined ? [] : [p.threadRootId])].every(value => typeof value === 'string' && /^[0-9a-f-]{36}$/i.test(value))) {callback({ type: 'chat-message', groupId: p.groupId, messageId: p.messageId,...(typeof p.threadRootId === 'string' ? { threadRootId: p.threadRootId } : {}) });- } else if (p.type === 'settings' && (p.tab === 'voice-input' || p.tab === 'providers')) {+ } else if (p.type === 'settings' && (p.tab === 'voice-input' || p.tab === 'providers' || p.tab === 'remote-control')) {// connect 只对 providers 页有意义;主进程已做 id 白名单,这里按纵深防御// 原样复用同一规则。字段存在但不合法时丢弃整个 payload,不降级成半执行。if (@@ -4116,7 +4129,7 @@ contextBridge.exposeInMainWorld('electronAPI', {| { type: 'provider-share-join'; link: string }| { type: 'chat-invite'; token: string }| { type: 'chat-invite-malformed' }- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string }+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'remote-control'; connect?: string }| null> => ipcRenderer.invoke('deep-link:take-pending'),diff --git a/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx b/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsxindex 104f398931..ec4a4cb851 100644--- a/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx+++ b/apps/desktop/src/renderer/__tests__/AppBadgeAttentionSync.test.tsx@@ -1,6 +1,8 @@// @vitest-environment jsdomimport { cleanup, render, renderHook } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';+import type { AgentIslandCompanionChatRead, AgentIslandCompanionChatsInput } from '../../shared/agentIsland';+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush';const state = vi.hoisted(() => ({sessions: ['a', 'b', 'c'].map((id) => ({ id, status: 'active' })) as { id: string; status: string; source?: string }[],@@ -26,19 +28,26 @@ const botState = vi.hoisted(() => ({groups: [] as unknown[],unreadGroups: new Set<string>(),remote: [] as unknown[],+ markRead: vi.fn(),+ markRemoteRead: vi.fn(),}));vi.mock('@/features/bots/useBotUnreadSync', () => ({ useBotUnreadSync: () => {} }));-vi.mock('@/features/bots/botStore', () => ({ useBotProfiles: () => botState.bots, useBotUnreadCounts: () => botState.unread }));+vi.mock('@/features/bots/botStore', () => ({ useBotProfiles: () => botState.bots, useBotUnreadCounts: () => botState.unread,+ canonicalBotSessionId: (bot: { sessions: { id: string; role?: string; kind?: string }[] }) => bot.sessions.find(session => session.role === 'canonical' || session.kind === 'chat')?.id,+}));vi.mock('@/features/bots/botGroupStore', () => ({ useBotGroupList: () => ({ groups: botState.groups }) }));vi.mock('@/features/bots/botReadState', () => ({isBotGroupUnread: (group: { id: string }) => botState.unreadGroups.has(group.id),subscribeBotReadState: () => () => {},getBotLastReadAtMap: () => ({}),+ markBotRead: botState.markRead,}));-vi.mock('@/features/bots/useRemoteBots', () => ({ useRemoteBotSync: () => {}, useRemoteBots: () => botState.remote }));+vi.mock('@/features/bots/useRemoteBots', () => ({ useRemoteBotSync: () => {}, useRemoteBots: () => botState.remote, markRemoteBotRead: botState.markRemoteRead }));vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({}) }));vi.mock('@/contexts/dataOwnerGeneration', () => ({getDataOwnerGeneration: () => state.owner,+ isDataOwnerPushCurrent: (stamp: { dataOwnerId: string; ownerGeneration: number }) =>+ stamp.dataOwnerId === state.owner.dataOwnerId && stamp.ownerGeneration === state.owner.generation,isDataOwnerGenerationCurrent: (owner: typeof state.owner) =>owner.dataOwnerId === state.owner.dataOwnerId && owner.generation === state.owner.generation,}));@@ -88,6 +97,7 @@ afterEach(() => {botState.bots = []; botState.unread = {}; botState.groups = []; botState.unreadGroups = new Set(); botState.remote = [];vi.unstubAllGlobals();state.publish.mockClear();+ botState.markRead.mockClear(); botState.markRemoteRead.mockClear();state.isLoading = false;state.sessions = ['a', 'b', 'c'].map((id) => ({ id, status: 'active' }));state.history = null;@@ -104,6 +114,44 @@ afterEach(() => {});describe('app badge projection lifecycle', () => {+ // Existing Dock tests did not verify the island or its read action. One unread local chat+ // and one offline remote chat must survive task-list loading and use the same read positions (unit).+ it('syncs companion unread independently of task loading and applies owner-fenced island reads', () => {+ const set = vi.fn<(input: AgentIslandCompanionChatsInput) => Promise<{ ok: true }>>().mockResolvedValue({ ok: true });+ let read!: (chat: AgentIslandCompanionChatRead, stamp: DataOwnerPushStamp) => void;+ vi.stubGlobal('electronAPI', { notificationSetAppAttentionCount: state.publish, agentIsland: {+ setCompanionChats: set,+ onCompanionChatRead: (cb: typeof read) => { read = cb; return () => {}; },+ } });+ const local = { id: 'bot', name: 'Cindy', avatar: '', avatarColor: 'blue', createdAt: 1,+ lastMessageAt: 100, lastMessageRole: 'assistant', lastMessagePreview: 'new reply',+ sessions: [{ id: 'chat', role: 'canonical' }] };+ botState.bots = [local, { ...local, id: 'hidden', hiddenAt: 1, sessions: [{ id: 'hidden-chat', role: 'canonical' }] }];+ botState.unread = { bot: 2, hidden: 1 };+ botState.remote = [{ id: 'remote', sessionId: 'remote-chat', deviceId: 'other-computer', name: 'Remote',+ avatar: '', avatarColor: 'blue', activityAt: 100, lastReplyAt: 100, readAt: 50, preview: 'remote reply', online: false }];+ state.isLoading = true;+ const view = render(<AppBadgeAttentionSync />);+ const snapshot = set.mock.calls.at(-1)![0];+ expect(snapshot.chats).toEqual([+ expect.objectContaining({ sessionId: 'chat', visible: true, unread: true }),+ expect.objectContaining({ sessionId: 'hidden-chat', visible: false }),+ expect.objectContaining({ sessionId: 'remote-chat', deviceId: 'other-computer', unread: true }),+ ]);+ const stamp = { dataOwnerId: state.owner.dataOwnerId, ownerGeneration: state.owner.generation };+ read({ ...snapshot.chats[0], readThroughAt: 100 }, stamp);+ expect(botState.markRead).toHaveBeenCalledWith('bot', 100);+ read({ ...snapshot.chats[2], readThroughAt: 100 }, stamp);+ expect(botState.markRemoteRead).toHaveBeenCalledWith('other-computer', 'remote', 100);+ read({ ...snapshot.chats[0], readThroughAt: 200 }, { ...stamp, ownerGeneration: 0 });+ expect(botState.markRead).toHaveBeenCalledTimes(1);+ botState.remote = botState.remote.map(bot => ({ ...(bot as object), online: true }));+ view.rerender(<AppBadgeAttentionSync />);+ expect(set).toHaveBeenCalledTimes(2);+ botState.unread = {};+ view.rerender(<AppBadgeAttentionSync />);+ expect(set.mock.calls.at(-1)![0].chats[0].unread).toBe(false);+ });it.each(['done', 'awaiting', 'error'])('excludes hidden Make tasks with %s attention while retaining notification deduplication IDs', (kind) => {vi.stubGlobal('electronAPI', { notificationSetAppAttentionCount: state.publish });state.sessions = [diff --git a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsxindex 8f76dee630..bbd3951318 100644--- a/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx+++ b/apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx@@ -18,6 +18,7 @@ import { useBotProfiles, useBotUnreadCounts } from '@/features/bots/botStore';import { useBotGroupList } from '@/features/bots/botGroupStore';import { isBotGroupUnread, subscribeBotReadState, getBotLastReadAtMap } from '@/features/bots/botReadState';import { useBotUnreadSync } from '@/features/bots/useBotUnreadSync';+import { useCompanionIslandChats } from '@/features/bots/useCompanionIslandChats';import { useRemoteBotSync, useRemoteBots } from '@/features/bots/useRemoteBots';import { isRemoteBotUnread } from '@/features/bots/remoteBotRoster';import { useCompanionCloud } from '@/features/bots/companionCloudStore';@@ -39,6 +40,7 @@ export function AppBadgeAttentionSync() {const { groups } = useBotGroupList();const rosterRemoteBots = useRemoteBots();const remoteBots = useMemo(() => cloudRemoteBots(cloud, rosterRemoteBots), [cloud, rosterRemoteBots]);+ useCompanionIslandChats(allBots, bots, unread, remoteBots);useSyncExternalStore(subscribeBotReadState, readRevision, readRevision);const localTeammates = bots.filter(bot => bot.status !== 'archived' && bot.status !== 'deleting' && !bot.hiddenAt && (unread[bot.id] ?? 0) > 0).length+ groups.filter(group => !group.archived && isBotGroupUnread(group)).length;diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 28623a0f00..820ea75897 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -711,7 +711,7 @@ export function MainLayout() {| { type: 'chat-invite'; token: string }| { type: 'chat-invite-malformed' }| { type: 'provider-share-join'; link: string }- | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' },+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' },) => {if (payload.type === 'chat-message') {const search = new URLSearchParams({ messageId: payload.messageId });diff --git a/apps/desktop/src/renderer/features/bots/useCompanionIslandChats.ts b/apps/desktop/src/renderer/features/bots/useCompanionIslandChats.tsnew file mode 100644index 0000000000..8271b92e46--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/useCompanionIslandChats.ts@@ -0,0 +1,70 @@+import { useEffect } from 'react';+import { getDataOwnerGeneration, isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';+import type { AgentIslandCompanionChatInput } from '../../../shared/agentIsland';+import { AGENT_ISLAND_REMOTE_SESSIONS_MAX } from '../../../shared/agentIsland';+import { canonicalBotSessionId, type BotProfile } from './botStore';+import { markBotRead } from './botReadState';+import { isRemoteBotUnread, type RemoteBot } from './remoteBotRoster';+import { markRemoteBotRead } from './useRemoteBots';+import { createLogger } from '@/lib/logger';++const log = createLogger('companionIslandChats');++export function buildCompanionIslandChats(+ allBots: readonly BotProfile[],+ visibleBots: readonly BotProfile[],+ unread: Readonly<Record<string, number>>,+ remoteBots: readonly RemoteBot[],+): AgentIslandCompanionChatInput[] {+ const visibleIds = new Set(visibleBots.map(bot => bot.id));+ const chats = new Map<string, AgentIslandCompanionChatInput>();+ for (const bot of allBots) {+ const sessionId = canonicalBotSessionId(bot);+ if (!sessionId) continue;+ chats.set(sessionId, {+ sessionId, botId: bot.id, deviceId: null,+ companion: { name: bot.name, avatar: bot.avatar, avatarColor: bot.avatarColor },+ visible: visibleIds.has(bot.id) && !bot.hiddenAt && bot.status !== 'archived' && bot.status !== 'deleting',+ unread: (unread[bot.id] ?? 0) > 0,+ lastMessageAt: bot.lastMessageAt ?? bot.createdAt,+ preview: bot.lastMessageRole === 'assistant' ? bot.lastMessagePreview ?? '' : '',+ });+ }+ // Cached unread remains useful while its home is offline. The roster already handles revocation.+ for (const bot of remoteBots) {+ if (!bot.sessionId) continue;+ chats.set(bot.sessionId, {+ sessionId: bot.sessionId, botId: bot.id, deviceId: bot.deviceId,+ companion: { name: bot.name, avatar: bot.avatar, avatarColor: bot.avatarColor },+ visible: true, unread: isRemoteBotUnread(bot),+ lastMessageAt: bot.lastReplyAt ?? bot.activityAt, preview: bot.preview,+ });+ }+ return [...chats.values()].slice(0, AGENT_ISLAND_REMOTE_SESSIONS_MAX);+}++/** Shares the sidebar's existing read positions; no second unread ledger or startup replay. */+export function useCompanionIslandChats(+ allBots: readonly BotProfile[],+ visibleBots: readonly BotProfile[],+ unread: Readonly<Record<string, number>>,+ remoteBots: readonly RemoteBot[],+): void {+ const owner = getDataOwnerGeneration();+ const signature = JSON.stringify(buildCompanionIslandChats(allBots, visibleBots, unread, remoteBots));+ // Re-send on reconnect so an unavailable avatar can use the existing thumbnail lookup again.+ const availability = remoteBots.map(bot => `${bot.deviceId}:${bot.id}:${bot.online}`).join('|');+ useEffect(() => {+ const set = window.electronAPI?.agentIsland?.setCompanionChats;+ if (!set) return;+ void set({ dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation,+ chats: JSON.parse(signature) }).catch(error => {+ log.warn('failed to sync companion chats', error);+ });+ }, [signature, availability, owner]);+ useEffect(() => window.electronAPI?.agentIsland?.onCompanionChatRead?.((chat, stamp) => {+ if (!isDataOwnerPushCurrent(stamp)) return;+ if (chat.deviceId) markRemoteBotRead(chat.deviceId, chat.botId, chat.readThroughAt);+ else markBotRead(chat.botId, chat.readThroughAt);+ }), []);+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex bc888084f6..c3ca543f83 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1348,6 +1348,8 @@"moreTasks_other": "{{n}} more tasks","running": "Running","openApp": "Open Cindy",+ "remoteControlTitle": "Remote control active",+ "remoteControlBody": "Other devices are accessing Cindy on this computer.","gateTitle": "Sign in to see what's left","gateBody": "Sign in to Cindy, or choose Skip Sign-In, and this panel shows your subscription quota and today's usage.","settings": "Manage",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fc2596eba6..85c7ad0cdb 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1321,6 +1321,8 @@"moreTasks_other": "ほか {{n}} 件のタスク","running": "実行中","openApp": "Cindy を開く",+ "remoteControlTitle": "リモート操作中",+ "remoteControlBody": "ほかのデバイスがこのコンピュータの Cindy にアクセスしています。","gateTitle": "ログインすると残りを確認できます","gateBody": "Cindy にログインするか、ログインをスキップすると、ここにサブスクリプションの残りと今日の使用量が表示されます。","settings": "管理",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 4a9043e71f..6fb02ac793 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1321,6 +1321,8 @@"moreTasks_other": "작업 {{n}}개 더","running": "진행 중","openApp": "Cindy 열기",+ "remoteControlTitle": "원격 제어 중",+ "remoteControlBody": "다른 기기에서 이 컴퓨터의 Cindy에 접근하고 있어요.","gateTitle": "로그인하면 남은 양을 볼 수 있어요","gateBody": "Cindy에 로그인하거나 로그인 건너뛰기를 선택하면 여기에 구독 남은 양과 오늘 사용량이 표시돼요.","settings": "관리",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a1c1072592..5852cea75a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1321,6 +1321,8 @@"moreTasks_other": "另外 {{n}} 个任务","running": "运行中","openApp": "打开 Cindy",+ "remoteControlTitle": "远程控制中",+ "remoteControlBody": "其他设备正在访问此电脑上的 Cindy","gateTitle": "登录后查看余量","gateBody": "在 Cindy 里登录,或选择跳过登录,这里就会显示订阅余量和今天的用量。","settings": "管理",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 9fe6b3f976..90bff8647a 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1321,6 +1321,8 @@"moreTasks_other": "另外 {{n}} 個任務","running": "執行中","openApp": "打開 Cindy",+ "remoteControlTitle": "遠端控制中",+ "remoteControlBody": "其他裝置正在存取這台電腦上的 Cindy","gateTitle": "登入後查看餘量","gateBody": "在 Cindy 裡登入,或選擇跳過登入,這裡就會顯示訂閱餘量和今天的用量。","settings": "管理",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8469b3eefa..e1e3acb839 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2120,6 +2120,8 @@ interface ElectronAPI {};agentIsland: {+ setCompanionChats: (snapshot: import('../shared/agentIsland').AgentIslandCompanionChatsInput) => Promise<{ ok: true }>;+ onCompanionChatRead: (cb: (chat: import('../shared/agentIsland').AgentIslandCompanionChatRead, stamp: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void) => () => void;setVisibleSession: (sessionId: string | string[] | null) => Promise<{ ok: true }>;setEnabled: (enabled: boolean) => Promise<{ ok: true }>;consumeEntryAlert: (sessionId: string, islandEntryId: string) => Promise<{ ok: true; consumed: boolean }>;@@ -3069,7 +3071,7 @@ interface ElectronAPI {| { type: 'chat-invite'; token: string }| { type: 'chat-invite-malformed' }| { type: 'provider-share-join'; link: string }- | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' },+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' },) => void,) => () => void;@@ -3090,7 +3092,7 @@ interface ElectronAPI {| { type: 'chat-invite'; token: string }| { type: 'chat-invite-malformed' }| { type: 'provider-share-join'; link: string }- | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' }+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' }| null>;diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex 46b848b71b..d49cbe019c 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -801,6 +801,52 @@ 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';+// Local main-window presentation only; never exposed through device-link.+export const AGENT_ISLAND_SET_COMPANION_CHATS_CHANNEL = 'agent-island:set-companion-chats';+export const AGENT_ISLAND_READ_COMPANION_CHAT_CHANNEL = 'agent-island:read-companion-chat';++export interface AgentIslandCompanionChatInput {+ sessionId: string;+ botId: string;+ deviceId: string | null;+ companion: AgentIslandRemoteCompanionInput;+ visible: boolean;+ unread: boolean;+ lastMessageAt: number;+ preview: string;+}++export interface AgentIslandCompanionChatsInput {+ dataOwnerId: string | null;+ ownerGeneration: number;+ chats: AgentIslandCompanionChatInput[];+}++export interface AgentIslandCompanionChatRead extends AgentIslandCompanionChatInput {+ readThroughAt: number;+}++export function parseAgentIslandCompanionChats(raw: unknown): AgentIslandCompanionChatInput[] | null {+ if (!Array.isArray(raw) || raw.length > AGENT_ISLAND_REMOTE_SESSIONS_MAX) return null;+ const chats: AgentIslandCompanionChatInput[] = [];+ const seen = new Set<string>();+ for (const item of raw) {+ if (!item || typeof item !== 'object') return null;+ const row = item as Record<string, unknown>;+ const sessionId = readBoundedString(row.sessionId, AGENT_ISLAND_REMOTE_ID_MAX_LENGTH);+ const botId = readBoundedString(row.botId, AGENT_ISLAND_REMOTE_ID_MAX_LENGTH);+ const deviceId = row.deviceId === null ? null : readBoundedString(row.deviceId, AGENT_ISLAND_REMOTE_ID_MAX_LENGTH);+ const companion = readRemoteCompanion(row.companion);+ if (!sessionId || !botId || !companion || (row.deviceId !== null && !deviceId)+ || typeof row.visible !== 'boolean' || typeof row.unread !== 'boolean'+ || typeof row.lastMessageAt !== 'number' || !Number.isFinite(row.lastMessageAt) || row.lastMessageAt < 0+ || seen.has(sessionId)) return null;+ seen.add(sessionId);+ chats.push({ sessionId, botId, deviceId, companion, visible: row.visible, unread: row.unread,+ lastMessageAt: row.lastMessageAt, preview: readBoundedString(row.preview, AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH) ?? '' });+ }+ return chats;+}/*** 远程设备(device-link「我控制它」)任务的活动镜像,供本机灵动岛与桌面通知使用。diff --git a/apps/desktop/src/shared/menubarQuota.ts b/apps/desktop/src/shared/menubarQuota.tsindex fe1aec9b20..4a2f59de4e 100644--- a/apps/desktop/src/shared/menubarQuota.ts+++ b/apps/desktop/src/shared/menubarQuota.ts@@ -189,6 +189,12 @@ export interface MenubarView {strings: MenubarStrings;/** Text after the menu bar icon for each mode; the active one is `settings.statusText`. */statusTextByMode: Record<MenubarStatusTextMode, string | null>;+ /** Same attention count as Agent Island, shown before the optional usage text. */+ attentionCount?: number;+ /** Same active-controller predicate as the in-app connection indicator. */+ remotelyControlled?: boolean;+ /** Live display names from the same controller set as the in-app indicator. */+ remoteControllerNames?: string[];updatedAtMs: number | null;headlinePrimary: string;headlineSecondary: string | null;@@ -220,6 +226,7 @@ export type MenubarHelperMessage =| { type: 'open-session'; sessionId: string }| { type: 'detail-action'; sourceId: string }| { type: 'open-provider-settings' }+ | { type: 'open-remote-control-settings' }| { type: 'settings'; patch: MenubarSettingsPatch };/** Settings → Window behavior toggle; only the local app renderer may call these. */diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 2214bdee47..3928ac2f70 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -609,6 +609,8 @@ The usage heatmap, daily-token bars and their separate interaction indicators foIcon refinement reference (2026-10-18, macOS AppKit rendering; enlarged and actual 18pt size):[Light/Dark before and after](assets/menubar-icon-refinement.png).+- Remote control uses the same active-controller set as the in-app connection indicator. Its menu-bar dot uses a brighter orange (`#FF9F0A`, owner correction, 2026-10-25). The 5pt dot sits near the icon's upper-left corner, centered at (4.5pt, 4.5pt), with a 0.75pt transparent rim, without widening the 18pt icon or moving the unread count. Release builds light it only for active controllers and clear it when the last one leaves; development builds temporarily keep it visible for visual tuning. The number uses 13pt regular monospaced digits with a thin space after the icon. The native menu item and its settings preview use the same artwork (owner request, 2026-10-25).+- When the remote-control dot is visible, the main panel explains it directly below the wordmark: a neutral computer symbol with the same orange dot, “Remote control active”, and the active devices' names, joined by middle dots (owner request, 2026-10-26). Names update on connection, disconnection and rename even while usage collection is pending; two visible lines keep the strip compact, with the full list available on hover and to accessibility. The entire row opens Settings → Remote control through the existing main-window navigation, with a quiet chevron and hover fill. This status strip stays above the scrolling quota content, shares the panel's warm neutrals and translucent backdrop, and ends with the existing inset hairline. Development preview without a real controller keeps the generic explanation rather than inventing a device name, including on the sign-in panel. Both appearances and all five languages share this layout.- A native status item (`NSStatusItem`) and panel rendered by the Swift helper in `apps/desktop/native/menubar/`, not an HTML window. Main builds every sentence and value; the helper renders, animates and formats only times that tick while the panel is open. Available on macOS 14+ and toggled in Settings → Window behavior (default on).- The panel uses the system popover material (`NSVisualEffectView`, `.popover`) with a 0.5pt hairline edge, so it follows the desktop wallpaper and Light/Dark automatically. Over the material it lays a warm tint (Light `#F8F7F3` at 50%, Dark `#1A1918` at 54%; owner corrections, 2026-10-16: 72%/74% was noticeably more solid than the plain material, 22%/26% let busy wallpapers wash out gray text and made the tiles read as pasted-on boxes) and a faint Heart Orange glow in the top-left corner, so the panel reads in Cindy's warm neutrals instead of the cool system gray (owner-approved B2 direction, 2026-10-16). Because the panel is translucent, every neutral — text, outlines, hairlines, tiles, the glass wells, the liquid and neutral ring arcs — is Cindy's warm black `#26221C` (Light) or warm white `#F2EFE9` (Dark) at an opacity, never a fixed gray, so its contrast tracks whatever shows through instead of drifting (owner decision, 2026-10-16): primary text 92% / 94%, secondary 60% / 62%, tertiary 42% / 42%, outlines 14% / 13%, hairlines 8% / 7%, faint fills and ring tracks 5% / 5%; tiles are white 45% / warm white 5%; wells white 70%→50% / warm white 7%→2.5%. Solid colors are reserved for state (warning, error), brand (logo red), Agent/harness identity (including the Codex blue and Claude orange detail rings, kept by owner decision 2026-10-16) and the primary pill fill (`#1F1E1C` / `#F2EFE9`), which must read at full contrast. Native SwiftUI controls (segmented `Picker`, `Toggle`, Swift Charts) are used as-is; their system geometry is not restyled to Web tokens. A segmented control is used only where its labels fit in every language (see below).- The menu bar icon uses a fixed Light/Dark image pair with template tinting disabled (owner-approved hair and earring refinement, 2026-10-18). Its silhouette stays flat and 100% opaque: pure black in Light, pure white in Dark. Four irregular, tapered hair strands add gray detail over that silhouette (`#BDBDBD` in Light / `#686868` in Dark, at 58%, 48%, 36% and 52%); these are tonal overlays, not transparent cutouts or whole-character shading. The `>` earring cutout is larger and shifted slightly left. The native status button's effective appearance selects the image, since the wallpaper can make the menu bar differ from the app; the settings preview uses the same pair. These fixed grays belong only to this native brand asset. Provider/harness logos remain template images (monochrome, tinted by the system). Brand red (logo red `#F70121`) appears only in the Cindy wordmark, a fixed Light/Dark image pair, and in the logo's `>` mark that leads the footer "Open Cindy" pill (owner request, 2026-10-16); it is never used for state.diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex fe47ba61a8..357e88ee80 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -1216,6 +1216,8 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘- 系统通知(完成 / 出错 / 待回复)只由任务侧栏一处发出,`/bots` 路由同样由它观察;正在看的伙伴会话按「注视中」处理,不记未读、不发通知(`useViewedBotSessionId`)。群专线仍不通知。- 伙伴未读按**有未读的对话数**聚合可见、未归档的伙伴私聊与群聊;私聊行仍显示原有的回复条数,群聊行标记该群未读。生成状态、工具过程、内部私信回执和静默巡检不新增未读。收起成头像时以头像角点提示未读,rail 伙伴图标显示聚合数。- 桌面 Dock 的完整投影为本机待关注任务数 + 本机未读伙伴对话数。远程伙伴可以出现在伙伴段,但不扩大本机 Dock 范围;目录加载前的通知事件兜底仍由既有 appBadgeService 管理,目录覆盖的伙伴底层 Session ID 用于去重。+- macOS 菜单栏 Cindy 图标后显示与灵动岛相同的待关注数字(包含未读伙伴,不包含仅运行中的任务),为零时隐藏。已选择额度或用量文字时,数字排在这些文字之前;关闭灵动岛不关闭菜单栏计数。读完、隐藏或切换账号时及时更新,不等待用量采集。+- macOS 灵动岛的伙伴私聊未读复用伙伴列表读位:重启后恢复,超过普通活动卡片的 4 小时期限仍显示;远程伙伴离线时保留已有未读,隐藏、归档或移出账号可见范围后移除。聊天未读与运行活动按主聊天 Session 合成一行,运行、待回复和错误仍取运行时状态;聊天读完不清除独立的错误或待回复。滑动标为已读推进这台电脑上该伙伴的读位至卡片对应消息时间,远程伙伴也不要求主力电脑在线。恢复未读只补显示,不重放完成通知、声音或活动中继。实现见 `useCompanionIslandChats.ts` 与 `agent-island/state.ts`,读位沿用下述设备本地语义。- 分区切换和列表刷新不是已读。只有对应对话前台可见、读到尾部并完成内容同步后,读位才推进到实际显示的回复时间;加载历史、后台窗口、生成过程、失败的远程恢复均不按当前时间清零。普通任务原有已读同步保持不变。- 伙伴读位复用设备本地、账号隔离的持久存储;同机窗口通过 storage 事件更新。它不是跨设备已读协议,手机读过不会清除桌面伙伴角标。群聊复用同样的读位机制,旧工作端缺少回复时间字段时不凭空推断未读。首次建立读位不追溯已有历史,之后列表刷新不重置读位。- 手机的伙伴未读显示在任务首页伙伴段的行与收起头像角点上,不另造菜单键提示点或返回按钮。首页聚焦时任务镜像按现有连接恢复链路同步全部可用电脑;任务列表本身的筛选、消息存储和运行行为不变。离线保留已有镜像,重连后重取;解除绑定或删除条目后不再聚合。