Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): 点击原收起位置收合灵动岛 (#2908)

Dash822adadf0a2b
diff --git a/apps/desktop/native/agent-island/macos-agent-island-helper.swift b/apps/desktop/native/agent-island/macos-agent-island-helper.swift
index 74d87e6421..e40393476d 100644
--- a/apps/desktop/native/agent-island/macos-agent-island-helper.swift
+++ b/apps/desktop/native/agent-island/macos-agent-island-helper.swift
@@ -1633,6 +1633,8 @@ private let expandedIslandBodySpacing: CGFloat = 4
private let expandedIslandBottomPadding: CGFloat = 16
private let compactIslandBaseWidth: CGFloat = 210
private let compactIslandMinContentWidth: CGFloat = 80
+private let compactCollapseLeadingReservedWidth: CGFloat = 80
+private let compactCollapseTrailingReservedWidth: CGFloat = 100
private let compactIslandBadgeCollapseContentThreshold: CGFloat = 152
private let compactIslandDetailCollapseContentThreshold: CGFloat = 190
private let compactIslandCjkTitleMinimumWidth: CGFloat = 32
@@ -4619,6 +4621,7 @@ final class AgentIslandController {
notchBaselineHeight: 24,
screenMetrics: .fallback
)
+ private var lastCompactIslandWidth: CGFloat?
private var globalClickMonitor: Any?
private var localClickMonitor: Any?
private var globalMoveMonitor: Any?
@@ -4758,7 +4761,7 @@ final class AgentIslandController {
)
return
}
- lastLayout = layout
+ rememberLayout(layout)
if state.mode == "expanded" {
cancelPendingCarrierFrame()
}
@@ -5255,8 +5258,12 @@ final class AgentIslandController {
return
}
pendingMoveInteraction = nil
+ // Collapse is owned here, not by SwiftUI top-bar taps, so the hit stays
+ // inside the original compact footprint instead of the whole spacer.
if shouldTreatAsCompactClick(interaction: interaction, screenPoint: screenPoint) {
eventSink(["type": "expand"])
+ } else if shouldTreatAsCompactCollapseClick(interaction: interaction, screenPoint: screenPoint) {
+ eventSink(["type": "collapse"])
}
handleMouseMoved(screenPoint: screenPoint, force: true)
replayDeferredInteractionUpdateIfNeeded()
@@ -5424,10 +5431,66 @@ final class AgentIslandController {
guard interaction.mode == .move, !interaction.startLayout.expanded else {
return false
}
- return abs(screenPoint.x - interaction.startMouseX) <= agentIslandClickDragTolerance
+ return isClickWithoutDrag(interaction: interaction, screenPoint: screenPoint)
+ }
+
+ private func shouldTreatAsCompactCollapseClick(
+ interaction: PanelDragInteraction,
+ screenPoint: NSPoint
+ ) -> Bool {
+ guard interaction.mode == .move, interaction.startLayout.expanded else {
+ return false
+ }
+ guard isClickWithoutDrag(interaction: interaction, screenPoint: screenPoint) else {
+ return false
+ }
+ return isCompactFootprintClick(interaction: interaction)
+ }
+
+ private func isClickWithoutDrag(interaction: PanelDragInteraction, screenPoint: NSPoint) -> Bool {
+ abs(screenPoint.x - interaction.startMouseX) <= agentIslandClickDragTolerance
&& abs(screenPoint.y - interaction.startMouseY) <= agentIslandClickDragTolerance
}
+ /// The screen rectangle where the collapsed island sat. After expand, that
+ /// center strip is blank (hardware-notch Color.clear, or the top-bar spacer).
+ /// Clicking it should fold the island back; toolbar / title live outside it.
+ private func isCompactFootprintClick(interaction: PanelDragInteraction) -> Bool {
+ let layout = interaction.startLayout
+ let footprintWidth = compactCollapseFootprintWidth(layout: layout)
+ let centerX = interaction.startFrame.midX
+ let clickX = interaction.startMouseX
+ guard clickX >= centerX - footprintWidth / 2 && clickX <= centerX + footprintWidth / 2 else {
+ return false
+ }
+ let visualMinX = centerX - layout.width / 2
+ let visualMaxX = centerX + layout.width / 2
+ let sideChrome = layout.hasHardwareNotch
+ ? max(0, (layout.width - layout.notchWidth) / 2)
+ : 0
+ let leadingReserved = max(compactCollapseLeadingReservedWidth, sideChrome)
+ let trailingReserved = max(compactCollapseTrailingReservedWidth, sideChrome)
+ return clickX > visualMinX + leadingReserved
+ && clickX < visualMaxX - trailingReserved
+ }
+
+ private func compactCollapseFootprintWidth(layout: AgentIslandLayout) -> CGFloat {
+ if let remembered = lastCompactIslandWidth, remembered > 0 {
+ return remembered
+ }
+ if layout.hasHardwareNotch {
+ return max(1, layout.notchWidth)
+ }
+ return compactIslandBaseWidth
+ }
+
+ private func rememberLayout(_ layout: AgentIslandLayout) {
+ lastLayout = layout
+ if !layout.expanded, layout.width > 0 {
+ lastCompactIslandWidth = layout.width
+ }
+ }
+
private func shouldPromotePendingMove(interaction: PanelDragInteraction, screenPoint: NSPoint) -> Bool {
abs(screenPoint.x - interaction.startMouseX) > agentIslandClickDragTolerance
|| abs(screenPoint.y - interaction.startMouseY) > agentIslandClickDragTolerance
@@ -5478,7 +5541,7 @@ final class AgentIslandController {
frame: frame,
expanded: lastLayout.expanded
)
- lastLayout = AgentIslandLayout.compute(
+ rememberLayout(AgentIslandLayout.compute(
state: model.state,
availableFrameWidth: frame.width,
locallyHovered: model.locallyHovered,
@@ -5486,7 +5549,7 @@ final class AgentIslandController {
screenMetrics: model.screenMetrics,
hardwareNotchLayoutEnabled: hardwareNotchLayoutEnabled,
preferredContentWidth: currentContentWidth(frame: frame, layout: lastLayout)
- )
+ ))
let nextContentWidth = currentContentWidth(frame: frame, layout: lastLayout)
if animatedSnap {
beginCompactSnapLayoutAnimation()
diff --git a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
index bdbf568f1c..4f63e52083 100644
--- a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
+++ b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
@@ -68,6 +68,7 @@ export interface AgentIslandNativeScreenMetrics {
interface MacAgentIslandNativeHostOptions {
onPointerZones: (zones: { menuBar: boolean; panel: boolean; displayId?: number | null }) => void;
onExpand: (displayId?: number | null) => void;
+ onCollapse: (displayId?: number | null) => void;
onFocusSession: (sessionId: string) => void;
onOpenSettings: () => void;
onNewMessage: () => void;
@@ -499,6 +500,11 @@ export class MacAgentIslandNativeHost {
return;
}
+ if (payload.type === 'collapse' && this.child === child) {
+ this.options.onCollapse(typeof payload.displayId === 'number' ? payload.displayId : null);
+ return;
+ }
+
if (payload.type === 'focus-session' && this.child === child && typeof payload.sessionId === 'string') {
this.options.onFocusSession(payload.sessionId);
return;
@@ -779,7 +785,9 @@ async function buildDevMacAgentIslandHelper(): Promise<void> {
return;
}
fs.mkdirSync(path.dirname(binary), { recursive: true });
- await execFilePromise('swiftc', [source, '-O', '-o', binary], 20_000);
+ // Cold -O compile of the single-file helper is ~20s+ on this machine;
+ // a 20s cap kills the first build and permanently hides the island.
+ await execFilePromise('swiftc', [source, '-O', '-o', binary], 120_000);
fs.chmodSync(binary, 0o755);
fs.writeFileSync(hashFile, `${sourceHash}\n`, 'utf8');
log.info('built dev macOS agent island helper', { path: binary });
diff --git a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
index 7121674ce3..5541e7bb7f 100644
--- a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
@@ -338,6 +338,26 @@ describe('MacAgentIslandNativeHost', () => {
});
});
+ it('forwards collapse events from the helper', async () => {
+ const child = createFakeChild();
+ h.spawn.mockReturnValue(child);
+ const options = createOptions();
+ const { MacAgentIslandNativeHost } = await import('../MacAgentIslandNativeHost.js');
+ const host = new MacAgentIslandNativeHost(options);
+
+ expect(host.publish(createDisplayState(), createFrame())).toBe(true);
+ await vi.advanceTimersByTimeAsync(0);
+
+ (child.stdout as PassThrough).write(`${JSON.stringify({ type: 'ready' })}\n`);
+ (child.stdout as PassThrough).write(`${JSON.stringify({
+ type: 'collapse',
+ displayId: 2,
+ })}\n`);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(options.onCollapse).toHaveBeenCalledWith(2);
+ });
+
it('copies builtin sounds when building the dev helper', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-island-dev-assets-'));
const appPath = path.join(tempDir, 'app');
@@ -565,6 +585,7 @@ function createOptions(): ConstructorParameters<typeof import('../MacAgentIsland
return {
onPointerZones: vi.fn(),
onExpand: vi.fn(),
+ onCollapse: vi.fn(),
onFocusSession: vi.fn(),
onOpenSettings: vi.fn(),
onNewMessage: vi.fn(),
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index e513e21e41..58814a974f 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -3583,6 +3583,43 @@ describe('AgentIslandService native publishing', () => {
expect(latestNativeFrame(publish)).toMatchObject({ height: 214 });
});
+ it('collapses a click-expanded island from the compact-position click', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish },
+ });
+ syncEnabledForTest(service, publish);
+ const expand = (
+ service as unknown as {
+ handleNativeExpand(): void;
+ }
+ ).handleNativeExpand.bind(service);
+ const collapse = (
+ service as unknown as {
+ handleNativeCollapse(): void;
+ }
+ ).handleNativeCollapse.bind(service);
+
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');
+ expand();
+ expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({
+ mode: 'expanded',
+ displayPolicy: 'manualExpanded',
+ });
+
+ collapse();
+ expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({
+ mode: 'compact',
+ displaySurface: 'collapsed',
+ });
+ });
+
it('publishes native frames for every display in all-displays render mode', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 758c1010da..9f6c0d1838 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -20,6 +20,7 @@ import {
dismissAgentIslandActiveReveal,
getNextAgentIslandTimerAt,
markAgentIslandSessionAttention,
+ requestAgentIslandManualCollapse,
requestAgentIslandManualExpand,
requestAgentIslandSessionFocus,
setAgentIslandAppFocused,
@@ -1411,6 +1412,50 @@ describe('Agent Island display state', () => {
expect(display.displaySurface).toBe('sessionList');
});
+ it('collapses immediately when the compact island position is clicked while expanded', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(state, { sessionId: 'running', title: 'Running' }, statusEvent(true, 'Running'), 1_000);
+ expect(requestAgentIslandManualExpand(state)).toBe(true);
+ expect(buildAgentIslandDisplayState(state, 1_051).mode).toBe('expanded');
+
+ expect(requestAgentIslandManualCollapse(state, 1_100)).toBe(true);
+
+ const display = buildAgentIslandDisplayState(state, 1_101);
+ expect(display.mode).toBe('compact');
+ expect(display.notchStatus).toBe('peek');
+ expect(display.displayPolicy).toBe('peek');
+ expect(display.displaySurface).toBe('collapsed');
+ });
+
+ it('does not immediately re-expand from hover after a compact-position collapse', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(state, { sessionId: 'running', title: 'Running' }, statusEvent(true, 'Running'), 1_000);
+ setAgentIslandHovered(state, true, 1_050);
+ expect(requestAgentIslandManualExpand(state)).toBe(true);
+ expect(buildAgentIslandDisplayState(state, 1_100).mode).toBe('expanded');
+
+ setAgentIslandPointerZones(state, { menuBar: true, panel: false }, 1_100);
+ expect(requestAgentIslandManualCollapse(state, 1_110)).toBe(true);
+ setAgentIslandPointerZones(state, { menuBar: true, panel: false }, 1_120);
+
+ expect(buildAgentIslandDisplayState(state, 1_200).mode).toBe('compact');
+ expect(buildAgentIslandDisplayState(state, 2_000).mode).toBe('compact');
+
+ setAgentIslandHovered(state, false, 2_100);
+ setAgentIslandHovered(state, true, 2_500);
+ expect(buildAgentIslandDisplayState(state, 3_100).mode).toBe('expanded');
+ });
+
+ it('does not collapse from a compact-position click while the island is being dragged', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(state, { sessionId: 'running', title: 'Running' }, statusEvent(true, 'Running'), 1_000);
+ expect(requestAgentIslandManualExpand(state)).toBe(true);
+ expect(setAgentIslandLayoutDragActive(state, true)).toBe(true);
+
+ expect(requestAgentIslandManualCollapse(state, 1_200)).toBe(false);
+ expect(buildAgentIslandDisplayState(state, 1_201).mode).toBe('expanded');
+ });
+
it('does not expand from pending hover while the island is being dragged', () => {
const state = createAgentIslandState();
applyAgentIslandEvent(state, { sessionId: 'running', title: 'Running' }, statusEvent(true, 'Running'), 1_000);
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 3209ea1529..adf675652c 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -81,6 +81,7 @@ import {
hasAgentIslandSessionAttention,
isAgentIslandPendingFocusAck,
markAgentIslandSessionAttention,
+ requestAgentIslandManualCollapse,
requestAgentIslandManualExpand,
patchAgentIslandMetadata,
removeAgentIslandSession,
@@ -294,6 +295,7 @@ export class AgentIslandService {
this.nativeHost = deps.nativeHost ?? new MacAgentIslandNativeHost({
onPointerZones: (zones) => this.handleNativePointerZones(zones),
onExpand: (displayId) => this.handleNativeExpand(displayId),
+ onCollapse: () => this.handleNativeCollapse(),
onFocusSession: (sessionId) => this.focusSession(sessionId),
onOpenSettings: () => this.dispatchMainWindowCommand('open-agent-island-settings', { playSelectSound: true }),
onNewMessage: () => this.dispatchMainWindowCommand('new-maker', { playSelectSound: true }),
@@ -1559,6 +1561,13 @@ export class AgentIslandService {
}
}
+ private handleNativeCollapse(): void {
+ const now = Date.now();
+ if (!requestAgentIslandManualCollapse(this.state, now)) return;
+ this.playConfiguredSound('select', now);
+ this.publish();
+ }
+
private handleNativeLayoutDragActive(active: boolean): void {
if (!active) {
this.flushLayoutPreferenceWrites();
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index a52e44762b..6289fd49c2 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -404,6 +404,22 @@ export function requestAgentIslandManualExpand(state: AgentIslandState, displayI
return changed;
}
+export function requestAgentIslandManualCollapse(state: AgentIslandState, now: number): boolean {
+ if (state.layoutDragActive) return false;
+ const changed = state.hoverExpanded
+ || state.hoverIntentAt !== null
+ || state.collapseAt !== null
+ || state.protectedDismissPending;
+ state.hoverIntentAt = null;
+ state.hoverExpanded = false;
+ state.collapseAt = null;
+ state.protectedDismissPending = false;
+ state.hoverCooldownUntil = now + AGENT_ISLAND_HOVER_SHORT_COOLDOWN_MS;
+ // Keep current pointer-zone flags. Hover expand only re-arms after leave+re-enter,
+ // so clicking the original compact position does not immediately pop the island open again.
+ return changed;
+}
+
export function applyAgentIslandMetadata(
state: AgentIslandState,
meta: AgentIslandSessionMeta,