Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(agent-island): 伙伴头像失败可重试、刷新取最新结果、群改名同步、远程输入不超上限
Dash9e40f844ef2f
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex b20a7c3a67..5766f654d1 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -65,6 +65,7 @@ const mocks = vi.hoisted(() => ({source?: string | null;} | null>>(() => Promise.resolve(null)),readAgentIslandCompanion: vi.fn<(sessionId: string) => Promise<AgentIslandCompanionIdentity | null>>(() => Promise.resolve(null)),+ companionAvatarThumbnail: vi.fn<(avatar: string, deviceId?: string | null) => Promise<string | undefined>>(() => Promise.resolve(undefined)),primaryDisplay: {id: 1,label: 'Built-in Retina Display',@@ -140,8 +141,10 @@ vi.mock('../../localDb/ipc/sessions.js', () => ({getSessionRowSnapshot: mocks.getSessionRowSnapshot,}));-vi.mock('../companionIdentity.js', () => ({+vi.mock('../companionIdentity.js', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../companionIdentity.js')>()),readAgentIslandCompanion: mocks.readAgentIslandCompanion,+ companionAvatarThumbnail: mocks.companionAvatarThumbnail,}));vi.mock('../layoutPreferenceStore.js', () => ({@@ -165,6 +168,8 @@ beforeEach(() => {mocks.getSessionRowSnapshot.mockResolvedValue(null);mocks.readAgentIslandCompanion.mockReset();mocks.readAgentIslandCompanion.mockResolvedValue(null);+ mocks.companionAvatarThumbnail.mockReset();+ mocks.companionAvatarThumbnail.mockResolvedValue(undefined);mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay);mocks.getPrimaryDisplay.mockReset();mocks.getDisplayMatching.mockReset();@@ -1768,6 +1773,75 @@ describe('AgentIslandService native publishing', () => {}));});+ // Review of #6436: a group rename never reached open group-lane cards, an older slow read+ // could overwrite a newer one, and a failed remote avatar read stayed a glyph forever.+ it('refreshes group-lane cards on a group rename, keeping only the latest of overlapping reads', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const lane = (groupName: string): AgentIslandCompanionIdentity => ({+ botId: 'b1', groupId: 'g1', companion: { name: 'Opus', groupName, hue: 'teal', glyph: 'O', glyphIsInitial: true },+ });+ mocks.getSessionRowSnapshot.mockImplementation(async () => ({+ status: 'active', title: 'Opus', userSendAt: null, workingDir: '/home', workspaceKind: null, source: 'bot',+ }));+ mocks.readAgentIslandCompanion.mockResolvedValue(lane('旧群名'));+ const service = new AgentIslandService({ getMainWindow: () => null, nativeHost: { failed: false, publish } });+ syncEnabledForTest(service, publish);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'claude-code', workingDir: '/home' }, 'hi');+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.projectName).toBe('旧群名'));++ service.handleBotGroupChanged('other-group');+ expect(mocks.readAgentIslandCompanion).toHaveBeenCalledTimes(1);++ let releaseSlow!: (identity: AgentIslandCompanionIdentity) => void;+ mocks.readAgentIslandCompanion.mockImplementationOnce(() => new Promise((resolve) => { releaseSlow = resolve; }));+ service.handleBotGroupChanged('g1');+ mocks.readAgentIslandCompanion.mockResolvedValueOnce(lane('新群名'));+ service.handleBotGroupChanged('g1');+ await vi.waitFor(() => expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.projectName).toBe('新群名'));+ releaseSlow(lane('过期群名'));+ await Promise.resolve();+ await Promise.resolve();+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.projectName).toBe('新群名');+ });++ it('retries a remote companion avatar after a failed read instead of keeping the glyph forever', async () => {+ vi.useFakeTimers();+ try {+ 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 input = {+ sessionId: 'r1', deviceId: 'd1', deviceName: 'Studio', title: 'Opus', workingDir: null, workspaceKind: null,+ agentKind: null, phase: 'running' as const, detail: 'x',+ companion: { name: 'Opus', avatar: 'cindy-media://blobs/' + 'a'.repeat(64) + '.png', avatarColor: 'teal' },+ };+ service.setDeviceSessions([input]);+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.companionAvatarThumbnail).toHaveBeenCalledTimes(1);+ service.setDeviceSessions([input]);+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.companionAvatarThumbnail).toHaveBeenCalledTimes(1);++ mocks.companionAvatarThumbnail.mockResolvedValue('JPEGDATA');+ await vi.advanceTimersByTimeAsync(61_000);+ service.setDeviceSessions([input]);+ await vi.advanceTimersByTimeAsync(0);+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]?.companion?.imageJpeg).toBe('JPEGDATA');+ } finally {+ vi.useRealTimers();+ }+ });+it('refreshes placeholder titles and hides dialogue workspace folders', 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/companionIdentity.ts b/apps/desktop/src/main/agent-island/companionIdentity.tsindex 8c22392ca7..4775c685ee 100644--- a/apps/desktop/src/main/agent-island/companionIdentity.ts+++ b/apps/desktop/src/main/agent-island/companionIdentity.ts@@ -13,6 +13,8 @@ import { encodeNotificationAvatar } from '../notificationAvatar.js';export interface AgentIslandCompanionIdentity {botId: string;+ /** Set for a group lane: a rename of that group changes what the card shows. */+ groupId?: string;companion: AgentIslandCompanionSnapshot;}@@ -57,7 +59,7 @@ export async function readAgentIslandCompanion(sessionId: string): Promise<Agentconst groupName = group?.name.trim();const base = companionSnapshotWithoutArtwork({ name: row.name, avatar: row.avatar, avatarColor: row.avatarColor, groupName });const imageJpeg = companionAvatarHasArtwork(row.avatar) ? await companionAvatarThumbnail(row.avatar) : undefined;- return { botId: row.botId, companion: imageJpeg ? { ...base, imageJpeg } : base };+ return { botId: row.botId, ...(groupId ? { groupId } : {}), companion: imageJpeg ? { ...base, imageJpeg } : base };}/** Name, tint and glyph: everything but the artwork, available without any read. */diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex fcb356391a..26d5a90b99 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -171,6 +171,7 @@ const REMOTE_AUTH_ERROR_FALLBACK_MS = 30_000;const ISLAND_ENTRY_ALERT_TTL_MS = 60_000;const MAX_ISLAND_ENTRY_SESSION_ID_LENGTH = 128;const REMOTE_COMPANION_CACHE_LIMIT = 64;+const REMOTE_COMPANION_ARTWORK_RETRY_MS = 60_000;const MAX_ISLAND_ENTRY_ID_LENGTH = 32;interface AgentIslandSessionMeta {@@ -332,7 +333,9 @@ export class AgentIslandService {private publishTimer: ReturnType<typeof setTimeout> | null = null;private readonly metadataCache = new Map<string, AgentIslandCachedMetadata>();private readonly metadataLoading = new Set<string>();- private readonly remoteCompanions = new Map<string, AgentIslandCompanionSnapshot>();+ private readonly remoteCompanions = new Map<string, { snapshot: AgentIslandCompanionSnapshot; retryAt: number | null }>();+ /** Latest refresh per Session: an older read that finishes late never overwrites a newer one. */+ private readonly companionRefreshSeq = new Map<string, number>();private lastDeviceSessionInputs: readonly AgentIslandRemoteSessionInput[] = [];private readonly layoutPreferencesByDisplayId: Map<number, AgentIslandLayoutPreference>;private readonly detachedLayoutPreferences: AgentIslandLayoutPreference[];@@ -754,22 +757,44 @@ export class AgentIslandService {if (!identity) return null;const key = JSON.stringify([input.deviceId, identity.name, identity.avatar, identity.avatarColor]);const cached = this.remoteCompanions.get(key);- if (cached) return cached;+ if (cached) {+ // A failed read stays a glyph, but the next sync after the pause tries again; the+ // avatar copy keeps its own failure backoff, so this never hammers the other computer.+ if (cached.retryAt !== null && cached.retryAt <= Date.now()) this.loadRemoteCompanionArtwork(key, input, cached.snapshot);+ return cached.snapshot;+ }const base = companionSnapshotWithoutArtwork(identity);- this.remoteCompanions.set(key, base);+ this.remoteCompanions.set(key, { snapshot: base, retryAt: null });if (this.remoteCompanions.size > REMOTE_COMPANION_CACHE_LIMIT) {this.remoteCompanions.delete(this.remoteCompanions.keys().next().value!);}- if (identity.avatar && companionAvatarHasArtwork(identity.avatar)) {- void companionAvatarThumbnail(identity.avatar, input.deviceId).then((imageJpeg) => {- if (!imageJpeg || this.remoteCompanions.get(key) !== base) return;- this.remoteCompanions.set(key, { ...base, imageJpeg });- this.setDeviceSessions(this.lastDeviceSessionInputs);- });- }+ this.loadRemoteCompanionArtwork(key, input, base);return base;}+ private loadRemoteCompanionArtwork(+ key: string,+ input: AgentIslandRemoteSessionInput,+ base: AgentIslandCompanionSnapshot,+ ): void {+ const avatar = input.companion?.avatar;+ if (!avatar || !companionAvatarHasArtwork(avatar)) return;+ const entry = this.remoteCompanions.get(key);+ if (!entry || entry.retryAt === Number.POSITIVE_INFINITY) return;+ // Marks the read as in flight until it settles.+ entry.retryAt = Number.POSITIVE_INFINITY;+ void companionAvatarThumbnail(avatar, input.deviceId).then((imageJpeg) => {+ const current = this.remoteCompanions.get(key);+ if (!current || current.snapshot !== base) return;+ if (!imageJpeg) {+ current.retryAt = Date.now() + REMOTE_COMPANION_ARTWORK_RETRY_MS;+ return;+ }+ this.remoteCompanions.set(key, { snapshot: { ...base, imageJpeg }, retryAt: null });+ this.setDeviceSessions(this.lastDeviceSessionInputs);+ });+ }+waitForCompletionNotification(sessionId: string): Promise<boolean> | undefined {return this.sessionActivityRelay.waitForCompletionNotification(sessionId);}@@ -788,6 +813,7 @@ export class AgentIslandService {this.metadataCache.clear();this.metadataLoading.clear();this.remoteCompanions.clear();+ this.companionRefreshSeq.clear();this.lastDeviceSessionInputs = [];this.lastSoundDisplayState = null;this.soundCooldownUntilByEvent.clear();@@ -1404,10 +1430,22 @@ export class AgentIslandService {/** A companion's name or avatar changed: redraw the Sessions that speak as it. */handleCompanionProfileChanged(botId: string): void {+ this.refreshCompanionSessions((identity) => identity.botId === botId);+ }++ /** A group was renamed or removed: redraw the group lanes that show its name. */+ handleBotGroupChanged(groupId: string): void {+ this.refreshCompanionSessions((identity) => identity.groupId === groupId);+ }++ private refreshCompanionSessions(matches: (identity: AgentIslandCompanionIdentity) => boolean): void {for (const [sessionId, cached] of this.metadataCache) {- if (cached.companion?.botId !== botId) continue;+ if (!cached.companion || !matches(cached.companion)) continue;+ const seq = (this.companionRefreshSeq.get(sessionId) ?? 0) + 1;+ this.companionRefreshSeq.set(sessionId, seq);void readAgentIslandCompanion(sessionId).then((companion) => {+ if (this.companionRefreshSeq.get(sessionId) !== seq) return;const latest = this.metadataCache.get(sessionId);if (latest) this.commitMetadata(sessionId, { ...latest, companion });})diff --git a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts b/apps/desktop/src/main/localDb/agentIslandSessionPatch.tsindex 801aa7bdb7..1f9cffb0e9 100644--- a/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts+++ b/apps/desktop/src/main/localDb/agentIslandSessionPatch.ts@@ -44,6 +44,13 @@ function toNullableString(value: unknown): string | null | undefined {return undefined;}+/** 伙伴群改名或解散后,让灵动岛重读以该群群专线说话的任务。 */+export function notifyAgentIslandBotGroupChanged(groupId: string): void {+ void import('../agent-island/service.js')+ .then(({ getAgentIslandService }) => getAgentIslandService()?.handleBotGroupChanged(groupId))+ .catch(() => undefined);+}+/** 伙伴改名或换头像后,让灵动岛重画以它身份说话的任务。 */export function notifyAgentIslandCompanionChanged(botId: string): void {void import('../agent-island/service.js')diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex b51b7d11f5..7a99b47b2a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12,6 +12,7 @@ import { createPluginTaskStore } from './pluginTaskStore.js';import { createPluginBackgroundTaskHandlers, revealAllPluginHiddenTasks } from './pluginHiddenTasks.js';import { setSessionHidden } from '../localDb/ipc/sessionHidden.js';import { isSessionHiddenSync } from '../localDb/hiddenSessionRegistry.js';+import { notifyAgentIslandBotGroupChanged } from '../localDb/agentIslandSessionPatch.js';import { ghostDeclaresHiddenTasks } from '../../shared/ghost.js';import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';@@ -11995,6 +11996,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const ownerScope = scope as ReturnType<typeof captureDataOwnerBroadcastScope> | undefined;if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return;broadcastToAllWindows(MAKER_PUSH.BOT_GROUP_CHANGED, payload, ownerScope);+ if (payload.change === 'updated' || payload.change === 'deleted') notifyAgentIslandBotGroupChanged(payload.groupId);// Phones read groups as remote resources; any change re-reads the row and the chat.broadcastBotGroupRemoteResourceChanged(payload.groupId);},diff --git a/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.tsindex 4a4d2eb804..299b6aa1d6 100644--- a/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts+++ b/apps/desktop/src/renderer/features/device-link/__tests__/agentIslandRemoteSessions.test.ts@@ -176,6 +176,17 @@ describe('buildAgentIslandRemoteSessionInputs', () => {expect(state.sessions.get('a-1')).toMatchObject({ companion, title: 'Opus', projectName: 'Mac Studio' });});+ // Review of #6436: companions are prepended, so near the parser cap one extra entry voided the whole payload.+ it('never exceeds the IPC cap, trimming tasks before companions', () => {+ const many = Array.from({ length: 600 }, (_, index) => remoteSession(`t-${index}`, 'device-a'));+ const everyActivity = (sessionId: string): RemoteSessionActivity => ({ sessionId, phase: 'running', compactDetail: '', attention: false });+ const bot = { id: 'opus', deviceId: 'device-a', deviceName: 'Mac', name: 'Opus', avatar: '', avatarColor: '', description: '', preview: '', activityAt: 1, sessionId: 'bot-s', online: true };+ const inputs = buildAgentIslandRemoteSessionInputs(many, MACHINE_ALL, everyActivity, [bot]);+ expect(inputs).toHaveLength(500);+ expect(inputs[0]?.sessionId).toBe('bot-s');+ expect(parseAgentIslandRemoteSessions(inputs)).not.toBeNull();+ });+it('skips Bot tasks and disconnected devices', () => {expect(buildAgentIslandRemoteSessionInputs(diff --git a/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.tsindex 19a4056549..f4e045a89a 100644--- a/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/agentIslandRemoteSessions.ts@@ -8,7 +8,7 @@*/import { useEffect, useRef } from 'react';-import type { AgentIslandRemoteSessionInput } from '../../../shared/agentIsland';+import { AGENT_ISLAND_REMOTE_SESSIONS_MAX, type AgentIslandRemoteSessionInput } from '../../../shared/agentIsland';import type { Session } from '@/lib/ccAgent.types';import type { RemoteBot } from '@/features/bots/remoteBotRoster';import { useRemoteBots } from '@/features/bots/useRemoteBots';@@ -32,6 +32,7 @@ export function buildAgentIslandRemoteSessionInputs(// another device reports its chat here whatever machine the sidebar is scoped to. Its chat is// a hidden Session, so it is never also in the remote task list.for (const bot of remoteBots) {+ if (inputs.length >= AGENT_ISLAND_REMOTE_SESSIONS_MAX) break;if (!bot.sessionId || !bot.online) continue;const activity = readActivity(bot.sessionId, bot.deviceId);if (!activity) continue;@@ -52,6 +53,8 @@ export function buildAgentIslandRemoteSessionInputs(const deviceId = session.deviceLinkDeviceId;if (!deviceId || session.deviceLinkConnectionStatus === 'disconnected') continue;if (companionSessionIds.has(session.id)) continue;+ // Companions were added first, so the cap trims tasks, never a companion.+ if (inputs.length >= AGENT_ISLAND_REMOTE_SESSIONS_MAX) break;const activity = readActivity(session.id, deviceId);if (!activity) continue;inputs.push({diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.tsindex 6e2c95f450..7c1bfcc2b0 100644--- a/apps/desktop/src/shared/agentIsland.ts+++ b/apps/desktop/src/shared/agentIsland.ts@@ -826,7 +826,8 @@ export interface AgentIslandRemoteCompanionInput {avatarColor: string;}-const AGENT_ISLAND_REMOTE_SESSIONS_MAX = 500;+/** Upper bound the IPC parser accepts; builders trim to it so one extra entry never voids the payload. */+export const AGENT_ISLAND_REMOTE_SESSIONS_MAX = 500;const AGENT_ISLAND_REMOTE_ID_MAX_LENGTH = 256;const AGENT_ISLAND_REMOTE_TEXT_MAX_LENGTH = 1024;const AGENT_ISLAND_SESSION_PHASES: readonly AgentIslandSessionPhase[] = [