Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(menubar): 支持未读、进行中和今日用量切换 (#7292)
Dashec576b590b30
diff --git a/apps/desktop/native/menubar/macos-menubar-helper.swift b/apps/desktop/native/menubar/macos-menubar-helper.swiftindex f133322f49..73aac9dcf8 100644--- a/apps/desktop/native/menubar/macos-menubar-helper.swift+++ b/apps/desktop/native/menubar/macos-menubar-helper.swift@@ -106,6 +106,20 @@ struct MBModelUsage: Decodable, Equatable {let tokens: Double}+struct MBActivity: Decodable, Identifiable, Equatable {+ var id: String { sessionId }+ let sessionId: String+ let title: String+ let logoSvg: String+ let companion: Bool+ let attention: Bool+ let phase: String+ let preview: String+ let status: String+ let startedAtMs: Double?+ let lastActivityAtMs: Double+}+struct MBDaily: Decodable, Equatable {let money: [Double]let paid: Double@@ -138,6 +152,7 @@ struct MBView: Decodable, Equatable {let strings: [String: String]let statusTextByMode: [String: String?]let attentionCount: Int?+ let activities: [MBActivity]?let remotelyControlled: Bool?let remoteControllerNames: [String]?let updatedAtMs: Double?@@ -535,6 +550,10 @@ enum UsageList: String {case tasks}+enum TaskTab: String, CaseIterable {+ case unread, ongoing, usage+}+@MainActorfinal class MenubarStore: ObservableObject {@Published var view: MBView?@@ -544,6 +563,10 @@ final class MenubarStore: ObservableObject {@Published var refreshing = false@Published var usageRange = 30@Published var usageList: UsageList = .models+ @Published var taskTab: TaskTab = .ongoing+ @Published var tasksExpanded = false+ /// Manual non-unread choice survives panel closes; automatic unread selection never overwrites it.+ private var preferredTaskTab: TaskTab?/// Manage list order while the user drags, before main echoes the saved settings back.@Published var draftOrder: [String]?@Published var mainContentHeight: CGFloat = 0@@ -581,6 +604,19 @@ final class MenubarStore: ObservableObject {var locale: String { view?.locale ?? "en" }+ func openTaskTab() {+ tasksExpanded = false+ if (view?.attentionCount ?? 0) > 0 { taskTab = .unread }+ else if let preferredTaskTab { taskTab = preferredTaskTab }+ else { taskTab = (view?.activities ?? []).contains { $0.phase == "running" || $0.phase == "needs-interaction" } ? .ongoing : .usage }+ }++ func selectTaskTab(_ tab: TaskTab) {+ taskTab = tab+ tasksExpanded = false+ if tab != .unread { preferredTaskTab = tab }+ }+func apply(_ next: MBView) {Fmt.symbol = next.moneySymbolview = next@@ -867,6 +903,7 @@ final class StatusController: NSObject, NSWindowDelegate {let short = forceShort || (screen.map { $0.visibleFrame.height < Self.shortScreenHeight } ?? false)if store.short != short { store.short = short }store.page = .main+ store.openTaskTab()store.fillToken += 1layoutPanel(for: .main, animated: false)let target = panel.frame@@ -1864,13 +1901,8 @@ struct MainPage: View {.padding(.top, measured.isEmpty ? 12 : 4)}- Caption(title: store.s("tasks"), detail: view.taskSummary) {- TaskTotal(tasks: view.tasks, tokenUnit: store.s("tokenUnit"), showsTokens: store.narrowWidth >= 350, replayToken: store.fillToken)- }- .padding(EdgeInsets(top: store.short ? 14 : 18, leading: 20, bottom: 6, trailing: 20))-- TaskList(store: store, tasks: view.tasks, controller: controller)- .padding(.horizontal, 10)+ TaskOverview(store: store, view: view, controller: controller)+ .padding(.top, store.short ? 12 : 16)MonthCard(store: store, view: view).padding(EdgeInsets(top: 8, leading: 12, bottom: 12, trailing: 12))@@ -2357,6 +2389,151 @@ struct CellPressStyle: ButtonStyle {// MARK: - Tasks+struct TaskOverview: View {+ @ObservedObject var store: MenubarStore+ let view: MBView+ let controller: StatusController++ private var activities: [MBActivity] { view.activities ?? [] }+ private var ongoing: [MBActivity] { activities.filter { $0.phase == "running" || $0.phase == "needs-interaction" } }+ private var unread: [MBActivity] { activities.filter(\.attention) }++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack(spacing: 16) {+ taskTab(.unread, title: store.s("tabUnread"), count: unread.count)+ taskTab(.ongoing, title: store.s("tabOngoing"), count: ongoing.count)+ taskTab(.usage, title: store.s("tabUsage"))+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 20)++ if store.taskTab == .usage {+ Caption(title: store.s("tasks"), detail: view.taskSummary) {+ TaskTotal(tasks: view.tasks, tokenUnit: store.s("tokenUnit"), showsTokens: store.narrowWidth >= 350, replayToken: store.fillToken)+ }+ .padding(.horizontal, 20)+ TaskList(store: store, tasks: view.tasks, controller: controller)+ .padding(.horizontal, 10)+ } else {+ let rows = store.taskTab == .unread ? unread : ongoing+ let limit = store.short ? 2 : 3+ let shown = store.tasksExpanded ? rows : Array(rows.prefix(limit))+ VStack(spacing: 0) {+ if rows.isEmpty {+ Text(store.s(store.taskTab == .unread ? "noUnread" : "noOngoing"))+ .font(.system(size: 12))+ .foregroundStyle(Palette.ink3)+ .padding(.vertical, 16)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 10)+ }+ ForEach(shown) { row in+ ActivityRow(store: store, activity: row) {+ controller.emitAndClose(["type": "open-session", "sessionId": row.sessionId])+ }+ }+ if rows.count > limit {+ MoreRow(label: store.s(store.tasksExpanded ? "collapseTasks" : "allTasks"), value: String(rows.count)) {+ store.tasksExpanded.toggle()+ }+ .padding(.horizontal, 10)+ }+ }+ .padding(.horizontal, 10)+ }+ }+ }++ private func taskTab(_ tab: TaskTab, title: String, count: Int = 0) -> some View {+ let selected = store.taskTab == tab+ return Button { store.selectTaskTab(tab) } label: {+ HStack(spacing: 4) {+ Text(title)+ .foregroundStyle(selected ? Palette.ink : Palette.ink3)+ if count > 0 {+ Text(String(count))+ .foregroundStyle(Palette.ink3)+ .monospacedDigit()+ }+ }+ .font(.system(size: 12, weight: .medium))+ .lineLimit(1)+ .fixedSize()+ .frame(minHeight: 28)+ .overlay(alignment: .bottomLeading) {+ Capsule().fill(selected ? Palette.ink2 : .clear).frame(width: 12, height: 1.5)+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(selected ? .isSelected : [])+ }+}++struct ActivityRow: View {+ @ObservedObject var store: MenubarStore+ let activity: MBActivity+ let action: () -> Void+ @State private var hovering = false++ var body: some View {+ Button(action: action) {+ HStack(spacing: 10) {+ if activity.companion {+ Image(systemName: "bubble.left.and.bubble.right")+ .font(.system(size: 15))+ .foregroundStyle(Palette.ink2)+ .frame(width: 28, height: 28)+ } else {+ TaskIcon(svg: activity.logoSvg, running: activity.phase == "running")+ }+ VStack(alignment: .leading, spacing: 3) {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ Text(activity.title)+ .font(.system(size: 12.5, weight: .semibold))+ .foregroundStyle(Palette.ink)+ .lineLimit(1)+ .frame(maxWidth: .infinity, alignment: .leading)+ TimelineView(.periodic(from: .now, by: activity.phase == "running" ? 1 : 60)) { context in+ Text(timeLabel(now: context.date))+ .font(.system(size: 10.5))+ .foregroundStyle(Palette.ink3)+ .monospacedDigit()+ }+ .fixedSize()+ }+ Text(activity.phase == "needs-interaction" || activity.phase == "error"+ ? (activity.preview == activity.status ? activity.status : activity.status + " · " + activity.preview)+ : activity.preview)+ .font(.system(size: 11.5))+ .foregroundStyle(Palette.ink2)+ .lineLimit(2)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 8)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(hovering ? Palette.ink5 : .clear))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .onHover { hovering = $0 }+ .help(activity.title + "\n" + activity.status + "\n" + activity.preview)+ }++ private func timeLabel(now: Date) -> String {+ if activity.phase == "running", let started = activity.startedAtMs {+ return Fmt.clock(max(0, now.timeIntervalSince1970 - started / 1000))+ }+ let minutes = max(0, Int((now.timeIntervalSince1970 - activity.lastActivityAtMs / 1000) / 60))+ if minutes < 1 { return store.s("activityNow") }+ if minutes < 60 { return store.s("activityMinutes", ["n": String(minutes)]) }+ if minutes < 1440 { return store.s("activityHours", ["n": String(minutes / 60)]) }+ return store.s("activityDays", ["n": String(minutes / 1440)])+ }+}+struct TaskTotal: View {let tasks: [MBTask]let tokenUnit: Stringdiff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.tsindex 1fe26e22f0..45e05bc188 100644--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts@@ -15,6 +15,7 @@ import {AGENT_ISLAND_MESSAGE_PREVIEW_MIN_DWELL_MS,AGENT_ISLAND_UNREAD_TRANSIENT_TTL_MS,buildAgentIslandDisplayState,+ buildAgentIslandTaskOverview,buildAllSessionActivitySnapshots,closeAgentIslandSessionPreservingUnread,completedReplySummary,@@ -44,6 +45,19 @@ describe('companion chat unread projection', () => {lastMessageAt: 1, preview: 'Reply waiting to be read', token: 'chat-token',companion: { name: 'Cindy', hue: 'blue', glyph: 'C', glyphIsInitial: true },};+ // Unit: a blocking card clips the island surface but must not clip the menu's badge candidates.+ it('keeps the full counted overview while an interaction card occupies the island', () => {+ const state = createAgentIslandState();+ applyAgentIslandUserPrompt(state, { sessionId: 'waiting' }, 'question', 100);+ applyAgentIslandInteractionRequest(state, { sessionId: 'waiting' }, { kind: 'ask_user_question', requestId: 'q', questions: [] }, 101);+ applyAgentIslandUserPrompt(state, { sessionId: 'working' }, 'work', 102);+ const display = buildAgentIslandDisplayState(state, 103, [chat]);+ const overview = buildAgentIslandTaskOverview(state, 103, [chat]);+ expect(overview.map(row => row.sessionId).sort()).toEqual(['companion-chat', 'waiting', 'working']);+ expect(overview.filter(row => row.attention)).toHaveLength(display.pillSnapshot.attentionCount);+ expect(overview.find(row => row.sessionId === chat.sessionId)).toMatchObject({ companion: { name: 'Cindy' }, attention: true });+ expect(buildAgentIslandTaskOverview(state, 104, [{ ...chat, unread: false }]).some(row => row.sessionId === chat.sessionId)).toBe(false);+ });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;diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex 40e2545ef6..287dd3194e 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -105,6 +105,7 @@ import {applyAgentIslandInteractionRequest,applyAgentIslandUserPrompt,buildAgentIslandDisplayState,+ buildAgentIslandTaskOverview,buildAllSessionActivitySnapshots,closeAgentIslandSessionPreservingUnread,completeAgentIslandSessionWithoutAttention,@@ -343,6 +344,7 @@ function canonicalSessionActivity(export class AgentIslandService {private attentionCount = 0;private readonly attentionCountListeners = new Set<(count: number) => void>();+ private readonly taskOverviewListeners = new Set<() => void>();private readonly sessionActivityListeners = new Set<(transition: SessionActivityTransition) => void>();@@ -1897,12 +1899,32 @@ export class AgentIslandService {return this.attentionCount;}+ getTaskOverview(): AgentIslandSessionSnapshot[] {+ return buildAgentIslandTaskOverview(this.state, Date.now(), this.companionChatProjections());+ }++ subscribeTaskOverview(listener: () => void): () => void {+ this.taskOverviewListeners.add(listener);+ return () => this.taskOverviewListeners.delete(listener);+ }++ /** Menu-bar entry uses the same device/companion navigation and read acknowledgement. */+ openTaskOverviewSession(sessionId: string): void {+ this.focusSession(sessionId);+ }+subscribeAttentionCount(listener: (count: number) => void): () => void {this.attentionCountListeners.add(listener);return () => this.attentionCountListeners.delete(listener);}private publishAttentionCount(count: number): void {+ // Content can change without changing the count (including restored companion chats).+ for (const listener of this.taskOverviewListeners) {+ try { listener(); } catch (error) {+ log.warn('task overview listener failed', { error: error instanceof Error ? error.message : String(error) });+ }+ }if (count === this.attentionCount) return;this.attentionCount = count;for (const listener of this.attentionCountListeners) {diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.tsindex 575425abcc..e8de73e74f 100644--- a/apps/desktop/src/main/agent-island/state.ts+++ b/apps/desktop/src/main/agent-island/state.ts@@ -1536,14 +1536,7 @@ export function buildAgentIslandDisplayState(&& (state.isMouseInExpandedPanel || isCollapsePending(state, now)));promoteNextTransientReveal(state, now, manualExpanded);- const sortedSessions = projectCompanionChats(state, companionChats)- .filter((session) => shouldDisplaySession(- state,- session,- now,- isPointerInsideIsland(state) || state.hoverExpanded || isCollapsePending(state, now),- ))- .sort((a, b) => compareSessionsForDisplay(state, a, b, now));+ const sortedSessions = visibleOverviewSessions(state, now, companionChats);const activeTransient = getActiveTransientSession(state, now);const orderedSessions = orderSessionsForCurrentSurface(state,@@ -1597,6 +1590,28 @@ export interface AgentIslandCompanionChatProjection {token: string;}+/** The same candidates counted by the pill, before its current-card/list clipping. */+export function buildAgentIslandTaskOverview(+ state: AgentIslandState,+ now: number,+ companionChats: readonly AgentIslandCompanionChatProjection[] = [],+): AgentIslandSessionSnapshot[] {+ return visibleOverviewSessions(state, now, companionChats).map(toSnapshot);+}++function visibleOverviewSessions(+ state: AgentIslandState,+ now: number,+ companionChats: readonly AgentIslandCompanionChatProjection[],+): AgentIslandSessionState[] {+ return projectCompanionChats(state, companionChats)+ .filter((session) => shouldDisplaySession(+ state, session, now,+ isPointerInsideIsland(state) || state.hoverExpanded || isCollapsePending(state, now),+ ))+ .sort((a, b) => compareSessionsForDisplay(state, a, b, now));+}+/** 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.*/diff --git a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.tsindex eb9959d6de..77cad0dce7 100644--- a/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts+++ b/apps/desktop/src/main/menubar/__tests__/quotaInvalidation.test.ts@@ -2,18 +2,21 @@ 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';+import type { AgentIslandSessionSnapshot } from '../../../shared/agentIsland';const mocks = vi.hoisted(() => ({app: { isPackaged: true },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(),+ activities: [] as AgentIslandSessionSnapshot[], attentionListeners: new Set<() => void>(), publish: vi.fn(),+ openOverviewSession: vi.fn(), openLocalSession: vi.fn(),openRemoteSettings: vi.fn(), onHelperMessage: null as null | ((message: MenubarHelperMessage) => void),}));vi.mock('electron', () => ({ app: mocks.app, Notification: class {} }));vi.mock('../../agent-island/service.js', () => ({ getAgentIslandService: () => ({- getAttentionCount: () => mocks.attentionCount,- subscribeAttentionCount: (listener: (count: number) => void) => {+ getTaskOverview: () => mocks.activities,+ openTaskOverviewSession: mocks.openOverviewSession,+ subscribeTaskOverview: (listener: () => void) => {mocks.attentionListeners.add(listener);return () => mocks.attentionListeners.delete(listener);},@@ -24,7 +27,7 @@ vi.mock('../../appSessionState.js', () => ({ getActiveAppSession: () => ({ dataOvi.mock('../../authManager.js', () => ({ getAuthState: () => mocks.auth, onAuthStateChange: () => () => {} }));vi.mock('../../billing/projection.js', () => ({}));vi.mock('../../clientEndpointsService.js', () => ({}));-vi.mock('../../deepLink.js', () => ({ openMainWindowRemoteControlSettings: mocks.openRemoteSettings }));+vi.mock('../../deepLink.js', () => ({ openMainWindowRemoteControlSettings: mocks.openRemoteSettings, openMainWindowSession: mocks.openLocalSession }));vi.mock('../../device-link/index.js', () => ({}));vi.mock('../../device-link/dispatch.js', () => ({ getActiveControllers: () => subscriptions.getControlControllers() }));vi.mock('../../device-link/ipc.js', () => ({}));@@ -42,7 +45,7 @@ vi.mock('../../usage/claudeAccountUsage.js', () => ({ readClaudeAccountUsageRevivi.mock('../../usage/ledgerCurrency.js', () => ({ currentLedgerCurrency: () => 'USD' }));vi.mock('../../usage/usageHistory.js', () => ({}));vi.mock('../../usageBroadcaster.js', () => ({ observeUsageChanges: () => () => {} }));-vi.mock('../settingsStore.js', () => ({ readMenubarSettings: () => ({ ...DEFAULT_MENUBAR_SETTINGS }), writeMenubarSettings: (value: unknown) => value }));+vi.mock('../settingsStore.js', () => ({ readMenubarSettings: () => ({ ...DEFAULT_MENUBAR_SETTINGS }), writeMenubarSettings: (value: object) => ({ ...DEFAULT_MENUBAR_SETTINGS, ...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); }@@ -53,7 +56,8 @@ import { MenubarService } from '../service';beforeEach(() => {mocks.app.isPackaged = true;vi.useFakeTimers(); mocks.revision = 0; mocks.listeners.clear(); mocks.refresh.mockReset(); mocks.collect.mockReset();- mocks.attentionCount = 0; mocks.attentionListeners.clear(); mocks.publish.mockReset();+ mocks.activities = []; mocks.attentionListeners.clear(); mocks.publish.mockReset();+ mocks.openOverviewSession.mockReset(); mocks.openLocalSession.mockReset();mocks.openRemoteSettings.mockReset(); mocks.onHelperMessage = null;subscriptions.__testing.reset();mocks.quota = { spend: 2, maxBudget: 10, currency: 'CNY', fetchedAt: Date.now(), todaySpend: null };@@ -64,7 +68,7 @@ afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });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;+ mocks.activities = [activity('one'), activity('two')];subscriptions.subscribe('phone', ['session:chat']);mocks.collect.mockResolvedValue(collected);service.init();@@ -74,8 +78,8 @@ it('updates the native count immediately while a usage rebuild is still pending'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);+ mocks.activities = [];+ for (const listener of mocks.attentionListeners) listener();subscriptions.clearAll();service.refreshControlState();expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ attentionCount: 0, remotelyControlled: false }));@@ -86,6 +90,51 @@ it('updates the native count immediately while a usage rebuild is still pending'expect(mocks.attentionListeners.size).toBe(0);});+function activity(sessionId: string): AgentIslandSessionSnapshot {+ return {+ sessionId, title: sessionId, projectName: null, detail: 'Latest reply', compactDetail: 'Latest reply',+ messagePreview: { id: 'reply', kind: 'assistant', text: 'Latest reply' }, phase: 'completed',+ agentKind: 'codex', permissionAction: null, attention: true, activityLines: [], startedAt: 1, lastActivityAt: 2,+ };+}++// Unit: the old count-only subscription misses content changes and cannot route remote companions.+it('updates same-count unread content immediately and opens through the island handoff', async () => {+ const service = new MenubarService({ openNewTask() {} });+ mocks.activities = [activity('remote-companion')];+ mocks.collect.mockResolvedValue(emptyMenubarInputs(Date.now(), 'Fixture'));+ service.init();+ await vi.advanceTimersByTimeAsync(0);+ mocks.activities = [{ ...activity('remote-companion'), messagePreview: { id: 'new', kind: 'assistant', text: 'New reply' } }];+ for (const listener of mocks.attentionListeners) listener();+ expect(mocks.publish).toHaveBeenLastCalledWith(expect.objectContaining({ attentionCount: 1,+ activities: [expect.objectContaining({ sessionId: 'remote-companion', preview: 'New reply' })],+ }));+ expect(mocks.activities[0]?.attention).toBe(true);+ mocks.onHelperMessage?.({ type: 'open-session', sessionId: 'remote-companion' });+ expect(mocks.openOverviewSession).toHaveBeenCalledWith('remote-companion');+ expect(mocks.openLocalSession).not.toHaveBeenCalled();+ mocks.onHelperMessage?.({ type: 'open-session', sessionId: 'usage-only' });+ expect(mocks.openLocalSession).toHaveBeenCalledWith('usage-only');+ service.stop();+});++// Unit: privacy applies to live message previews as well as the older usage list.+it('masks companion names and message bodies in privacy mode', async () => {+ const service = new MenubarService({ openNewTask() {} });+ mocks.activities = [{ ...activity('companion'), companion: { name: 'Private name', hue: 'blue', glyph: 'P', glyphIsInitial: true } }];+ mocks.collect.mockResolvedValue(emptyMenubarInputs(Date.now(), 'Fixture'));+ service.init();+ await vi.advanceTimersByTimeAsync(0);+ mocks.onHelperMessage?.({ type: 'settings', patch: { privacy: true } });+ await vi.advanceTimersByTimeAsync(0);+ const view = mocks.publish.mock.calls.at(-1)?.[0];+ expect(view.activities[0]).toMatchObject({ title: 'menubar.ui.privateCompanion', preview: 'menubar.ui.activityCompleted' });+ expect(JSON.stringify(view)).not.toContain('Private name');+ expect(JSON.stringify(view)).not.toContain('Latest reply');+ service.stop();+});+// Unit regression: dev builds forced the native indicator on with no controllers.// Existing coverage only used packaged builds; exercise the published state in both modes.it.each([true, false])('lights only for active controllers and clears on exit (packaged=%s)', async (isPackaged) => {diff --git a/apps/desktop/src/main/menubar/activity.ts b/apps/desktop/src/main/menubar/activity.tsnew file mode 100644index 0000000000..5b220f3570--- /dev/null+++ b/apps/desktop/src/main/menubar/activity.ts@@ -0,0 +1,59 @@+import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';+import type { AgentIslandSessionSnapshot } from '../../shared/agentIsland.js';+import type { MenubarActivity } from '../../shared/menubarQuota.js';+import { MENUBAR_HARNESS_LOGOS } from './logos.js';+import type { MenubarTranslate } from './snapshot.js';++/** Keep the island's exact candidate/attention semantics; only adapt presentation. */+export function buildMenubarActivities(+ sessions: readonly AgentIslandSessionSnapshot[],+ privacy: boolean,+ t: MenubarTranslate,+): MenubarActivity[] {+ return sessions+ .map((session): MenubarActivity => {+ const companion = session.companion;+ const harness =+ session.agentKind === 'codex' ? 'codex' : session.agentKind === 'pi' ? 'pi' : 'claude-code';+ const status = t(+ `ui.activity${+ {+ running: 'Running',+ 'needs-interaction': 'Waiting',+ completed: 'Completed',+ error: 'Error',+ }[session.phase]+ }`,+ );+ return {+ sessionId: session.sessionId,+ title: privacy+ ? t(companion ? 'ui.privateCompanion' : 'tasks.private', {+ harness: t(`harness.${harness}`),+ })+ : companion+ ? [companion.groupName, companion.name].filter(Boolean).join(' · ')+ : isDefaultDraftSessionTitle(session.title) || !session.title.trim()+ ? t('ui.untitledTask')+ : session.title,+ logoSvg: MENUBAR_HARNESS_LOGOS[harness],+ companion: !!companion,+ attention: session.attention,+ phase: session.phase,+ preview: privacy+ ? status+ : (session.messagePreview?.text || session.compactDetail || session.detail || status)+ .replace(/\s+/g, ' ')+ .slice(0, 240),+ status,+ startedAtMs: session.phase === 'running' ? session.startedAt : null,+ lastActivityAtMs: session.lastActivityAt,+ };+ })+ .sort(+ (a, b) =>+ Number(b.phase === 'needs-interaction') - Number(a.phase === 'needs-interaction') ||+ b.lastActivityAtMs - a.lastActivityAtMs ||+ a.sessionId.localeCompare(b.sessionId),+ );+}diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.tsindex 8ba161ecd8..2aebc8445b 100644--- a/apps/desktop/src/main/menubar/service.ts+++ b/apps/desktop/src/main/menubar/service.ts@@ -87,6 +87,7 @@ import {type MenubarSubscriptionInput,} from './snapshot.js';import { buildMenubarUiStrings, createMenubarTranslate } from './strings.js';+import { buildMenubarActivities } from './activity.js';const log = createLogger('menubar');@@ -253,7 +254,7 @@ export class MenubarService {const island = getAgentIslandService();if (island) {this.disposers.push(- island.subscribeAttentionCount((count) => this.publishAttentionCount(count)),+ island.subscribeTaskOverview(() => this.publishTaskOverview()),island.subscribeSessionActivity(({ previous, current }) => {const wasRunning = previous ? isSessionActivityRunning(previous) : false;const isRunning = current ? isSessionActivityRunning(current) : false;@@ -477,7 +478,7 @@ export class MenubarService {...(gate ? { gate } : {}),};const view = buildMenubarView(input);- view.attentionCount = gate ? 0 : (getAgentIslandService()?.getAttentionCount() ?? 0);+ Object.assign(view, this.taskOverview(gate));Object.assign(view, this.controlState(gate));this.lastView = view;this.host.publish(view);@@ -490,10 +491,20 @@ export class MenubarService {}/** 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 };+ private taskOverview(gate?: MenubarGate): Pick<MenubarView, 'activities' | 'attentionCount'> {+ const locale = getResolvedMainLocale();+ const activities = gate ? [] : buildMenubarActivities(+ getAgentIslandService()?.getTaskOverview() ?? [], this.settings.privacy,+ createMenubarTranslate(locale, key => rawMainString(key, locale)),+ );+ return { activities, attentionCount: activities.filter(row => row.attention).length };+ }++ private publishTaskOverview(): void {+ if (!this.started || !this.lastView || this.lastView.gate || isAppSessionBoundaryPending() || !hasDataOwner()) return;+ const overview = this.taskOverview();+ if (JSON.stringify(this.lastView.activities) === JSON.stringify(overview.activities)) return;+ this.lastView = { ...this.lastView, ...overview };this.host.publish(this.lastView);}@@ -660,7 +671,11 @@ export class MenubarService {this.showMainWindow();return;case 'open-session':- openMainWindowSession(message.sessionId);+ if (this.lastView?.activities?.some(row => row.sessionId === message.sessionId)) {+ getAgentIslandService()?.openTaskOverviewSession(message.sessionId);+ } else {+ openMainWindowSession(message.sessionId);+ }return;case 'detail-action':void this.runDetailAction(message.sourceId);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3d418deb1f..6f4ac8195e 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1422,6 +1422,23 @@"tasks": "Tasks","tokenUnit": "tokens","noTasksToday": "No tasks yet today",+ "tabUnread": "Unread",+ "tabOngoing": "In progress",+ "tabUsage": "Today’s usage",+ "noUnread": "All caught up",+ "noOngoing": "No tasks in progress",+ "allTasks": "All tasks",+ "collapseTasks": "Collapse",+ "activityRunning": "Running",+ "activityWaiting": "Needs your input",+ "activityCompleted": "Completed",+ "activityError": "Needs attention",+ "privateCompanion": "Companion message",+ "untitledTask": "Untitled task",+ "activityNow": "Just now",+ "activityMinutes": "{{n}}m ago",+ "activityHours": "{{n}}h ago",+ "activityDays": "{{n}}d ago","moreTasks_one": "{{n}} more task","moreTasks_other": "{{n}} more tasks","running": "Running",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex bcb925a28d..41af7b4c70 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1396,6 +1396,23 @@"tasks": "タスク","tokenUnit": "token","noTasksToday": "今日のタスクはまだありません",+ "tabUnread": "未読",+ "tabOngoing": "進行中",+ "tabUsage": "今日の使用量",+ "noUnread": "すべて既読です",+ "noOngoing": "進行中のタスクはありません",+ "allTasks": "すべてのタスク",+ "collapseTasks": "折りたたむ",+ "activityRunning": "実行中",+ "activityWaiting": "確認待ち",+ "activityCompleted": "完了",+ "activityError": "対応が必要",+ "privateCompanion": "仲間のメッセージ",+ "untitledTask": "無題のタスク",+ "activityNow": "たった今",+ "activityMinutes": "{{n}}分前",+ "activityHours": "{{n}}時間前",+ "activityDays": "{{n}}日前","moreTasks_other": "ほか {{n}} 件のタスク","running": "実行中","openApp": "Cindy を開く",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 134c49f2f1..7c4131e54f 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1396,6 +1396,23 @@"tasks": "작업","tokenUnit": "token","noTasksToday": "오늘은 아직 작업이 없어요",+ "tabUnread": "읽지 않음",+ "tabOngoing": "진행 중",+ "tabUsage": "오늘 사용량",+ "noUnread": "모두 읽었어요",+ "noOngoing": "진행 중인 작업이 없어요",+ "allTasks": "모든 작업",+ "collapseTasks": "접기",+ "activityRunning": "실행 중",+ "activityWaiting": "확인 대기",+ "activityCompleted": "완료",+ "activityError": "확인 필요",+ "privateCompanion": "동료 메시지",+ "untitledTask": "제목 없는 작업",+ "activityNow": "방금",+ "activityMinutes": "{{n}}분 전",+ "activityHours": "{{n}}시간 전",+ "activityDays": "{{n}}일 전","moreTasks_other": "작업 {{n}}개 더","running": "진행 중","openApp": "Cindy 열기",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1ad413a557..6dfdc22f2b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1396,6 +1396,23 @@"tasks": "任务","tokenUnit": "token","noTasksToday": "今天还没有任务",+ "tabUnread": "未读",+ "tabOngoing": "进行中",+ "tabUsage": "今日用量",+ "noUnread": "已全部读完",+ "noOngoing": "当前没有进行中的任务",+ "allTasks": "全部任务",+ "collapseTasks": "收起",+ "activityRunning": "运行中",+ "activityWaiting": "等你确认",+ "activityCompleted": "已完成",+ "activityError": "需要处理",+ "privateCompanion": "伙伴消息",+ "untitledTask": "未命名任务",+ "activityNow": "刚刚",+ "activityMinutes": "{{n}} 分钟前",+ "activityHours": "{{n}} 小时前",+ "activityDays": "{{n}} 天前","moreTasks_other": "另外 {{n}} 个任务","running": "运行中","openApp": "打开 Cindy",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 249ca19d9d..73496970c5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1396,6 +1396,23 @@"tasks": "任務","tokenUnit": "token","noTasksToday": "今天還沒有任務",+ "tabUnread": "未讀",+ "tabOngoing": "進行中",+ "tabUsage": "今日用量",+ "noUnread": "已全部讀完",+ "noOngoing": "目前沒有進行中的任務",+ "allTasks": "全部任務",+ "collapseTasks": "收起",+ "activityRunning": "執行中",+ "activityWaiting": "等你確認",+ "activityCompleted": "已完成",+ "activityError": "需要處理",+ "privateCompanion": "夥伴訊息",+ "untitledTask": "未命名任務",+ "activityNow": "剛剛",+ "activityMinutes": "{{n}} 分鐘前",+ "activityHours": "{{n}} 小時前",+ "activityDays": "{{n}} 天前","moreTasks_other": "另外 {{n}} 個任務","running": "執行中","openApp": "打開 Cindy",diff --git a/apps/desktop/src/shared/menubarQuota.ts b/apps/desktop/src/shared/menubarQuota.tsindex 4a2f59de4e..3bde0b298c 100644--- a/apps/desktop/src/shared/menubarQuota.ts+++ b/apps/desktop/src/shared/menubarQuota.ts@@ -147,6 +147,20 @@ export interface MenubarModelUsage {tokens: number;}+/** Live task/companion projection, independent of today's local usage ranking. */+export interface MenubarActivity {+ sessionId: string;+ title: string;+ logoSvg: string;+ companion: boolean;+ attention: boolean;+ phase: 'running' | 'needs-interaction' | 'completed' | 'error';+ preview: string;+ status: string;+ startedAtMs: number | null;+ lastActivityAtMs: number;+}+export interface MenubarUsageScopeData {/** One entry per day, oldest first, aligned with `MenubarUsage.days`. */daily: {@@ -191,6 +205,7 @@ export interface MenubarView {statusTextByMode: Record<MenubarStatusTextMode, string | null>;/** Same attention count as Agent Island, shown before the optional usage text. */attentionCount?: number;+ activities?: MenubarActivity[];/** 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. */diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 629ad7707b..13254d1cb9 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -622,6 +622,8 @@ Icon refinement reference (2026-10-18, macOS AppKit rendering; enlarged and actu- Size and density (owner request, 2026-10-12: lighter on small laptops, verified in every language): every page is 320–368pt wide by tube count, with a 20pt panel radius and 14pt tile radius. The panel never takes more than 86% of the screen's visible height; longer content scrolls between the fixed header and footer. When the visible height is under 1000pt (13–14" laptops at default scaling), the panel opens in a short layout: 82pt tubes instead of 104pt, 160pt rings instead of 188pt, and two task rows instead of three.- The usage page (owner-approved redesign, 2026-10-12) shares the panel width and slides in like a detail page instead of widening into a dashboard. Top to bottom it shows: back, title and a 7/30/90-day switch; one total with two caption lines (period, scope and value basis; daily average, paid and tokens); a 100pt stacked chart labeled only with its first day and Today, where hovering a day swaps the total for that day's amount and harness split; a thin harness bar with share and amount per harness; the top five models or today's tasks; and the value note. There is no amount/tokens switch and no scope switch: the scope follows Settings, and the caption names it.- Every row must fit in the longest supported language. A segmented control is used only where all its labels fit on one row in every language. The four menu bar text options are a two-column chip grid. Other controls fall back instead of overflowing: the usage-scope picker moves under its title. Screenshots for review cover English, Simplified and Traditional Chinese, Japanese and Korean, in Light and Dark.+- Keep the main panel's original order: model quota first, tasks second, then the usage chart (owner correction, 2026-10-26). The task section uses three quiet text tabs: Unread, In progress and Today's usage. These are deliberately frameless, with no filled segment track; ink emphasis and a short underline identify selection. Each keeps a 28pt hit height and native keyboard/selected accessibility. Opening with attention selects Unread; otherwise it restores the last manually selected non-unread tab for this helper lifetime. Before any manual choice, prefer In progress when work exists, otherwise Today's usage. Updates never switch an already-open panel, including when the last unread item clears. Opening or switching tabs never acknowledges messages.+- Unread and In progress reuse the island's full candidate projection before current-card clipping, including remote tasks and restored companion chats. Unread counts the exact attention candidates; In progress includes running and waiting-for-input tasks. Waiting items come first, then newest activity. Rows show identity, message/status preview and time; privacy mode masks both identity and preview. Clicking uses the island's existing device-aware navigation and read acknowledgement. Two rows on short screens, otherwise three, with an in-place All tasks / Collapse action; usage keeps its existing money ranking and usage-page link.### Desktop chat and operation authorization (DS-9, 2026-09-11)