Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(agent-island): 支持完成任务左右滑动与乐观收起

Dash5a0082dc94d1
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 1635e65369..8b9df19cf9 100644
--- a/apps/desktop/native/agent-island/macos-agent-island-helper.swift
+++ b/apps/desktop/native/agent-island/macos-agent-island-helper.swift
@@ -1447,6 +1447,8 @@ struct AgentIslandStrings: Codable, Equatable {
let allowOnce: String
let alwaysAllowForSession: String
let deny: String
+ var markRead: String? = nil
+ var archive: String? = nil
// Older main-process payloads do not contain appName; keep their idle view brand-current.
var displayAppName: String { appName ?? "Cindy" }
@@ -1608,6 +1610,8 @@ struct AgentIslandDisplayState: Codable {
struct IncomingMessage: Codable {
let type: String
+ let requestId: String?
+ let success: Bool?
let state: AgentIslandDisplayState?
let frame: AgentIslandCarrierFrame?
let frames: [AgentIslandCarrierFrame]?
@@ -1657,7 +1661,7 @@ private let compactIslandStatusIconWidth: CGFloat = 18
private let compactIslandCarrierInset: CGFloat = 20
private let expandedIslandCarrierExpandedInset: CGFloat = 80
private let expandedIslandMinContentWidth: CGFloat = 360
-private let expandedIslandDefaultContentWidth: CGFloat = 640
+private let expandedIslandDefaultContentWidth: CGFloat = 440
private let expandedIslandMaxContentWidth: CGFloat = 920
private let expandedIslandHardwareNotchSideWidth: CGFloat = 96
private let expandedIslandHardwareNotchHorizontalPadding: CGFloat = 36
@@ -3330,7 +3334,10 @@ struct ExpandedSessionsView: View {
onFocus: {
eventSink(["type": "focus-session", "sessionId": current.sessionId])
},
- onPermissionAction: emitPermissionAction
+ onPermissionAction: emitPermissionAction,
+ onCompletionAction: { action, requestId in
+ eventSink(["type": "completion-action", "sessionId": current.sessionId, "action": action, "requestId": requestId])
+ }
)
.equatable()
.frame(maxWidth: .infinity, alignment: .leading)
@@ -3370,7 +3377,10 @@ struct ExpandedSessionsView: View {
onFocus: {
eventSink(["type": "focus-session", "sessionId": session.sessionId])
},
- onPermissionAction: emitPermissionAction
+ onPermissionAction: emitPermissionAction,
+ onCompletionAction: { action, requestId in
+ eventSink(["type": "completion-action", "sessionId": session.sessionId, "action": action, "requestId": requestId])
+ }
)
.equatable()
.frame(maxWidth: .infinity, alignment: .leading)
@@ -3395,6 +3405,7 @@ struct ExpandedSessionRow: View, Equatable {
let mascotSkin: String
let onFocus: () -> Void
let onPermissionAction: (AgentIslandPermissionAction, String) -> Void
+ let onCompletionAction: (String, String) -> Void
@State private var isHovered = false
static func == (lhs: ExpandedSessionRow, rhs: ExpandedSessionRow) -> Bool {
@@ -3407,6 +3418,18 @@ struct ExpandedSessionRow: View, Equatable {
}
var body: some View {
+ if session.phase == "completed" {
+ CompletedSessionSwipeRow(strings: strings, canArchive: session.companion == nil,
+ onFocus: onFocus, onAction: onCompletionAction) {
+ card
+ }
+ .id("\(session.sessionId):\(session.lastActivityAt)")
+ } else {
+ card
+ }
+ }
+
+ @ViewBuilder private var card: some View {
let shape = RoundedRectangle(cornerRadius: 12, style: .continuous)
VStack(alignment: .leading, spacing: rowSpacing) {
if session.permissionAction == nil {
@@ -3497,6 +3520,210 @@ struct ExpandedSessionRow: View, Equatable {
}
}
+/// One displacement shared by mouse dragging and AppKit's phased trackpad events.
+/// Momentum never commits an action: only the user's release can do that.
+struct CompletedSessionSwipeRow<Content: View>: View {
+ let strings: AgentIslandStrings
+ let canArchive: Bool
+ let onFocus: () -> Void
+ let onAction: (String, String) -> Void
+ @ViewBuilder let content: () -> Content
+ @State private var offset: CGFloat = 0
+ @State private var armed = false
+ @State private var commitRequestId: String?
+ @State private var collapsed = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ private let reveal: CGFloat = 80
+ private var settleAnimation: Animation? { reduceMotion ? nil : .spring(response: 0.3, dampingFraction: 0.86) }
+
+ var body: some View {
+ content()
+ .offset(x: offset)
+ .background(GeometryReader { geometry in
+ let right = offset >= 0
+ Button { commit(width: geometry.size.width) } label: {
+ VStack(spacing: 5) {
+ Image(systemName: right ? "checkmark" : "archivebox")
+ .font(.system(size: 18, weight: .medium))
+ Text(right ? (strings.markRead ?? "Mark as read") : (strings.archive ?? "Archive"))
+ .font(.system(size: 11, weight: .medium))
+ .lineLimit(1)
+ }
+ .foregroundColor(.white.opacity(0.95))
+ .fixedSize(horizontal: true, vertical: false)
+ .frame(width: reveal, height: geometry.size.height)
+ // Lay out the label once behind the card. The opening clips it; it never reflows.
+ .frame(width: geometry.size.width, alignment: right ? .leading : .trailing)
+ .background((right ? agentIslandBlue : Color.white.opacity(0.24)).opacity(armed ? 1 : 0.8))
+ .mask(alignment: right ? .leading : .trailing) {
+ Rectangle().frame(width: abs(offset))
+ }
+ }
+ .buttonStyle(.plain)
+ .frame(maxWidth: .infinity, alignment: right ? .leading : .trailing)
+ .opacity(offset == 0 ? 0 : 1)
+ .accessibilityHidden(offset == 0)
+ })
+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .overlay(GeometryReader { geometry in
+ CompletionSwipeInput(offset: offset,
+ onChange: { proposed in
+ guard commitRequestId == nil else { return }
+ offset = min(geometry.size.width, max(canArchive ? -geometry.size.width : 0, proposed))
+ let nextArmed = abs(offset) >= max(140, geometry.size.width * 0.72)
+ if nextArmed && !armed {
+ NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now)
+ }
+ armed = nextArmed
+ },
+ onEnd: { cancelled in
+ guard commitRequestId == nil else { return }
+ if armed && !cancelled {
+ commit(width: geometry.size.width)
+ return
+ }
+ withAnimation(settleAnimation) {
+ offset = !cancelled && abs(offset) >= 24 ? (offset > 0 ? reveal : -reveal) : 0
+ armed = false
+ }
+ },
+ onClick: { x in
+ guard commitRequestId == nil else { return }
+ if (offset > 0 && x < offset) || (offset < 0 && x > geometry.size.width + offset) {
+ commit(width: geometry.size.width)
+ }
+ else if offset != 0 {
+ withAnimation(settleAnimation) { offset = 0 }
+ } else { onFocus() }
+ })
+ })
+ .frame(height: collapsed ? 0 : nil)
+ .clipped()
+ .allowsHitTesting(commitRequestId == nil)
+ .task(id: commitRequestId) {
+ guard commitRequestId != nil else { return }
+ // Fill first, then collapse locally. Neither animation waits for disk or the remote host.
+ do {
+ if !reduceMotion { try await Task.sleep(nanoseconds: 120_000_000) }
+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.10)) { collapsed = true }
+ } catch { /* View disappeared or a newer completion replaced it. */ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .islandCompletionActionResult)) { notification in
+ guard notification.userInfo?["requestId"] as? String == commitRequestId,
+ notification.userInfo?["success"] as? Bool == false else { return }
+ offset = 0
+ armed = false
+ commitRequestId = nil
+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.12)) { collapsed = false }
+ }
+ }
+
+ private func commit(width: CGFloat) {
+ guard commitRequestId == nil else { return }
+ let requestId = UUID().uuidString
+ let action = offset >= 0 ? "mark-read" : "archive"
+ commitRequestId = requestId
+ withAnimation(reduceMotion ? nil : .easeOut(duration: 0.12)) {
+ offset = offset >= 0 ? width : -width
+ armed = true
+ }
+ // A committed user action survives the island closing during its brief animation.
+ let send = onAction
+ DispatchQueue.main.asyncAfter(deadline: .now() + (reduceMotion ? 0 : 0.22)) {
+ send(action, requestId)
+ }
+ }
+}
+
+extension Notification.Name {
+ static let islandCompletionActionResult = Notification.Name("islandCompletionActionResult")
+}
+
+struct CompletionSwipeInput: NSViewRepresentable {
+ let offset: CGFloat
+ let onChange: (CGFloat) -> Void
+ let onEnd: (Bool) -> Void
+ let onClick: (CGFloat) -> Void
+
+ func makeNSView(context: Context) -> CompletionSwipeInputView { CompletionSwipeInputView() }
+ func updateNSView(_ view: CompletionSwipeInputView, context: Context) {
+ view.input = self
+ }
+}
+
+final class CompletionSwipeInputView: NSView {
+ var input: CompletionSwipeInput?
+ private var origin: NSPoint?
+ private var startOffset: CGFloat = 0
+ private var translation = NSPoint.zero
+ private var axis = 0 // 0 undecided, 1 horizontal, 2 vertical
+ private var wheelActive = false
+ private var suppressWheelMomentum = false
+ private var wheelEnd: DispatchWorkItem?
+ override var acceptsFirstResponder: Bool { true }
+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
+
+ override func mouseDown(with event: NSEvent) {
+ origin = event.locationInWindow
+ startOffset = input?.offset ?? 0
+ axis = 0
+ }
+ override func mouseDragged(with event: NSEvent) {
+ guard let origin else { return }
+ update(x: event.locationInWindow.x - origin.x, y: event.locationInWindow.y - origin.y)
+ }
+ override func mouseUp(with event: NSEvent) {
+ guard origin != nil else { return }
+ origin = nil
+ if axis == 1 { input?.onEnd(false) }
+ else if axis == 0 { input?.onClick(convert(event.locationInWindow, from: nil).x) }
+ axis = 0
+ }
+ private func update(x: CGFloat, y: CGFloat) {
+ if axis == 0 && max(abs(x), abs(y)) >= 6 { axis = abs(x) > abs(y) ? 1 : 2 }
+ if axis == 1 { input?.onChange(startOffset + x) }
+ }
+ override func scrollWheel(with event: NSEvent) {
+ // Vertical inertia belongs to the list; horizontal inertia cannot commit another row.
+ if !event.momentumPhase.isEmpty {
+ if !suppressWheelMomentum { super.scrollWheel(with: event) }
+ return
+ }
+ if !wheelActive || event.phase.contains(.began) {
+ wheelActive = true
+ suppressWheelMomentum = false
+ startOffset = input?.offset ?? 0
+ translation = .zero
+ axis = 0
+ }
+ translation.x += event.scrollingDeltaX
+ translation.y += event.scrollingDeltaY
+ update(x: translation.x, y: translation.y)
+ if axis != 1 { super.scrollWheel(with: event) }
+ wheelEnd?.cancel()
+ if event.phase.contains(.ended) || event.phase.contains(.cancelled) {
+ finishWheel(cancelled: event.phase.contains(.cancelled))
+ } else if event.phase.isEmpty {
+ let work = DispatchWorkItem { [weak self] in self?.finishWheel(cancelled: false) }
+ wheelEnd = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: work)
+ }
+ }
+ private func finishWheel(cancelled: Bool) {
+ suppressWheelMomentum = axis == 1
+ if axis == 1 { input?.onEnd(cancelled) }
+ wheelActive = false
+ axis = 0
+ }
+ override func keyDown(with event: NSEvent) {
+ if event.keyCode == 53 { input?.onEnd(true) }
+ else { super.keyDown(with: event) }
+ }
+ override func viewDidMoveToWindow() {
+ if window == nil { wheelEnd?.cancel() }
+ }
+}
+
private let expandedRowLeadingSize: CGFloat = 32
func expandedCardFillOpacity(session: AgentIslandSession, hovered: Bool) -> Double {
@@ -6893,6 +7120,13 @@ final class AgentIslandAppDelegate: NSObject, NSApplicationDelegate {
guard let data = line.data(using: .utf8) else { return }
do {
let message = try decoder.decode(IncomingMessage.self, from: data)
+ if message.type == "completion-action-result", let requestId = message.requestId {
+ DispatchQueue.main.async {
+ NotificationCenter.default.post(name: .islandCompletionActionResult, object: nil,
+ userInfo: ["requestId": requestId, "success": message.success == true])
+ }
+ return
+ }
if message.type == "shutdown" {
DispatchQueue.main.async { [controllerManager] in
controllerManager.closeAll()
diff --git a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
index 4f63e52083..4a4fdcb849 100644
--- a/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
+++ b/apps/desktop/src/main/agent-island/MacAgentIslandNativeHost.ts
@@ -70,6 +70,7 @@ interface MacAgentIslandNativeHostOptions {
onExpand: (displayId?: number | null) => void;
onCollapse: (displayId?: number | null) => void;
onFocusSession: (sessionId: string) => void;
+ onCompletionAction?: (sessionId: string, action: 'mark-read' | 'archive') => Promise<boolean>;
onOpenSettings: () => void;
onNewMessage: () => void;
onToggleSound: () => void;
@@ -510,6 +511,26 @@ export class MacAgentIslandNativeHost {
return;
}
+ if (
+ payload.type === 'completion-action' && this.child === child
+ && typeof payload.sessionId === 'string' && payload.sessionId.length > 0
+ && (payload.action === 'mark-read' || payload.action === 'archive')
+ ) {
+ const { sessionId, action, requestId } = payload;
+ const reply = (success: boolean): void => {
+ if (this.child !== child || typeof requestId !== 'string') return;
+ try {
+ child.stdin.write(`${JSON.stringify({ type: 'completion-action-result', requestId, success })}\n`);
+ } catch (error) {
+ log.warn('failed to send completion action result', { error });
+ }
+ };
+ void Promise.resolve()
+ .then(() => this.options.onCompletionAction?.(sessionId, action) ?? false)
+ .then(reply, () => reply(false));
+ return;
+ }
+
if (
payload.type === 'permission-action'
&& this.child === child
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 5d12562c41..e575e86197 100644
--- a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
@@ -215,6 +215,30 @@ describe('MacAgentIslandNativeHost', () => {
expect(h.spawn).toHaveBeenCalledTimes(4);
});
+ // The native protocol must accept only the two completion actions; no existing
+ // callback test covers malformed completion events (unit tier).
+ it('forwards completion actions and rejects unknown actions', async () => {
+ const child = createFakeChild();
+ h.spawn.mockReturnValue(child);
+ const options = { ...createOptions(), onCompletionAction: vi.fn().mockResolvedValueOnce(true).mockRejectedValueOnce(new Error('offline')) };
+ const replies: string[] = [];
+ child.stdin.on('data', (data) => replies.push(String(data)));
+ const { MacAgentIslandNativeHost } = await import('../MacAgentIslandNativeHost.js');
+ const host = new MacAgentIslandNativeHost(options);
+ host.publish(createDisplayState(), createFrame());
+ await vi.advanceTimersByTimeAsync(0);
+ for (const action of ['mark-read', 'archive', 'delete']) {
+ (child.stdout as PassThrough).write(`${JSON.stringify({ type: 'completion-action', sessionId: 's1', action, requestId: action })}\n`);
+ }
+ await vi.advanceTimersByTimeAsync(0);
+ expect(options.onCompletionAction.mock.calls).toEqual([['s1', 'mark-read'], ['s1', 'archive']]);
+ expect(replies.map(line => JSON.parse(line)).filter(message => message.type === 'completion-action-result')).toEqual([
+ { type: 'completion-action-result', requestId: 'mark-read', success: true },
+ { type: 'completion-action-result', requestId: 'archive', success: false },
+ ]);
+ host.stop();
+ });
+
it('forwards permission action events from the helper', async () => {
const child = createFakeChild();
h.spawn.mockReturnValue(child);
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 581beba19e..5fad32d9ed 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -56,6 +56,8 @@ function handleInteractionRequestForTest(
}
const mocks = vi.hoisted(() => ({
+ patchSessionMetaInDb: vi.fn(),
+ remoteInvoke: vi.fn(),
getSessionRowSnapshot: vi.fn<() => Promise<{
status: string;
title: string | null;
@@ -139,8 +141,11 @@ vi.mock('electron', () => {
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionRowSnapshot: mocks.getSessionRowSnapshot,
+ patchSessionMetaInDb: mocks.patchSessionMetaInDb,
}));
+vi.mock('../../device-link/index.js', () => ({ remoteInvoke: mocks.remoteInvoke }));
+
vi.mock('../companionIdentity.js', async (importOriginal) => ({
...(await importOriginal<typeof import('../companionIdentity.js')>()),
readAgentIslandCompanion: mocks.readAgentIslandCompanion,
@@ -162,6 +167,8 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({
import { resetEpermGuidanceForTest } from '../../file-access/permissions.js';
beforeEach(() => {
+ mocks.patchSessionMetaInDb.mockReset();
+ mocks.remoteInvoke.mockReset();
setDeepLinkMainWindow(null);
takePendingDeepLink();
mocks.getSessionRowSnapshot.mockReset();
@@ -311,9 +318,9 @@ describe('Agent Island window geometry', () => {
};
expect(computeAgentIslandWindowBounds(display)).toEqual({
- x: 624,
+ x: 724,
y: -900,
- width: 680,
+ width: 480,
height: 580,
});
});
@@ -337,9 +344,9 @@ describe('Agent Island window geometry', () => {
};
expect(computeAgentIslandWindowBounds(display, true)).toEqual({
- x: 564,
+ x: 664,
y: -900,
- width: 800,
+ width: 600,
height: 640,
});
});
@@ -350,9 +357,9 @@ describe('Agent Island window geometry', () => {
};
expect(computeAgentIslandWindowBounds(display, { expanded: true, contentHeight: 240 })).toEqual({
- x: 564,
+ x: 664,
y: -900,
- width: 800,
+ width: 600,
height: 320,
});
});
@@ -363,16 +370,16 @@ describe('Agent Island window geometry', () => {
};
expect(computeAgentIslandWindowBounds(display, { expanded: false, centerXRatio: 1 })).toEqual({
- x: 1088,
+ x: 1288,
y: -900,
- width: 680,
+ width: 480,
height: 580,
});
expect(computeAgentIslandWindowBounds(display, { expanded: true, centerXRatio: 1 })).toEqual({
- x: 1028,
+ x: 1228,
y: -900,
- width: 800,
+ width: 600,
height: 640,
});
});
@@ -612,6 +619,69 @@ describe('AgentIslandService native publishing', () => {
mocks.tapWindowBroadcast.mockReset();
});
+ // Swipe actions must use the real lifecycle entry and retain attention on failure.
+ // Existing focus tests do not cover background completion actions (unit tier).
+ it('reads or archives completed tasks without focusing, and retains failed archives', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, headless: true, publish: () => true, suspend: () => undefined },
+ });
+ service.setEnabled(false);
+ const meta = { sessionId: 'swipe-task', agentKind: 'codex' as const };
+ service.handleUserPrompt(meta, 'run');
+ await service.handleCompletionAction(meta.sessionId, 'archive');
+ expect(mocks.patchSessionMetaInDb).not.toHaveBeenCalled();
+ service.handleAgentEvent(meta, doneEvent());
+ mocks.patchSessionMetaInDb.mockRejectedValueOnce(new Error('offline'));
+ await service.handleCompletionAction(meta.sessionId, 'archive');
+ expect(service.getSessionActivitySnapshot(meta.sessionId)).toMatchObject({ attention: true });
+ expect(mocks.showMessageBox).toHaveBeenCalled();
+ mocks.patchSessionMetaInDb.mockResolvedValueOnce({ status: 'archived' });
+ await service.handleCompletionAction(meta.sessionId, 'archive');
+ expect(mocks.patchSessionMetaInDb).toHaveBeenLastCalledWith(meta.sessionId, { status: 'archived' });
+ expect(service.getSessionActivitySnapshot(meta.sessionId)?.attention ?? false).toBe(false);
+ service.handleUserPrompt(meta, 'again');
+ service.handleAgentEvent(meta, doneEvent());
+ await service.handleCompletionAction(meta.sessionId, 'mark-read');
+ expect(service.getSessionActivitySnapshot(meta.sessionId)?.attention ?? false).toBe(false);
+ expect(mocks.patchSessionMetaInDb).toHaveBeenCalledTimes(2);
+ service.resetRuntimeState();
+ });
+
+ it('routes remote swipe actions to their owner and excludes companion archives', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn<(state: AgentIslandDisplayState) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, suspend: () => undefined },
+ });
+ syncEnabledForTest(service, publish);
+ const input = { sessionId: 'remote-swipe', deviceId: 'owner-device', deviceName: 'Mac',
+ title: 'Task', workingDir: null, workspaceKind: null, agentKind: 'codex', detail: '' };
+ const complete = () => {
+ service.setDeviceSessions([{ ...input, phase: 'running' }]);
+ service.setDeviceSessions([{ ...input, phase: 'completed' }]);
+ };
+ complete();
+ mocks.remoteInvoke.mockResolvedValueOnce({ ok: false, error: { message: 'offline' } });
+ await service.handleCompletionAction(input.sessionId, 'mark-read');
+ expect(publish.mock.calls.at(-1)?.[0].sessions).toContainEqual(expect.objectContaining({ sessionId: input.sessionId, attention: true }));
+ mocks.remoteInvoke.mockResolvedValue({ ok: true });
+ await service.handleCompletionAction(input.sessionId, 'mark-read');
+ expect(mocks.remoteInvoke).toHaveBeenLastCalledWith('owner-device', 'notification:clear-session-attention', ['remote-swipe', 'explicit']);
+ expect(publish.mock.calls.at(-1)?.[0].sessions.some(s => s.sessionId === input.sessionId && s.attention)).toBe(false);
+ complete();
+ await service.handleCompletionAction(input.sessionId, 'archive');
+ expect(mocks.remoteInvoke).toHaveBeenLastCalledWith('owner-device', 'local-db:sessions:patch-meta', ['remote-swipe', { status: 'archived' }]);
+ const count = mocks.remoteInvoke.mock.calls.length;
+ service.setDeviceSessions([{ ...input, phase: 'completed', companion: { name: 'Teammate', avatar: '', avatarColor: 'teal' } }]);
+ await service.handleCompletionAction(input.sessionId, 'archive');
+ expect(mocks.remoteInvoke).toHaveBeenCalledTimes(count);
+ expect(mocks.patchSessionMetaInDb).not.toHaveBeenCalled();
+ service.resetRuntimeState();
+ });
+
it('keeps compact activity broadcasting alive in headless mode', async () => {
const { AgentIslandService } = await import('../service.js');
const service = new AgentIslandService({
@@ -4596,7 +4666,7 @@ describe('AgentIslandService native publishing', () => {
};
handleInteractionRequestForTest(service, { sessionId: 's1', agentKind: 'codex' }, request);
expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({ mode: 'expanded' });
- expect(latestNativeFrame(publish)).toMatchObject({ width: 800 });
+ expect(latestNativeFrame(publish)).toMatchObject({ width: 600 });
setLayoutPreference({ expandedContentWidth: 700 });
expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({ mode: 'expanded' });
@@ -4757,7 +4827,7 @@ describe('AgentIslandService native publishing', () => {
const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));
expect(framesById.get(1)).toMatchObject({ width: 368 });
- expect(framesById.get(2)).toMatchObject({ width: 800 });
+ expect(framesById.get(2)).toMatchObject({ width: 600 });
vi.runOnlyPendingTimers();
} finally {
vi.useRealTimers();
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 72b475fe72..d8cae6b92b 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -75,7 +75,7 @@ import {
type AgentIslandSoundSettings,
type AgentIslandScreenLayoutMetrics,
} from '../../shared/agentIsland.js';
-import { getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
+import { getSessionRowSnapshot, patchSessionMetaInDb } from '../localDb/ipc/sessions.js';
import { setAgentIslandCompanionChangeSink } from '../localDb/agentIslandSessionPatch.js';
import {
companionAvatarHasArtwork,
@@ -423,6 +423,7 @@ export class AgentIslandService {
onExpand: (displayId) => this.handleNativeExpand(displayId),
onCollapse: () => this.handleNativeCollapse(),
onFocusSession: (sessionId) => this.focusSession(sessionId),
+ onCompletionAction: (sessionId, action) => this.handleCompletionAction(sessionId, action),
onOpenSettings: () => this.dispatchMainWindowCommand('open-agent-island-settings', { playSelectSound: true }),
onNewMessage: () => this.dispatchMainWindowCommand('new-maker', { playSelectSound: true }),
onToggleSound: () => this.dispatchMainWindowCommand('toggle-agent-island-sound'),
@@ -2653,6 +2654,40 @@ export class AgentIslandService {
openMainWindowSession(nextSessionId, islandEntryId ? { islandEntryId } : undefined);
}
+ private readonly completionActionsPending = new Set<string>();
+
+ async handleCompletionAction(sessionId: string, action: 'mark-read' | 'archive'): Promise<boolean> {
+ const session = this.state.sessions.get(sessionId);
+ if (!session || session.phase !== 'completed' || this.completionActionsPending.has(sessionId)) return false;
+ // Companion main tasks have their own lifecycle; only their notification may be read here.
+ if (action === 'archive' && session.companion) return false;
+ const generation = session.activityGeneration;
+ this.completionActionsPending.add(sessionId);
+ try {
+ if (session.sourceDeviceId) {
+ const { remoteInvoke } = await import('../device-link/index.js');
+ const result = await remoteInvoke(session.sourceDeviceId,
+ action === 'archive' ? 'local-db:sessions:patch-meta' : 'notification:clear-session-attention',
+ action === 'archive' ? [sessionId, { status: 'archived' }] : [sessionId, 'explicit']);
+ if (!result.ok) throw new Error(result.error.message);
+ } else if (action === 'archive') {
+ await patchSessionMetaInDb(sessionId, { status: 'archived' });
+ }
+ const current = this.state.sessions.get(sessionId);
+ if (current && (current !== session || current.activityGeneration !== generation)) return false;
+ clearAppBadgeSessionAttention(sessionId, 'explicit');
+ // Keep the local mirror in sync even when the remote push arrives later.
+ this.handleSessionAttentionCleared(sessionId, 'explicit');
+ return true;
+ } catch (error) {
+ log.warn('island completion action failed', { action, error });
+ void dialog.showMessageBox({ type: 'error', message: t('agentIsland.native.actionFailed') });
+ return false;
+ } finally {
+ this.completionActionsPending.delete(sessionId);
+ }
+ }
+
/** 记下这次点击并取代之前的任何一次;被点的卡不是未读完成 / 报错时不留可处置记录。 */
private recordIslandEntryAlert(sessionId: string, now: number): string | null {
const stamp = readAgentIslandUnreadTerminalStamp(this.state, sessionId);
@@ -2757,6 +2792,8 @@ function collapseManualExpandedStateForInactiveDisplay(displayState: AgentIsland
function buildAgentIslandStrings(): AgentIslandStrings {
return {
appName: BRAND_NAME,
+ markRead: t('agentIsland.native.markRead'),
+ archive: t('agentIsland.native.archive'),
newConversationTitle: t('agentIsland.native.newConversationTitle'),
newConversationHint: t('agentIsland.native.newConversationHint'),
muteSound: t('agentIsland.native.muteSound'),
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e5e321e289..7b827b6345 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1085,6 +1085,9 @@
},
"agentIsland": {
"native": {
+ "markRead": "Mark as read",
+ "archive": "Archive",
+ "actionFailed": "Could not complete the action. The notification has been kept. Try again.",
"newConversationTitle": "New Session",
"newConversationHint": "Start a new session",
"muteSound": "Mute Agent Island",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c634b6c660..aa28c17a46 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1073,6 +1073,9 @@
},
"agentIsland": {
"native": {
+ "markRead": "既読にする",
+ "archive": "アーカイブ",
+ "actionFailed": "操作を完了できませんでした。通知は保持されています。もう一度お試しください。",
"newConversationTitle": "新しいセッション",
"newConversationHint": "新しいセッションを開始",
"muteSound": "Agent Island の音をミュート",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 66f9c9d783..e66f0008f9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1073,6 +1073,9 @@
},
"agentIsland": {
"native": {
+ "markRead": "읽음으로 표시",
+ "archive": "보관",
+ "actionFailed": "작업을 완료하지 못했습니다. 알림은 유지됩니다. 다시 시도해 주세요.",
"newConversationTitle": "새 세션",
"newConversationHint": "새 세션 시작",
"muteSound": "Agent Island 소리 끄기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 0f0fe7389c..1892a60cba 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1073,6 +1073,9 @@
},
"agentIsland": {
"native": {
+ "markRead": "标为已读",
+ "archive": "存档",
+ "actionFailed": "操作未完成,提醒已保留,请重试。",
"newConversationTitle": "新建任务",
"newConversationHint": "开始一个新的任务",
"muteSound": "关闭灵动岛声音",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d6cdcbde1a..daf32744a4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1073,6 +1073,9 @@
},
"agentIsland": {
"native": {
+ "markRead": "標為已讀",
+ "archive": "封存",
+ "actionFailed": "操作未完成,提醒已保留,請重試。",
"newConversationTitle": "新建任務",
"newConversationHint": "開始一個新的任務",
"muteSound": "關閉靈動島聲音",
diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.ts
index 2142aa9af4..03622db2ce 100644
--- a/apps/desktop/src/shared/agentIsland.ts
+++ b/apps/desktop/src/shared/agentIsland.ts
@@ -426,6 +426,8 @@ export function createEmptyAgentIslandPillSnapshot(): AgentIslandPillSnapshot {
*/
export interface AgentIslandStrings {
appName: string;
+ markRead?: string;
+ archive?: string;
newConversationTitle: string;
newConversationHint: string;
muteSound: string;
@@ -480,7 +482,7 @@ export const DEFAULT_AGENT_ISLAND_STRINGS: AgentIslandStrings = {
deny: 'Deny',
};
-export const AGENT_ISLAND_MAX_EXPANDED_WIDTH = 640;
+export const AGENT_ISLAND_MAX_EXPANDED_WIDTH = 440;
export const AGENT_ISLAND_MAX_RESIZABLE_WIDTH = 920;
export const AGENT_ISLAND_MIN_EXPANDED_WIDTH = 360;
export const AGENT_ISLAND_IDLE_EXPANDED_WIDTH = 340;