Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复多显示器下灵动岛紧凑态宽度异常 (#2191)
Dash0ed352b5977c
diff --git a/apps/desktop/src/main/agent-island/__tests__/layoutPreferenceStore.test.ts b/apps/desktop/src/main/agent-island/__tests__/layoutPreferenceStore.test.tsnew file mode 100644index 0000000000..e6750fae7c--- /dev/null+++ b/apps/desktop/src/main/agent-island/__tests__/layoutPreferenceStore.test.ts@@ -0,0 +1,129 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, expect, it, vi } from 'vitest';++import type { AgentIslandLayoutPreference } from '../geometry.js';++const mocks = vi.hoisted(() => ({+ userDataPath: '',+}));++vi.mock('electron', () => ({+ app: {+ getPath: () => mocks.userDataPath,+ },+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ warn: vi.fn() }),+}));++function settingsFilePath(): string {+ return path.join(mocks.userDataPath, 'agent-island-layout-settings.json');+}++beforeEach(() => {+ mocks.userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-agent-island-layout-'));+ vi.resetModules();+});++afterEach(() => {+ fs.rmSync(mocks.userDataPath, { recursive: true, force: true });+});++it('reads the legacy displays-only format without creating detached preferences', async () => {+ fs.writeFileSync(+ settingsFilePath(),+ JSON.stringify({+ displays: {+ 7: {+ compactContentWidth: 420,+ displayName: 'Mi Monitor',+ },+ },+ }),+ );+ const store = await import('../layoutPreferenceStore.js');++ expect(store.readAgentIslandLayoutPreferences().get(7)).toEqual({+ compactContentWidth: 420,+ displayName: 'Mi Monitor',+ displayBounds: undefined,+ });+ expect(store.readAgentIslandDetachedLayoutPreferences()).toEqual([]);+});++it('preserves detached preferences during a single-display write', async () => {+ fs.writeFileSync(+ settingsFilePath(),+ JSON.stringify({+ displays: {+ 1: { compactContentWidth: 300 },+ },+ detachedDisplays: [+ {+ compactContentWidth: 500,+ centerXRatio: 0.25,+ displayName: 'Mi Monitor',+ displayInternal: false,+ displayBounds: { x: 1728, y: 0, width: 1512, height: 982 },+ },+ ],+ }),+ );+ const store = await import('../layoutPreferenceStore.js');++ store.writeAgentIslandLayoutPreference(1, { compactContentWidth: 320 });++ const persisted = JSON.parse(fs.readFileSync(settingsFilePath(), 'utf-8')) as {+ displays: Record<string, AgentIslandLayoutPreference>;+ detachedDisplays: AgentIslandLayoutPreference[];+ };+ expect(persisted.displays['1']).toEqual({ compactContentWidth: 320 });+ expect(persisted.detachedDisplays).toEqual([+ expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }),+ ]);+});++it('round-trips a complete active and detached preference snapshot', async () => {+ const store = await import('../layoutPreferenceStore.js');+ store.writeAgentIslandLayoutPreferences(+ new Map<number, AgentIslandLayoutPreference>([+ [+ 2,+ {+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ displayInternal: true,+ },+ ],+ ]),+ [+ {+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ displayInternal: false,+ },+ ],+ );+ vi.resetModules();+ const reloaded = await import('../layoutPreferenceStore.js');++ expect(reloaded.readAgentIslandLayoutPreferences().get(2)).toEqual(+ expect.objectContaining({+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ }),+ );+ expect(reloaded.readAgentIslandDetachedLayoutPreferences()).toEqual([+ expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }),+ ]);+});diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex 9dd27411ca..e513e21e41 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -74,7 +74,9 @@ const mocks = vi.hoisted(() => ({browserWindowFromWebContents: vi.fn(),browserWindowGetAllWindows: vi.fn<() => BrowserWindow[]>(() => []),readLayoutPreferences: vi.fn<() => Map<number, AgentIslandLayoutPreference>>(() => new Map()),+ readDetachedLayoutPreferences: vi.fn<() => AgentIslandLayoutPreference[]>(() => []),writeLayoutPreference: vi.fn(),+ writeLayoutPreferences: vi.fn(),tapWindowBroadcast: vi.fn(),showMessageBox: vi.fn(),openExternal: vi.fn(),@@ -120,8 +122,10 @@ vi.mock('../../localDb/ipc/sessions.js', () => ({}));vi.mock('../layoutPreferenceStore.js', () => ({+ readAgentIslandDetachedLayoutPreferences: mocks.readDetachedLayoutPreferences,readAgentIslandLayoutPreferences: mocks.readLayoutPreferences,writeAgentIslandLayoutPreference: mocks.writeLayoutPreference,+ writeAgentIslandLayoutPreferences: mocks.writeLayoutPreferences,}));vi.mock('../../device-link/broadcast-tap.js', () => ({@@ -157,7 +161,10 @@ beforeEach(() => {AGENT_ISLAND_DISPLAY_CONFIG.notifyOrcaWorkerSessions = false;mocks.readLayoutPreferences.mockReset();mocks.readLayoutPreferences.mockReturnValue(new Map());+ mocks.readDetachedLayoutPreferences.mockReset();+ mocks.readDetachedLayoutPreferences.mockReturnValue([]);mocks.writeLayoutPreference.mockReset();+ mocks.writeLayoutPreferences.mockReset();mocks.tapWindowBroadcast.mockReset();mocks.showMessageBox.mockReset();mocks.showMessageBox.mockResolvedValue({ response: 1, checkboxChecked: false });@@ -3932,6 +3939,89 @@ describe('AgentIslandService native publishing', () => {expect(framesById.get(2)).toMatchObject({ width: 460 });});+ it('does not reuse an identity-less compact width on a multi-display notch screen', async () => {+ mocks.readLayoutPreferences.mockReturnValueOnce(new Map<number, AgentIslandLayoutPreference>([+ [1, { compactContentWidth: 500, centerXRatio: 0.25 }],+ ]));+ const builtInDisplay = {+ id: 1,+ label: 'Built-in Retina Display',+ bounds: { x: 0, y: 0, width: 1728, height: 1117 },+ internal: false,+ };+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.displays.splice(0, mocks.displays.length, builtInDisplay, externalDisplay);++ 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 setNativeScreenMetrics = (+ service as unknown as {+ handleNativeScreenMetrics(metrics: {+ screens: Array<{+ displayId: number;+ frame: { x: number; y: number; width: number; height: number };+ hasNotch: boolean;+ notchWidth: number;+ topBarHeight: number;+ menuBarHeight: number;+ safeAreaTop: number;+ isMain: boolean;+ signature: string;+ }>;+ preferredDisplayId: number | null;+ }): void;+ }+ ).handleNativeScreenMetrics.bind(service);+ setNativeScreenMetrics({+ preferredDisplayId: 1,+ screens: [+ {+ displayId: 1,+ frame: builtInDisplay.bounds,+ hasNotch: true,+ notchWidth: 256,+ topBarHeight: 37,+ menuBarHeight: 37,+ safeAreaTop: 37,+ isMain: true,+ signature: 'builtin-notch',+ },+ {+ displayId: 2,+ frame: externalDisplay.bounds,+ hasNotch: false,+ notchWidth: 0,+ topBarHeight: 25,+ menuBarHeight: 25,+ safeAreaTop: 0,+ isMain: false,+ signature: 'external',+ },+ ],+ });++ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));+ expect(framesById.get(1)).toMatchObject({ x: 684, width: 360, contentWidth: 320 });+ expect(framesById.get(2)).toMatchObject({ width: 250, contentWidth: 210 });+ });+it('applies native layout preferences to the emitting display instead of the current target display', async () => {const { AgentIslandService } = await import('../service.js');const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {@@ -4008,12 +4098,727 @@ describe('AgentIslandService native publishing', () => {expect(mocks.writeLayoutPreference).toHaveBeenLastCalledWith(1, {compactContentWidth: 500,centerXRatio: 0.5,+ displayName: 'Built-in Retina Display',+ displayIndex: 1,+ displayInternal: false,+ displayBounds: mocks.primaryDisplay.bounds,});const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));expect(framesById.get(1)).toMatchObject({ width: 540, contentWidth: 500 });expect(framesById.get(2)).toMatchObject({ width: 360, contentWidth: 320 });});+ it('trusts matching native display ids when vertical frame coordinates differ', async () => {+ const lowerDisplay = {+ id: 1,+ label: 'Mi Monitor',+ bounds: { x: 0, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ const upperDisplay = {+ id: 2,+ label: 'Built-in Retina Display',+ bounds: { x: 0, y: -982, width: 1512, height: 982 },+ internal: true,+ };+ mocks.displays.splice(0, mocks.displays.length, lowerDisplay, upperDisplay);+ mocks.getPrimaryDisplay.mockReturnValue(lowerDisplay);++ 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 setNativeScreenMetrics = (+ service as unknown as {+ handleNativeScreenMetrics(metrics: {+ screens: Array<{+ displayId: number;+ frame: { x: number; y: number; width: number; height: number };+ hasNotch: boolean;+ notchWidth: number;+ topBarHeight: number;+ menuBarHeight: number;+ safeAreaTop: number;+ isMain: boolean;+ signature: string;+ }>;+ preferredDisplayId: number | null;+ }): void;+ }+ ).handleNativeScreenMetrics.bind(service);+ const setLayoutPreference = (+ service as unknown as {+ handleNativeLayoutPreference(preference: AgentIslandLayoutPreference): void;+ }+ ).handleNativeLayoutPreference.bind(service);++ setNativeScreenMetrics({+ preferredDisplayId: 2,+ screens: [+ {+ displayId: 1,+ frame: { x: 0, y: 0, width: 1512, height: 982 },+ hasNotch: false,+ notchWidth: 0,+ topBarHeight: 25,+ menuBarHeight: 25,+ safeAreaTop: 0,+ isMain: true,+ signature: 'lower',+ },+ {+ displayId: 2,+ frame: { x: 0, y: 982, width: 1512, height: 982 },+ hasNotch: true,+ notchWidth: 256,+ topBarHeight: 37,+ menuBarHeight: 37,+ safeAreaTop: 37,+ isMain: false,+ signature: 'upper-notch',+ },+ ],+ });+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const framesById = new Map(+ latestNativeFrames(publish).map((frame) => [frame.displayId, frame]),+ );+ expect(framesById.get(2)).toMatchObject({ contentWidth: 320 });++ setLayoutPreference({ displayId: 2, compactContentWidth: 500, centerXRatio: 0.5 });+ expect(mocks.writeLayoutPreference).toHaveBeenLastCalledWith(+ 2,+ expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Built-in Retina Display',+ }),+ );+ });++ it('remaps saved layout preferences by display identity when runtime ids change', async () => {+ mocks.readLayoutPreferences.mockReturnValueOnce(new Map<number, AgentIslandLayoutPreference>([+ [1, {+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ displayIndex: 2,+ displayInternal: false,+ displayBounds: { x: 1728, y: 0, width: 1512, height: 982 },+ }],+ ]));+ const builtInDisplay = {+ id: 1,+ label: 'Built-in Retina Display',+ bounds: { x: 0, y: 0, width: 1728, height: 1117 },+ internal: true,+ };+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.displays.splice(0, mocks.displays.length, builtInDisplay, externalDisplay);++ 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 setNativeScreenMetrics = (+ service as unknown as {+ handleNativeScreenMetrics(metrics: {+ screens: Array<{+ displayId: number;+ frame: { x: number; y: number; width: number; height: number };+ hasNotch: boolean;+ notchWidth: number;+ topBarHeight: number;+ menuBarHeight: number;+ safeAreaTop: number;+ isMain: boolean;+ signature: string;+ }>;+ preferredDisplayId: number | null;+ }): void;+ }+ ).handleNativeScreenMetrics.bind(service);+ setNativeScreenMetrics({+ preferredDisplayId: 1,+ screens: [+ {+ displayId: 1,+ frame: builtInDisplay.bounds,+ hasNotch: true,+ notchWidth: 256,+ topBarHeight: 37,+ menuBarHeight: 37,+ safeAreaTop: 37,+ isMain: true,+ signature: 'builtin-notch',+ },+ {+ displayId: 2,+ frame: externalDisplay.bounds,+ hasNotch: false,+ notchWidth: 0,+ topBarHeight: 25,+ menuBarHeight: 25,+ safeAreaTop: 0,+ isMain: false,+ signature: 'external',+ },+ ],+ });++ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));+ expect(framesById.get(1)).toMatchObject({ width: 360, contentWidth: 320 });+ expect(framesById.get(2)).toMatchObject({ width: 540, contentWidth: 500 });+ const persisted = mocks.writeLayoutPreferences.mock.calls.at(-1)?.[0] as Map<number, AgentIslandLayoutPreference> | undefined;+ expect(persisted?.get(2)).toEqual(expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }));+ expect(persisted?.has(1)).toBe(false);+ });++ it('moves exchanged display preferences as one atomic snapshot', async () => {+ const builtInDisplay = {+ id: 1,+ label: 'Built-in Retina Display',+ bounds: { x: 0, y: 0, width: 1728, height: 1117 },+ internal: false,+ };+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.readLayoutPreferences.mockReturnValueOnce(new Map<number, AgentIslandLayoutPreference>([+ [1, {+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ displayIndex: 2,+ displayInternal: false,+ displayBounds: externalDisplay.bounds,+ }],+ [2, {+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ displayIndex: 1,+ displayInternal: false,+ displayBounds: builtInDisplay.bounds,+ }],+ ]));+ mocks.displays.splice(0, mocks.displays.length, builtInDisplay, externalDisplay);++ 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 setNativeScreenMetrics = (+ service as unknown as {+ handleNativeScreenMetrics(metrics: {+ screens: Array<{+ displayId: number;+ frame: { x: number; y: number; width: number; height: number };+ hasNotch: boolean;+ notchWidth: number;+ topBarHeight: number;+ menuBarHeight: number;+ safeAreaTop: number;+ isMain: boolean;+ signature: string;+ }>;+ preferredDisplayId: number | null;+ }): void;+ }+ ).handleNativeScreenMetrics.bind(service);+ setNativeScreenMetrics({+ preferredDisplayId: 1,+ screens: [+ {+ displayId: 1,+ frame: builtInDisplay.bounds,+ hasNotch: true,+ notchWidth: 256,+ topBarHeight: 37,+ menuBarHeight: 37,+ safeAreaTop: 37,+ isMain: true,+ signature: 'builtin-notch',+ },+ {+ displayId: 2,+ frame: externalDisplay.bounds,+ hasNotch: false,+ notchWidth: 0,+ topBarHeight: 25,+ menuBarHeight: 25,+ safeAreaTop: 0,+ isMain: false,+ signature: 'external',+ },+ ],+ });++ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));+ expect(framesById.get(1)).toMatchObject({ width: 360, contentWidth: 320 });+ expect(framesById.get(2)).toMatchObject({ width: 540, contentWidth: 500 });+ expect(mocks.writeLayoutPreferences).toHaveBeenCalledTimes(1);+ const persisted = mocks.writeLayoutPreferences.mock.calls[0]?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(Array.from(persisted.keys())).toEqual([2, 1]);+ expect(persisted.get(1)).toEqual(expect.objectContaining({+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ }));+ expect(persisted.get(2)).toEqual(expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }));+ expect(mocks.writeLayoutPreferences.mock.calls[0]?.[1]).toEqual([]);+ });++ it('preserves a disconnected display preference when its old runtime id is reused', async () => {+ const externalBounds = { x: 1728, y: 0, width: 1512, height: 982 };+ mocks.readLayoutPreferences.mockReturnValueOnce(+ new Map<number, AgentIslandLayoutPreference>([+ [+ 1,+ {+ compactContentWidth: 500,+ centerXRatio: 0.25,+ displayName: 'Mi Monitor',+ displayIndex: 2,+ displayInternal: false,+ displayBounds: externalBounds,+ },+ ],+ [+ 2,+ {+ compactContentWidth: 300,+ centerXRatio: 0.5,+ displayName: 'Built-in Retina Display',+ displayIndex: 1,+ displayInternal: false,+ displayBounds: mocks.primaryDisplay.bounds,+ },+ ],+ ]),+ );+ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay);++ 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);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ let persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ let persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.get(1)).toEqual(+ expect.objectContaining({+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ }),+ );+ expect(persistedCall?.[1]).toEqual([+ expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }),+ ]);+ expect(latestNativeFrame(publish)).toMatchObject({ displayId: 1, contentWidth: 300 });++ const reconnectedDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: externalBounds,+ internal: false,+ };+ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay, reconnectedDisplay);+ service.handleUserPrompt({ sessionId: 's2', agentKind: 'codex' }, 'run more tests');++ persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.get(1)).toEqual(expect.objectContaining({ compactContentWidth: 300 }));+ expect(persisted.get(2)).toEqual(expect.objectContaining({ compactContentWidth: 500 }));+ expect(persistedCall?.[1]).toEqual([]);+ const framesById = new Map(+ latestNativeFrames(publish).map((frame) => [frame.displayId, frame]),+ );+ expect(framesById.get(1)).toMatchObject({ contentWidth: 300 });+ expect(framesById.get(2)).toMatchObject({ contentWidth: 500 });+ });++ it('restores a detached display preference when the display is connected at startup', async () => {+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.readDetachedLayoutPreferences.mockReturnValueOnce([+ {+ compactContentWidth: 500,+ centerXRatio: 0.25,+ displayName: 'Mi Monitor',+ displayIndex: 3,+ displayInternal: false,+ displayBounds: { x: 1000, y: 0, width: 1512, height: 982 },+ },+ ]);+ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay, externalDisplay);++ 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);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ const persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.get(2)).toEqual(+ expect.objectContaining({+ compactContentWidth: 500,+ displayBounds: externalDisplay.bounds,+ displayIndex: 2,+ displayName: 'Mi Monitor',+ }),+ );+ expect(persistedCall?.[1]).toEqual([]);+ const framesById = new Map(+ latestNativeFrames(publish).map((frame) => [frame.displayId, frame]),+ );+ expect(framesById.get(2)).toMatchObject({ contentWidth: 500 });+ });++ it('keeps an ambiguous preference detached when display order and bounds change', async () => {+ const firstExternal = {+ id: 1,+ label: 'Mi Monitor',+ bounds: { x: 0, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ const secondExternal = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1512, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.readLayoutPreferences.mockReturnValueOnce(+ new Map<number, AgentIslandLayoutPreference>([+ [+ 9,+ {+ compactContentWidth: 500,+ centerXRatio: 0.25,+ displayName: 'Mi Monitor',+ displayIndex: 2,+ displayInternal: false,+ displayBounds: { x: 1728, y: 0, width: 1512, height: 982 },+ },+ ],+ ]),+ );+ mocks.displays.splice(0, mocks.displays.length, firstExternal, secondExternal);+ mocks.getPrimaryDisplay.mockReturnValue(firstExternal);++ 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);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ const persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.size).toBe(0);+ expect(persistedCall?.[1]).toEqual([+ expect.objectContaining({+ compactContentWidth: 500,+ displayIndex: 2,+ displayName: 'Mi Monitor',+ }),+ ]);+ });++ it('moves a pending layout write into detached storage when the display disconnects', async () => {+ vi.useFakeTimers();+ try {+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay, externalDisplay);++ 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 setLayoutPreference = (+ service as unknown as {+ handleNativeLayoutPreference(preference: AgentIslandLayoutPreference): void;+ }+ ).handleNativeLayoutPreference.bind(service);+ const setLayoutDragActive = (+ service as unknown as {+ handleNativeLayoutDragActive(active: boolean): void;+ }+ ).handleNativeLayoutDragActive.bind(service);++ setLayoutDragActive(true);+ setLayoutPreference({ displayId: 2, compactContentWidth: 525, centerXRatio: 0.25 });+ expect(mocks.writeLayoutPreference).not.toHaveBeenCalled();++ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ const persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.has(2)).toBe(false);+ expect(persistedCall?.[1]).toEqual([+ expect.objectContaining({+ compactContentWidth: 525,+ centerXRatio: 0.25,+ displayName: 'Mi Monitor',+ }),+ ]);++ await vi.advanceTimersByTimeAsync(150);+ expect(mocks.writeLayoutPreference).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it('reconciles all connected displays while rendering only the selected display', async () => {+ const builtInDisplay = {+ id: 1,+ label: 'Built-in Retina Display',+ bounds: { x: 0, y: 0, width: 1728, height: 1117 },+ internal: false,+ };+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.readLayoutPreferences.mockReturnValueOnce(+ new Map<number, AgentIslandLayoutPreference>([+ [+ 1,+ {+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ displayIndex: 2,+ displayInternal: false,+ displayBounds: externalDisplay.bounds,+ },+ ],+ [+ 2,+ {+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ displayIndex: 1,+ displayInternal: false,+ displayBounds: builtInDisplay.bounds,+ },+ ],+ ]),+ );+ mocks.displays.splice(0, mocks.displays.length, builtInDisplay, externalDisplay);+ mocks.getPrimaryDisplay.mockReturnValue(builtInDisplay);++ 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 },+ });+ service.setDisplayTarget({ mode: 'display', displayId: 1 });+ syncEnabledForTest(service, publish);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ expect(latestNativeFrames(publish).map((frame) => frame.displayId)).toEqual([1]);+ const persistedCall = mocks.writeLayoutPreferences.mock.calls.at(-1);+ const persisted = persistedCall?.[0] as Map<number, AgentIslandLayoutPreference>;+ expect(persisted.get(1)).toEqual(+ expect.objectContaining({+ compactContentWidth: 300,+ displayName: 'Built-in Retina Display',+ }),+ );+ expect(persisted.get(2)).toEqual(+ expect.objectContaining({+ compactContentWidth: 500,+ displayName: 'Mi Monitor',+ }),+ );+ expect(persistedCall?.[1]).toEqual([]);+ });++ it('persists a pending layout write in the migrated snapshot without a stale single write', async () => {+ vi.useFakeTimers();+ try {+ const externalDisplay = {+ id: 2,+ label: 'Mi Monitor',+ bounds: { x: 1728, y: 0, width: 1512, height: 982 },+ internal: false,+ };+ mocks.displays.splice(0, mocks.displays.length, mocks.primaryDisplay, externalDisplay);++ 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 setLayoutPreference = (+ service as unknown as {+ handleNativeLayoutPreference(preference: AgentIslandLayoutPreference): void;+ }+ ).handleNativeLayoutPreference.bind(service);+ const setLayoutDragActive = (+ service as unknown as {+ handleNativeLayoutDragActive(active: boolean): void;+ }+ ).handleNativeLayoutDragActive.bind(service);++ setLayoutDragActive(true);+ setLayoutPreference({ displayId: 2, compactContentWidth: 500, centerXRatio: 0.25 });+ expect(mocks.writeLayoutPreference).not.toHaveBeenCalled();++ const reenumeratedExternal = { ...externalDisplay, id: 1 };+ const reenumeratedBuiltIn = { ...mocks.primaryDisplay, id: 2 };+ mocks.displays.splice(0, mocks.displays.length, reenumeratedExternal, reenumeratedBuiltIn);+ mocks.getPrimaryDisplay.mockReturnValue(reenumeratedBuiltIn);+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');++ const migrated = mocks.writeLayoutPreferences.mock.calls.at(-1)?.[0] as Map<+ number,+ AgentIslandLayoutPreference+ >;+ expect(migrated.get(1)).toEqual(+ expect.objectContaining({+ compactContentWidth: 500,+ displayIndex: 1,+ displayName: 'Mi Monitor',+ }),+ );+ expect(migrated.has(2)).toBe(false);++ await vi.advanceTimersByTimeAsync(150);+ expect(mocks.writeLayoutPreference).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });+it('re-publishes native frames when a wake refresh keeps the same screen signature', 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/geometry.ts b/apps/desktop/src/main/agent-island/geometry.tsindex 611ccb5a3b..7f90d8174e 100644--- a/apps/desktop/src/main/agent-island/geometry.ts+++ b/apps/desktop/src/main/agent-island/geometry.ts@@ -25,6 +25,13 @@ interface RectangleLike {height: number;}+export interface AgentIslandDisplayIdentity {+ displayName?: string | null;+ displayIndex?: number | null;+ displayInternal?: boolean | null;+ displayBounds?: RectangleLike | null;+}+export interface AgentIslandGeometryPreference {centerXRatio?: number | null;contentWidth?: number | null;@@ -33,7 +40,7 @@ export interface AgentIslandGeometryPreference {expandedClampContentWidth?: number | null;}-export interface AgentIslandLayoutPreference {+export interface AgentIslandLayoutPreference extends AgentIslandDisplayIdentity {displayId?: number | null;centerXRatio?: number | null;compactContentWidth?: number | null;diff --git a/apps/desktop/src/main/agent-island/layoutPreferenceStore.ts b/apps/desktop/src/main/agent-island/layoutPreferenceStore.tsindex ff94ed6f19..56046db7b2 100644--- a/apps/desktop/src/main/agent-island/layoutPreferenceStore.ts+++ b/apps/desktop/src/main/agent-island/layoutPreferenceStore.ts@@ -3,11 +3,11 @@ import fs from 'node:fs';import path from 'node:path';import { createLogger } from '../logger.js';-import type { AgentIslandLayoutPreference } from './geometry.js';+import type { AgentIslandLayoutPreference, AgentIslandDisplayIdentity } from './geometry.js';const log = createLogger('agent-island:layout-store');-interface StoredLayoutPreference {+interface StoredLayoutPreference extends AgentIslandDisplayIdentity {centerXRatio?: number;compactContentWidth?: number;expandedContentWidth?: number;@@ -15,10 +15,12 @@ interface StoredLayoutPreference {interface AgentIslandLayoutSettings {displays: Record<string, StoredLayoutPreference>;+ detachedDisplays: StoredLayoutPreference[];}const DEFAULTS: AgentIslandLayoutSettings = {displays: {},+ detachedDisplays: [],};let cached: AgentIslandLayoutSettings | null = null;@@ -35,19 +37,54 @@ function normalize(raw: unknown): AgentIslandLayoutSettings {if (!raw || typeof raw !== 'object') return { ...DEFAULTS };const record = raw as Record<string, unknown>;const rawDisplays = record.displays;- if (!rawDisplays || typeof rawDisplays !== 'object') return { ...DEFAULTS };const displays: Record<string, StoredLayoutPreference> = {};- for (const [displayId, value] of Object.entries(rawDisplays as Record<string, unknown>)) {- const normalized = normalizePreference(value);- if (normalized) displays[displayId] = normalized;+ if (rawDisplays && typeof rawDisplays === 'object' && !Array.isArray(rawDisplays)) {+ for (const [displayId, value] of Object.entries(rawDisplays as Record<string, unknown>)) {+ const normalized = normalizePreference(value);+ if (normalized) displays[displayId] = normalized;+ }}- return { displays };+ const detachedDisplays = Array.isArray(record.detachedDisplays)+ ? record.detachedDisplays+ .map(normalizePreference)+ .filter(+ (preference): preference is StoredLayoutPreference =>+ preference !== null && hasStoredDisplayIdentity(preference),+ )+ : [];+ return { displays, detachedDisplays };}function normalizePreference(raw: unknown): StoredLayoutPreference | null {if (!raw || typeof raw !== 'object') return null;const record = raw as Record<string, unknown>;const preference: StoredLayoutPreference = {};+ if (typeof record.displayName === 'string' && record.displayName.trim()) {+ preference.displayName = record.displayName.trim();+ }+ if (typeof record.displayIndex === 'number' && Number.isFinite(record.displayIndex)) {+ preference.displayIndex = record.displayIndex;+ }+ if (typeof record.displayInternal === 'boolean') {+ preference.displayInternal = record.displayInternal;+ }+ const rawBounds = record.displayBounds;+ if (rawBounds && typeof rawBounds === 'object') {+ const bounds = rawBounds as Record<string, unknown>;+ if (+ typeof bounds.x === 'number' && Number.isFinite(bounds.x)+ && typeof bounds.y === 'number' && Number.isFinite(bounds.y)+ && typeof bounds.width === 'number' && Number.isFinite(bounds.width)+ && typeof bounds.height === 'number' && Number.isFinite(bounds.height)+ ) {+ preference.displayBounds = {+ x: bounds.x,+ y: bounds.y,+ width: bounds.width,+ height: bounds.height,+ };+ }+ }if (typeof record.centerXRatio === 'number' && Number.isFinite(record.centerXRatio)) {preference.centerXRatio = record.centerXRatio;}@@ -60,6 +97,22 @@ function normalizePreference(raw: unknown): StoredLayoutPreference | null {return Object.keys(preference).length > 0 ? preference : null;}+function hasStoredDisplayIdentity(preference: StoredLayoutPreference): boolean {+ return (+ Boolean(preference.displayName?.trim()) ||+ typeof preference.displayIndex === 'number' ||+ typeof preference.displayInternal === 'boolean' ||+ preference.displayBounds !== undefined+ );+}++function clonePreference(preference: StoredLayoutPreference): AgentIslandLayoutPreference {+ return {+ ...preference,+ displayBounds: preference.displayBounds ? { ...preference.displayBounds } : undefined,+ };+}+function readSettings(): AgentIslandLayoutSettings {if (cached) return cached;const file = settingsFilePath();@@ -98,25 +151,54 @@ export function readAgentIslandLayoutPreferences(): Map<number, AgentIslandLayoufor (const [displayIdText, preference] of Object.entries(settings.displays)) {const displayId = Number(displayIdText);if (!Number.isFinite(displayId)) continue;- preferences.set(displayId, { ...preference });+ preferences.set(displayId, clonePreference(preference));}return preferences;}+export function readAgentIslandDetachedLayoutPreferences(): AgentIslandLayoutPreference[] {+ return readSettings().detachedDisplays.map(clonePreference);+}+export function writeAgentIslandLayoutPreference(displayId: number,preference: AgentIslandLayoutPreference,): void {if (!Number.isFinite(displayId)) return;+ const detachedPreferences = readAgentIslandDetachedLayoutPreferences();+ const next = readAgentIslandLayoutPreferences();const normalized = normalizePreference(preference);- const next: AgentIslandLayoutSettings = {- displays: { ...readSettings().displays },- };- const key = String(displayId);if (normalized) {- next.displays[key] = normalized;+ next.set(displayId, normalized);} else {- delete next.displays[key];+ next.delete(displayId);+ }+ writeAgentIslandLayoutPreferences(next, detachedPreferences);+}++/**+ * Replaces the complete per-display snapshot in one atomic file write.+ *+ * Display ids can be exchanged when macOS re-enumerates monitors. Updating+ * those entries one by one would overwrite the destination key before the+ * source preference is moved, so migrations must publish the final map as a+ * single snapshot.+ */+export function writeAgentIslandLayoutPreferences(+ preferences: Map<number, AgentIslandLayoutPreference>,+ detachedPreferences: readonly AgentIslandLayoutPreference[] = readAgentIslandDetachedLayoutPreferences(),+): void {+ const displays: Record<string, StoredLayoutPreference> = {};+ for (const [displayId, preference] of preferences) {+ if (!Number.isFinite(displayId)) continue;+ const normalized = normalizePreference(preference);+ if (normalized) displays[String(displayId)] = normalized;}- writeSettings(next);+ const detachedDisplays = detachedPreferences+ .map(normalizePreference)+ .filter(+ (preference): preference is StoredLayoutPreference =>+ preference !== null && hasStoredDisplayIdentity(preference),+ );+ writeSettings({ displays, detachedDisplays });}diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex afed5ce726..3209ea1529 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -98,6 +98,7 @@ import {} from './state.js';import { createLocalizedToolRowWording } from './toolWording.js';import {+ type AgentIslandDisplayIdentity,type AgentIslandLayoutPreference,computeAgentIslandCarrierSize,computeAgentIslandWindowBounds,@@ -109,8 +110,10 @@ import {} from './MacAgentIslandNativeHost.js';import { AGENT_ISLAND_DISPLAY_CONFIG } from './displayConfig.js';import {+ readAgentIslandDetachedLayoutPreferences,readAgentIslandLayoutPreferences,writeAgentIslandLayoutPreference,+ writeAgentIslandLayoutPreferences,} from './layoutPreferenceStore.js';import { throwIpcError } from '../utils/ipcValidate.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';@@ -231,6 +234,7 @@ export class AgentIslandService {}>();private readonly metadataLoading = new Set<string>();private readonly layoutPreferencesByDisplayId: Map<number, AgentIslandLayoutPreference>;+ private readonly detachedLayoutPreferences: AgentIslandLayoutPreference[];private nativeFailureLogged = false;private enabled = false;private enabledSynced = false;@@ -286,6 +290,7 @@ export class AgentIslandService {// lazy t() 闭包跟随 locale 运行时切换,注入一次即可(strings 仍每次 publish 重建)。setAgentIslandToolWording(this.state, createLocalizedToolRowWording());this.layoutPreferencesByDisplayId = readAgentIslandLayoutPreferences();+ this.detachedLayoutPreferences = readAgentIslandDetachedLayoutPreferences();this.nativeHost = deps.nativeHost ?? new MacAgentIslandNativeHost({onPointerZones: (zones) => this.handleNativePointerZones(zones),onExpand: (displayId) => this.handleNativeExpand(displayId),@@ -1578,11 +1583,19 @@ export class AgentIslandService {}private handleNativeLayoutPreference(preference: AgentIslandLayoutPreference): void {- const displayId = typeof preference.displayId === 'number' && Number.isFinite(preference.displayId)+ const displays = this.getAvailableDisplays();+ this.reconcileLayoutPreferencesForDisplays(displays);+ const nativeDisplayId = typeof preference.displayId === 'number' && Number.isFinite(preference.displayId)? preference.displayId- : this.getTargetDisplay().id;+ : this.getTargetDisplay(displays).id;+ const display = this.displayForNativeId(nativeDisplayId, displays);+ if (!display) return;+ const displayId = display.id;const current = this.layoutPreferencesByDisplayId.get(displayId) ?? {};- const next: AgentIslandLayoutPreference = { ...current };+ const next: AgentIslandLayoutPreference = {+ ...current,+ ...(display ? this.displayIdentityForDisplay(display, displays) : {}),+ };if (typeof preference.centerXRatio === 'number' && Number.isFinite(preference.centerXRatio)) {next.centerXRatio = preference.centerXRatio;}@@ -1596,6 +1609,10 @@ export class AgentIslandService {next.centerXRatio === current.centerXRatio&& next.compactContentWidth === current.compactContentWidth&& next.expandedContentWidth === current.expandedContentWidth+ && next.displayName === current.displayName+ && next.displayIndex === current.displayIndex+ && next.displayInternal === current.displayInternal+ && sameDisplayBounds(next.displayBounds, current.displayBounds)) {return;}@@ -1673,7 +1690,9 @@ export class AgentIslandService {frames: AgentIslandNativeFrame[];statesByDisplayId?: Record<string, AgentIslandDisplayState>;} {- const displays = this.getTargetDisplays();+ const availableDisplays = this.getAvailableDisplays();+ this.reconcileLayoutPreferencesForDisplays(availableDisplays);+ const displays = this.getTargetDisplays(availableDisplays);const statesByDisplayId = this.computeDisplayStatesByDisplayId(displayState, displays);const frames = displays.map((display) => {const stateForDisplay = statesByDisplayId?.[String(display.id)] ?? displayState;@@ -1705,7 +1724,7 @@ export class AgentIslandService {private computeNativeFrame(displayState: AgentIslandDisplayState, display: Display): AgentIslandNativeFrame {const rawScreenMetrics = this.getScreenLayoutMetrics(display);- const layoutPreference = this.layoutPreferencesByDisplayId.get(display.id) ?? {};+ const layoutPreference = this.getLayoutPreferenceForDisplay(display);const expanded = displayState.notchStatus === 'expanded';const hasSession = displayState.totalCount > 0;const screenMetrics = this.getEffectiveScreenLayoutMetrics({@@ -1784,8 +1803,7 @@ export class AgentIslandService {};}- private getTargetDisplays(): Display[] {- const displays = this.getAvailableDisplays();+ private getTargetDisplays(displays = this.getAvailableDisplays()): Display[] {if (this.displayTarget.mode === 'display') {const selectedDisplay = this.resolveSelectedDisplay(displays);if (!selectedDisplay) {@@ -1802,6 +1820,178 @@ export class AgentIslandService {return displays;}+ private getLayoutPreferenceForDisplay(display: Display): AgentIslandLayoutPreference {+ const preference = this.layoutPreferencesByDisplayId.get(display.id);+ if (!preference) return {};+ if (hasPersistedLayoutIdentity(preference)) return preference;++ // 0.1.31 and earlier stored only the runtime display id. On a multi-display+ // setup that id can be reused by another monitor, so an old wide compact+ // width and center are unsafe to apply to a centered hardware-notch+ // display. Preserve the expanded preference, but let compact layout derive+ // its current notch-safe defaults until the next native drag records identity.+ const displays = this.getAvailableDisplays();+ const metrics = this.getScreenLayoutMetrics(display);+ if (displays.length > 1 && metrics?.hasNotch) {+ return {+ ...preference,+ centerXRatio: undefined,+ compactContentWidth: undefined,+ };+ }+ return preference;+ }++ private reconcileLayoutPreferencesForDisplays(displays: Display[]): void {+ const entries = Array.from(this.layoutPreferencesByDisplayId.entries());+ if (+ (entries.length === 0 && this.detachedLayoutPreferences.length === 0) ||+ displays.length === 0+ )+ return;++ const next = new Map<number, AgentIslandLayoutPreference>();+ const nextDetached: AgentIslandLayoutPreference[] = [];+ const claimedDisplayIds = new Set<number>();+ const assignedPreferences = new Set<AgentIslandLayoutPreference>();+ const identityEntries = [+ ...entries+ .filter(([, preference]) => hasPersistedLayoutIdentity(preference))+ .map(([storedDisplayId, preference]) => ({ storedDisplayId, preference })),+ ...this.detachedLayoutPreferences.map((preference) => ({+ storedDisplayId: null,+ preference,+ })),+ ];++ // Keep an identity-bearing preference on its current id when the identity+ // still resolves there. This is the common case and also makes collisions+ // deterministic before looking for migrated ids.+ for (const { storedDisplayId, preference } of identityEntries) {+ if (storedDisplayId === null) continue;+ const direct = this.displayById(displays, storedDisplayId);+ const resolved = findDisplayByIdentity(displays, preference);+ if (!direct || !resolved || resolved.id !== direct.id) continue;+ next.set(direct.id, {+ ...preference,+ ...this.displayIdentityForDisplay(direct, displays),+ });+ claimedDisplayIds.add(direct.id);+ assignedPreferences.add(preference);+ }++ // Resolve the remaining identity-bearing entries as a one-to-one batch.+ // Do not mutate the live map while iterating: two exchanged runtime ids+ // must be able to swap without one migration overwriting the other.+ for (const { preference } of identityEntries) {+ if (assignedPreferences.has(preference)) continue;+ const resolved = findDisplayByIdentity(displays, preference);+ if (!resolved || claimedDisplayIds.has(resolved.id)) continue;+ next.set(resolved.id, {+ ...preference,+ ...this.displayIdentityForDisplay(resolved, displays),+ });+ claimedDisplayIds.add(resolved.id);+ assignedPreferences.add(preference);+ }++ // Identity-bearing preferences that cannot currently resolve remain+ // detached from runtime ids. This preserves a disconnected display even+ // when another online display reuses its previous id.+ for (const { preference } of identityEntries) {+ if (!assignedPreferences.has(preference)) {+ nextDetached.push(preference);+ }+ }++ // Keep old id-only entries for backwards compatibility when their id still+ // names an unclaimed display. If an identity-bearing entry already claims+ // that id, the ambiguous legacy value must not overwrite the safer match.+ for (const [storedDisplayId, preference] of entries) {+ if (hasPersistedLayoutIdentity(preference)) continue;+ const direct = this.displayById(displays, storedDisplayId);+ if (direct && !claimedDisplayIds.has(direct.id)) {+ next.set(direct.id, preference);+ claimedDisplayIds.add(direct.id);+ continue;+ }+ // Keep disconnected legacy entries so a future display with the same id+ // can still use the old preference; no physical identity exists to do a+ // safer reconnect migration yet.+ if (!direct && !next.has(storedDisplayId)) {+ next.set(storedDisplayId, preference);+ }+ }++ if (+ sameLayoutPreferenceMap(this.layoutPreferencesByDisplayId, next) &&+ sameLayoutPreferenceList(this.detachedLayoutPreferences, nextDetached)+ ) {+ return;+ }+ this.clearPendingLayoutPreferenceWrites();+ this.layoutPreferencesByDisplayId.clear();+ for (const [displayId, preference] of next) {+ this.layoutPreferencesByDisplayId.set(displayId, preference);+ }+ this.detachedLayoutPreferences.splice(+ 0,+ this.detachedLayoutPreferences.length,+ ...nextDetached,+ );+ this.writeLayoutPreferencesSafely(next, nextDetached);+ }++ private clearPendingLayoutPreferenceWrites(): void {+ this.pendingLayoutPreferenceWrites.clear();+ if (this.layoutPreferenceWriteTimer) {+ clearTimeout(this.layoutPreferenceWriteTimer);+ this.layoutPreferenceWriteTimer = null;+ }+ }++ private writeLayoutPreferencesSafely(+ preferences: Map<number, AgentIslandLayoutPreference>,+ detachedPreferences: readonly AgentIslandLayoutPreference[],+ ): void {+ try {+ writeAgentIslandLayoutPreferences(preferences, detachedPreferences);+ } catch (error) {+ log.warn('agent island layout preferences migration write failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ private displayForNativeId(displayId: number | null, displays: Display[]): Display | null {+ if (typeof displayId !== 'number' || !Number.isFinite(displayId)) return null;+ const direct = this.displayById(displays, displayId);+ // AppKit and Electron expose the same system display id, while their frame+ // coordinates use different vertical origins. A matching id is therefore+ // stronger evidence than a full-bounds comparison.+ if (direct) return direct;+ const metrics = this.screenMetricsByDisplayId.get(displayId);+ if (!metrics) return null;+ const exactBounds = displays.filter((display) => sameDisplayBounds(display.bounds, metrics.frame));+ if (exactBounds.length === 1) return exactBounds[0] ?? null;+ const sameSize = displays.filter((display) => (+ display.bounds.width === metrics.frame.width+ && display.bounds.height === metrics.frame.height+ ));+ return sameSize.length === 1 ? (sameSize[0] ?? null) : null;+ }++ private displayIdentityForDisplay(display: Display, displays: Display[]): AgentIslandDisplayIdentity {+ return {+ displayName: typeof display.label === 'string' && display.label.trim()+ ? display.label.trim()+ : undefined,+ displayIndex: displays.findIndex((item) => item.id === display.id) + 1,+ displayInternal: Boolean(display.internal),+ displayBounds: { ...display.bounds },+ };+ }+private resolveSelectedDisplay(displays: Display[]): Display | null {if (this.displayTarget.mode !== 'display') return null;if (hasPersistedDisplayIdentity(this.displayTarget)) {@@ -1832,44 +2022,7 @@ export class AgentIslandService {displays: Display[],target: Extract<AgentIslandDisplayTarget, { mode: 'display' }>,): Display | null {- let candidates = displays;- const name = target.displayName?.trim();- if (name) {- candidates = candidates.filter((display) => (- typeof display.label === 'string' && display.label.trim() === name- ));- }-- if (typeof target.displayInternal === 'boolean') {- candidates = candidates.filter((display) => (- Boolean(display.internal) === target.displayInternal- ));- }-- const persistedBounds = target.displayBounds;- if (persistedBounds) {- const exactBounds = candidates.filter((display) => (- sameDisplayBounds(display.bounds, persistedBounds)- ));- if (exactBounds.length === 1) return exactBounds[0] ?? null;- if (exactBounds.length > 1) {- candidates = exactBounds;- } else {- const sameSize = candidates.filter((display) => (- display.bounds.width === persistedBounds.width- && display.bounds.height === persistedBounds.height- ));- if (sameSize.length === 1) return sameSize[0] ?? null;- if (sameSize.length > 1) candidates = sameSize;- }- }-- if (typeof target.displayIndex === 'number' && target.displayIndex >= 1) {- const byIndex = displays[target.displayIndex - 1];- if (byIndex && candidates.includes(byIndex)) return byIndex;- }-- return candidates.length === 1 ? (candidates[0] ?? null) : null;+ return findDisplayByIdentity(displays, target);}private normalizePreferredContentWidth(input: {@@ -1905,7 +2058,7 @@ export class AgentIslandService {const mainWindowDisplay = mainWindow && !mainWindow.isDestroyed()? screen.getDisplayMatching(mainWindow.getBounds()): null;- const nativePreferred = this.displayById(displays, this.nativePreferredDisplayId);+ const nativePreferred = this.displayForNativeId(this.nativePreferredDisplayId, displays);if (AGENT_ISLAND_DISPLAY_CONFIG.selectionMode === 'native-preferred-then-xdmaker-window') {if (nativePreferred) return nativePreferred;if (mainWindowDisplay) return mainWindowDisplay;@@ -1915,7 +2068,7 @@ export class AgentIslandService {if (nativePreferred) return nativePreferred;}if (AGENT_ISLAND_DISPLAY_CONFIG.preferHardwareNotchFallback) {- const notchDisplay = displays.find((display) => this.screenMetricsByDisplayId.get(display.id)?.hasNotch);+ const notchDisplay = displays.find((display) => this.screenMetricsForDisplay(display)?.hasNotch);if (notchDisplay) return notchDisplay;}if (AGENT_ISLAND_DISPLAY_CONFIG.preferInternalDisplayFallback) {@@ -1953,7 +2106,7 @@ export class AgentIslandService {}private getScreenLayoutMetrics(display: Display): AgentIslandScreenLayoutMetrics | null {- const metrics = this.screenMetricsByDisplayId.get(display.id);+ const metrics = this.screenMetricsForDisplay(display);if (!metrics) return null;return {hasNotch: metrics.hasNotch,@@ -1961,6 +2114,21 @@ export class AgentIslandService {};}+ private screenMetricsForDisplay(display: Display): AgentIslandNativeScreenMetrics | null {+ const direct = this.screenMetricsByDisplayId.get(display.id);+ if (direct) return direct;+ const exactBounds = Array.from(this.screenMetricsByDisplayId.values()).filter((metrics) => (+ sameDisplayBounds(display.bounds, metrics.frame)+ ));+ if (exactBounds.length === 1) return exactBounds[0] ?? null;+ const sameSize = Array.from(this.screenMetricsByDisplayId.values()).filter((metrics) => (+ metrics.frame.width === display.bounds.width+ && metrics.frame.height === display.bounds.height+ ));+ if (sameSize.length === 1) return sameSize[0] ?? null;+ return null;+ }+private getEffectiveScreenLayoutMetrics(input: {display: Display;expanded: boolean;@@ -2164,10 +2332,97 @@ function hasPersistedDisplayIdentity(|| target.displayBounds !== undefined;}+function hasPersistedLayoutIdentity(preference: AgentIslandLayoutPreference): boolean {+ return Boolean(preference.displayName?.trim())+ || typeof preference.displayIndex === 'number'+ || typeof preference.displayInternal === 'boolean'+ || preference.displayBounds !== undefined;+}++function findDisplayByIdentity(+ displays: Display[],+ identity: AgentIslandDisplayIdentity,+): Display | null {+ let candidates = displays;+ const name = identity.displayName?.trim();+ if (name) {+ candidates = candidates.filter((display) => (+ typeof display.label === 'string' && display.label.trim() === name+ ));+ }++ if (typeof identity.displayInternal === 'boolean') {+ candidates = candidates.filter((display) => (+ Boolean(display.internal) === identity.displayInternal+ ));+ }++ const persistedBounds = identity.displayBounds;+ if (persistedBounds) {+ const exactBounds = candidates.filter((display) => (+ sameDisplayBounds(display.bounds, persistedBounds)+ ));+ if (exactBounds.length === 1) return exactBounds[0] ?? null;+ if (exactBounds.length > 1) {+ candidates = exactBounds;+ } else {+ const sameSize = candidates.filter((display) => (+ display.bounds.width === persistedBounds.width+ && display.bounds.height === persistedBounds.height+ ));+ if (sameSize.length === 1) return sameSize[0] ?? null;+ if (sameSize.length > 1) candidates = sameSize;+ }+ }++ // Display enumeration order is runtime-local and may change after reconnect,+ // reboot, or topology changes. An index must never break an otherwise+ // ambiguous physical-identity match; failing closed keeps the preference+ // detached instead of assigning it to the wrong monitor.+ return candidates.length === 1 ? (candidates[0] ?? null) : null;+}++function sameLayoutPreferenceMap(+ a: Map<number, AgentIslandLayoutPreference>,+ b: Map<number, AgentIslandLayoutPreference>,+): boolean {+ if (a.size !== b.size) return false;+ for (const [displayId, preference] of a) {+ const other = b.get(displayId);+ if (!other || !sameLayoutPreference(preference, other)) return false;+ }+ return true;+}++function sameLayoutPreferenceList(+ a: readonly AgentIslandLayoutPreference[],+ b: readonly AgentIslandLayoutPreference[],+): boolean {+ return (+ a.length === b.length &&+ a.every((preference, index) => sameLayoutPreference(preference, b[index] ?? {}))+ );+}++function sameLayoutPreference(+ a: AgentIslandLayoutPreference,+ b: AgentIslandLayoutPreference,+): boolean {+ return a.displayId === b.displayId+ && a.centerXRatio === b.centerXRatio+ && a.compactContentWidth === b.compactContentWidth+ && a.expandedContentWidth === b.expandedContentWidth+ && a.displayName === b.displayName+ && a.displayIndex === b.displayIndex+ && a.displayInternal === b.displayInternal+ && sameDisplayBounds(a.displayBounds, b.displayBounds);+}+function sameDisplayBounds(- a: { x: number; y: number; width: number; height: number },- b: { x: number; y: number; width: number; height: number },+ a: { x: number; y: number; width: number; height: number } | null | undefined,+ b: { x: number; y: number; width: number; height: number } | null | undefined,): boolean {+ if (!a || !b) return a === b;return a.x === b.x&& a.y === b.y&& a.width === b.width