Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(test): preserve startup and native regression contracts
MagicLizie4c61a80a88c
diff --git a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.tsindex 2d4ef7527b..5d12562c41 100644--- a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts@@ -13,7 +13,6 @@ import {createEmptyAgentIslandPillSnapshot,type AgentIslandDisplayState,} from '../../../shared/agentIsland.js';-import { CLAUDE_CODE_MARK_PATH, CODEX_FLOWER_OUTLINE, CODEX_PROMPT_GLYPHS } from '../../../shared/brandMarkPaths.js';import type { AgentIslandNativeFrame } from '../MacAgentIslandNativeHost.js';const h = vi.hoisted(() => ({@@ -71,132 +70,6 @@ afterEach(() => {});describe('MacAgentIslandNativeHost', () => {- it('renders the idle brand from main-provided display strings', () => {- const sourceUrl = new URL(- '../../../../native/agent-island/macos-agent-island-helper.swift',- import.meta.url,- );- if (!fs.existsSync(sourceUrl)) {- throw new Error(`macos-agent-island-helper.swift 未找到: ${sourceUrl.pathname}`);- }- const source = fs.readFileSync(sourceUrl, 'utf8');-- expect(source).toContain('Text(strings.displayAppName)');- expect(source).not.toContain('Text("XD Maker")');- });-- it('keeps the native panel nonactivating during pointer interaction', () => {- const sourceUrl = new URL(- '../../../../native/agent-island/macos-agent-island-helper.swift',- import.meta.url,- );- const source = fs.readFileSync(sourceUrl, 'utf8');-- expect(source).toContain('styleMask: [.borderless, .nonactivatingPanel]');- expect(source).toContain('override var canBecomeKey: Bool { false }');- expect(source).toContain('override var canBecomeMain: Bool { false }');- expect(source).not.toContain('makeKey()');- });-- it('refreshes native display metrics after macOS wakes from sleep', () => {- const source = fs.readFileSync(- new URL('../../../../native/agent-island/macos-agent-island-helper.swift', import.meta.url),- 'utf8',- );-- const wakeObserver = source.match(- /workspaceWakeObserver\s*=\s*NSWorkspace\.shared\.notificationCenter\.addObserver\(\s*forName:\s*NSWorkspace\.didWakeNotification,[\s\S]*?self\?\.scheduleScreenMetricsPublish\(forceRefresh:\s*true\)\s*\n\s*}/,- )?.[0];-- expect(wakeObserver).toBeTruthy();- expect(wakeObserver).toContain('NSWorkspace.didWakeNotification');- expect(wakeObserver).toContain('scheduleScreenMetricsPublish(forceRefresh: true)');- expect(source).toContain('payload["forceRefresh"] = true');- });-- it('keeps native Agent marks aligned with the renderer icons', () => {- const nativeSource = fs.readFileSync(- new URL('../../../../native/agent-island/macos-agent-island-helper.swift', import.meta.url),- 'utf8',- );- const claudeSource = fs.readFileSync(- new URL('../../../renderer/components/icons/ClaudeMark.tsx', import.meta.url),- 'utf8',- );- const codexSource = fs.readFileSync(- new URL('../../../renderer/components/icons/CodexMark.tsx', import.meta.url),- 'utf8',- );- // The renderer icons draw these shared paths; the native helper must carry the same ones.- expect(claudeSource).toContain('d={CLAUDE_CODE_MARK_PATH}');- expect(codexSource).toContain('d={`${CODEX_FLOWER_OUTLINE}z`}');- expect(codexSource).toContain('d={CODEX_PROMPT_GLYPHS}');- const claudePath = CLAUDE_CODE_MARK_PATH;- const codexOutline = CODEX_FLOWER_OUTLINE;- const codexPrompt = CODEX_PROMPT_GLYPHS;- const codexSmallStrokeWidth = codexSource.match(- /const monoStrokeWidth = size <= 14 \? ([\d.]+) : [\d.]+;/,- )?.[1];- const nativeCodexSvg = nativeSource.match(- /private let agentIslandCodexMarkSVG = """([\s\S]*?)"""/,- )?.[1];- const nativeCodexOutlineStrokeWidth = nativeCodexSvg?.match(- /<path fill="none" stroke="black" stroke-width="([^"]+)"/,- )?.[1];-- expect(claudePath).toBeTruthy();- expect(codexOutline).toBeTruthy();- expect(codexPrompt).toBeTruthy();- expect(codexSmallStrokeWidth).toBeTruthy();- expect(nativeCodexOutlineStrokeWidth).toBeTruthy();- expect(nativeSource).toContain(`d="${claudePath}"`);- expect(nativeSource).toContain(`d="${codexOutline}z"`);- expect(nativeSource).toContain(`d="${codexPrompt}"`);- expect(nativeCodexOutlineStrokeWidth).toBe(codexSmallStrokeWidth);- expect(nativeSource).not.toContain('agentIslandXDIncMarkSVG');- });-- it('renders Pi sessions with the Pi mark instead of the Claude mark', () => {- const source = fs.readFileSync(- new URL('../../../../native/agent-island/macos-agent-island-helper.swift', import.meta.url),- 'utf8',- );- const vendorResolver = source.match(- /func agentIslandSessionVendor\(for session: AgentIslandSession\) -> AgentIslandSessionVendor \{([\s\S]*?)\n\}/,- )?.[1];- const markImageResolver = source.match(- /func image\(for vendor: AgentIslandSessionVendor\) -> NSImage\? \{([\s\S]*?)\n \}/,- )?.[1];-- expect(source).toContain('case pi');- expect(vendorResolver).toContain('if kind == "pi" { return .pi }');- expect(markImageResolver).toContain('case .pi:');- expect(markImageResolver).toContain('svg = agentIslandPiMarkSVG');- expect(source).toContain('private let agentIslandPiMarkSVG = """');- expect(source).toContain('<path d="M3.6 6.6h16.8"/>');- expect(source).toContain('<path d="M8.4 6.6v11.8"/>');- expect(source).toContain('<path d="M15.6 6.6v9.6c0 1.5.9 2.2 2.4 2.2"/>');- expect(source).toContain('if lower == "pi" { return "Pi" }');- });-- it('uses semantic icons for expanded terminal and interaction rows', () => {- const source = fs- .readFileSync(- new URL('../../../../native/agent-island/macos-agent-island-helper.swift', import.meta.url),- 'utf8',- )- // Windows CRLF 检出下 \n 字面量正则会失配,统一归一化成 LF 再匹配。- .replace(/\r\n/g, '\n');- const expandedHeader = source.match(- /struct ExpandedSessionHeaderLine: View \{([\s\S]*?)\n\}\n\nstruct ExpandedSessionMetaLine/,- )?.[1];-- expect(expandedHeader).toBeTruthy();- expect(expandedHeader).toContain('case "needs-interaction", "completed":');- expect(expandedHeader).toContain('return false');- expect(expandedHeader).toContain('showsRunningAnimation: showsMascot');- });-it('restarts the helper when it exits before ready', async () => {const children: FakeNativeProcess[] = [];h.spawn.mockImplementation(() => {diff --git a/apps/desktop/src/main/agent-island/__tests__/nativeContracts.test.ts b/apps/desktop/src/main/agent-island/__tests__/nativeContracts.test.tsnew file mode 100644index 0000000000..5921bb2f6b--- /dev/null+++ b/apps/desktop/src/main/agent-island/__tests__/nativeContracts.test.ts@@ -0,0 +1,52 @@+// Native helper contract tier: Swift cannot be imported by the JS host tests.+// Preserve cross-runtime display/protocol, focus ownership and wake-refresh+// contracts here; process recovery remains in MacAgentIslandNativeHost.test.ts.+// Minimal failures are missing native protocol fields, activation or stale metrics.+import fs from 'node:fs';+import { describe, expect, it } from 'vitest';++describe('Agent Island native contracts', () => {+ it('renders the idle brand from main-provided display strings', () => {+ const sourceUrl = new URL(+ '../../../../native/agent-island/macos-agent-island-helper.swift',+ import.meta.url,+ );+ if (!fs.existsSync(sourceUrl)) {+ throw new Error(`macos-agent-island-helper.swift 未找到: ${sourceUrl.pathname}`);+ }+ const source = fs.readFileSync(sourceUrl, 'utf8');++ expect(source).toContain('Text(strings.displayAppName)');+ expect(source).not.toContain('Text("XD Maker")');+ });++ it('keeps the native panel nonactivating during pointer interaction', () => {+ const sourceUrl = new URL(+ '../../../../native/agent-island/macos-agent-island-helper.swift',+ import.meta.url,+ );+ const source = fs.readFileSync(sourceUrl, 'utf8');++ expect(source).toContain('styleMask: [.borderless, .nonactivatingPanel]');+ expect(source).toContain('override var canBecomeKey: Bool { false }');+ expect(source).toContain('override var canBecomeMain: Bool { false }');+ expect(source).not.toContain('makeKey()');+ });++ it('refreshes native display metrics after macOS wakes from sleep', () => {+ const source = fs.readFileSync(+ new URL('../../../../native/agent-island/macos-agent-island-helper.swift', import.meta.url),+ 'utf8',+ );++ const wakeObserver = source.match(+ /workspaceWakeObserver\s*=\s*NSWorkspace\.shared\.notificationCenter\.addObserver\(\s*forName:\s*NSWorkspace\.didWakeNotification,[\s\S]*?self\?\.scheduleScreenMetricsPublish\(forceRefresh:\s*true\)\s*\n\s*}/,+ )?.[0];++ expect(wakeObserver).toBeTruthy();+ expect(wakeObserver).toContain('NSWorkspace.didWakeNotification');+ expect(wakeObserver).toContain('scheduleScreenMetricsPublish(forceRefresh: true)');+ expect(source).toContain('payload["forceRefresh"] = true');+ });++});diff --git a/apps/desktop/src/main/im/__tests__/startupDefaultRouteBackfill.test.ts b/apps/desktop/src/main/im/__tests__/startupDefaultRouteBackfill.test.tsnew file mode 100644index 0000000000..8c76d612c4--- /dev/null+++ b/apps/desktop/src/main/im/__tests__/startupDefaultRouteBackfill.test.ts@@ -0,0 +1,86 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++// PR #5155: an upgraded user who never saves channel settings still needs+// legacy-route backfill at startImConnection. The existing SQLite tests cover+// backfill persistence, but never call this startup entry. Use pending backfill+// and lifecycle ports to observe ordering without loading real transports/DBs.+// A separate unit file keeps the index singleton and channel mocks isolated+// from the existing pure lifecycle tests. The module is imported only once.+const h = vi.hoisted(() => ({+ events: [] as string[],+ started: false,+ relaunching: false,+ db: { owner: 'fake-startup-owner' },+ config: { agentKind: 'claude-code', defaultModel: 'test-model' },+ finishBackfill: (() => undefined) as () => void,+ backfill: vi.fn(),+}));++vi.mock('../../localDb/client/current', () => ({ getDbClient: () => h.db }));+vi.mock('../../maker-ipc/sessionRuntimeControl.js', () => ({}));+vi.mock('../host', () => ({}));+vi.mock('../feishu', () => ({}));+vi.mock('../discord', () => ({}));+vi.mock('../telegram', () => ({}));+vi.mock('../dingtalk', () => ({}));+vi.mock('../wechat', () => ({}));+vi.mock('../wecom', () => ({}));+vi.mock('../telegram/groupWindow', () => ({}));+vi.mock('../shared/orchestrator', () => ({+ getImOrchestrator: (source: string) => source === 'feishu' ? { adapter: { config: h.config } } : undefined,+}));+vi.mock('../shared/channelDefaultRouteSync', () => ({+ backfillLegacyImDefaultRoutesAtStartup: h.backfill,+}));+vi.mock('../connectionLifecycle', () => ({+ createSerializedConnectionLifecycle: () => ({+ isStarted: () => h.started,+ start: () => { h.events.push('connect'); h.started = true; },+ }),+}));+vi.mock('../accountBoundary', () => ({ captureImAccountGeneration: vi.fn() }));+vi.mock('../accountScopeBridge', () => ({ configureImAccountScope: vi.fn() }));+vi.mock('../binding', () => ({}));+vi.mock('../../authManager', () => ({}));+vi.mock('../../updateService', () => ({+ isUpdateRelaunchImminent: () => h.relaunching,+ getUpdateStatus: () => 'ready',+}));+vi.mock('../../logger', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../security/trustedAppRenderer', () => ({}));+vi.mock('../wechat/channelSettings', () => ({}));++import { startImConnection } from '../index';++beforeEach(() => {+ h.events.length = 0;+ h.started = false;+ h.relaunching = false;+ h.backfill.mockReset().mockImplementation(() => {+ h.events.push('backfill');+ return new Promise<void>((resolve) => { h.finishBackfill = resolve; });+ });+});++describe('IM startup legacy route backfill', () => {+ it('starts backfill with current channel config and DB before connecting, without waiting for it', async () => {+ startImConnection();+ expect(h.events).toEqual(['backfill', 'connect']);+ expect(h.backfill).toHaveBeenCalledWith([{ source: 'feishu', config: h.config }], h.db);+ // A repeated ready signal must not launch another backfill or connection.+ startImConnection();+ expect(h.backfill).toHaveBeenCalledOnce();+ expect(h.events).toEqual(['backfill', 'connect']);+ h.finishBackfill();+ await h.backfill.mock.results[0].value;+ });++ it('leaves both startup operations untouched while an update relaunch is imminent', () => {+ h.relaunching = true;+ startImConnection();+ expect(h.events).toEqual([]);+ expect(h.backfill).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.tsindex 453c595dd8..b3e991e5e6 100644--- a/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts@@ -1,6 +1,5 @@import type { ChildProcessWithoutNullStreams } from 'node:child_process';import { EventEmitter } from 'node:events';-import { readFileSync } from 'node:fs';import { PassThrough } from 'node:stream';import path from 'node:path';import { describe, expect, it, vi } from 'vitest';@@ -340,90 +339,3 @@ describe('XboxGamepadHost', () => {expect(onMessage).not.toHaveBeenCalled();});});--describe('Xbox gamepad helper packaging contract', () => {- it('starts Windows input and ships a native helper for the requested architecture', () => {- const index = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');- const forge = readFileSync(new URL('../../../../forge.config.ts', import.meta.url), 'utf8');- expect(index).toContain("process.platform === 'darwin' || process.platform === 'win32'");- expect(forge).toContain('buildWindowsGamepadHelper(platform, arch)');- expect(forge).toContain('aarch64-pc-windows-msvc');- expect(forge).toContain('x86_64-pc-windows-msvc');- expect(forge).toContain("buildWindowsInputHelper('gamepad', platform, arch)");- expect(forge).toContain("buildWindowsInputHelper('micro', platform, arch)");- expect(forge).toContain('cindy-windows-${kind}-helper.exe');- });- it('matches HID transport to the current controller instead of any Microsoft USB device', () => {- const source = readFileSync(- new URL('../../../../native/xbox-gamepad/macos-xbox-gamepad-helper.swift', import.meta.url),- 'utf8',- );- expect(source).toContain('func controllerTransport(for controller: GCController)');- expect(source).toContain('IOHIDManagerSetDeviceMatchingMultiple');- expect(source).toContain('0x054C');- expect(source).toContain('0x057E');- expect(source).not.toContain('func microsoftControllerTransport()');- expect(source).not.toContain('if sawUsb { return "usb" }');- });-- it('attaches any extended gamepad instead of filtering to Xbox', () => {- const source = readFileSync(- new URL('../../../../native/xbox-gamepad/macos-xbox-gamepad-helper.swift', import.meta.url),- 'utf8',- );- expect(source).toContain('func isSupportedGamepad');- expect(source).toContain('func resolveGamepadFamily');- expect(source).toContain('for controller in all where isSupportedGamepad(controller)');- expect(source).toContain('return "generic"');- expect(source).not.toContain('func isXboxController');- expect(source).not.toContain('all.first(where: isXboxController)');- expect(source).toContain('switch2_usb_ensure');- expect(source).toContain('switch2-usb on');- expect(source).toContain('switch2-usb off');- expect(source).toContain('switch2_usb_shutdown');- expect(source).toContain('func setSwitch2UsbWanted');- const startFn = source.match(/func start\(\) \{[\s\S]*?\n {2}\}/)?.[0] ?? '';- expect(startFn).not.toContain('switch2_usb_ensure');- expect(startFn).not.toContain('scheduledTimer');- expect(source).toContain('switch2PollTimer');- expect(source).toMatch(- /if family == "nintendo" \{[\s\S]*?if switch2UsbWanted \{[\s\S]*?continue/,- );- expect(source).not.toMatch(- /if family == "nintendo" \{\s*observed\[family\] = nil\s*continue\s*\}/,- );- });-- it('compiles switch2_usb.c with clang before linking the object into swiftc', () => {- const forge = readFileSync(new URL('../../../../forge.config.ts', import.meta.url), 'utf8');- const host = readFileSync(new URL('../host.ts', import.meta.url), 'utf8');- expect(forge).toContain("MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET = 'macos11.0'");- expect(forge).toContain('compileCObjectForTarget');- expect(forge).toContain("'clang'");- expect(forge).toContain('switch2_usb.c');- expect(forge).toContain('switch2_usb.h');- expect(host).toContain("'clang'");- expect(host).toContain("'-c'");- expect(host).toContain('switch2_usb.o');- expect(host).not.toMatch(/swiftc',[\s\S]*switch2UsbC/);- expect(host).toContain('setSwitch2UsbWanted');- const index = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');- expect(index).toContain('setSwitch2UsbWanted');- expect(index).toContain('computeSwitch2UsbWanted');- expect(index).toContain('taskSlotsSuspended');- expect(index).toContain('layoutPreviewLease.setActive(false, owner)');- expect(index).not.toMatch(/previewFamily = family;\s*layoutPreviewLease\.setActive\(active/);- expect(index).not.toMatch(- /setSwitch2UsbWanted\(\s*controller\.getAccessories\(\)\.nintendo\.settings\.deviceEnabled \|\| previewFamily === 'nintendo'/,- );- });-- it('copies the matching HID set into a buffer sized for every device', () => {- const source = readFileSync(- new URL('../../../../native/xbox-gamepad/switch2_usb.c', import.meta.url),- 'utf8',- );- expect(source).toContain('CFSetApplyFunction');- expect(source).not.toContain('CFSetGetValues(devices, (const void **)&device)');- });-});diff --git a/apps/desktop/src/main/xbox-gamepad/__tests__/nativeContracts.test.ts b/apps/desktop/src/main/xbox-gamepad/__tests__/nativeContracts.test.tsnew file mode 100644index 0000000000..0bb8c5089a--- /dev/null+++ b/apps/desktop/src/main/xbox-gamepad/__tests__/nativeContracts.test.ts@@ -0,0 +1,92 @@+// Guard tier: native transport, memory safety and packaged helper contracts+// span Swift/C, Forge and the JS host; JS host fakes cannot execute these APIs.+// Keep real host lifecycle behavior in host.test.ts.+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';++describe('Xbox gamepad helper packaging contract', () => {+ it('starts Windows input and ships a native helper for the requested architecture', () => {+ const index = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');+ const forge = readFileSync(new URL('../../../../forge.config.ts', import.meta.url), 'utf8');+ expect(index).toContain("process.platform === 'darwin' || process.platform === 'win32'");+ expect(forge).toContain('buildWindowsGamepadHelper(platform, arch)');+ expect(forge).toContain('aarch64-pc-windows-msvc');+ expect(forge).toContain('x86_64-pc-windows-msvc');+ expect(forge).toContain("buildWindowsInputHelper('gamepad', platform, arch)");+ expect(forge).toContain("buildWindowsInputHelper('micro', platform, arch)");+ expect(forge).toContain('cindy-windows-${kind}-helper.exe');+ });+ it('matches HID transport to the current controller instead of any Microsoft USB device', () => {+ const source = readFileSync(+ new URL('../../../../native/xbox-gamepad/macos-xbox-gamepad-helper.swift', import.meta.url),+ 'utf8',+ );+ expect(source).toContain('func controllerTransport(for controller: GCController)');+ expect(source).toContain('IOHIDManagerSetDeviceMatchingMultiple');+ expect(source).toContain('0x054C');+ expect(source).toContain('0x057E');+ expect(source).not.toContain('func microsoftControllerTransport()');+ expect(source).not.toContain('if sawUsb { return "usb" }');+ });++ it('attaches any extended gamepad instead of filtering to Xbox', () => {+ const source = readFileSync(+ new URL('../../../../native/xbox-gamepad/macos-xbox-gamepad-helper.swift', import.meta.url),+ 'utf8',+ );+ expect(source).toContain('func isSupportedGamepad');+ expect(source).toContain('func resolveGamepadFamily');+ expect(source).toContain('for controller in all where isSupportedGamepad(controller)');+ expect(source).toContain('return "generic"');+ expect(source).not.toContain('func isXboxController');+ expect(source).not.toContain('all.first(where: isXboxController)');+ expect(source).toContain('switch2_usb_ensure');+ expect(source).toContain('switch2-usb on');+ expect(source).toContain('switch2-usb off');+ expect(source).toContain('switch2_usb_shutdown');+ expect(source).toContain('func setSwitch2UsbWanted');+ const startFn = source.match(/func start\(\) \{[\s\S]*?\n {2}\}/)?.[0] ?? '';+ expect(startFn).not.toContain('switch2_usb_ensure');+ expect(startFn).not.toContain('scheduledTimer');+ expect(source).toContain('switch2PollTimer');+ expect(source).toMatch(+ /if family == "nintendo" \{[\s\S]*?if switch2UsbWanted \{[\s\S]*?continue/,+ );+ expect(source).not.toMatch(+ /if family == "nintendo" \{\s*observed\[family\] = nil\s*continue\s*\}/,+ );+ });++ it('compiles switch2_usb.c with clang before linking the object into swiftc', () => {+ const forge = readFileSync(new URL('../../../../forge.config.ts', import.meta.url), 'utf8');+ const host = readFileSync(new URL('../host.ts', import.meta.url), 'utf8');+ expect(forge).toContain("MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET = 'macos11.0'");+ expect(forge).toContain('compileCObjectForTarget');+ expect(forge).toContain("'clang'");+ expect(forge).toContain('switch2_usb.c');+ expect(forge).toContain('switch2_usb.h');+ expect(host).toContain("'clang'");+ expect(host).toContain("'-c'");+ expect(host).toContain('switch2_usb.o');+ expect(host).not.toMatch(/swiftc',[\s\S]*switch2UsbC/);+ expect(host).toContain('setSwitch2UsbWanted');+ const index = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');+ expect(index).toContain('setSwitch2UsbWanted');+ expect(index).toContain('computeSwitch2UsbWanted');+ expect(index).toContain('taskSlotsSuspended');+ expect(index).toContain('layoutPreviewLease.setActive(false, owner)');+ expect(index).not.toMatch(/previewFamily = family;\s*layoutPreviewLease\.setActive\(active/);+ expect(index).not.toMatch(+ /setSwitch2UsbWanted\(\s*controller\.getAccessories\(\)\.nintendo\.settings\.deviceEnabled \|\| previewFamily === 'nintendo'/,+ );+ });++ it('copies the matching HID set into a buffer sized for every device', () => {+ const source = readFileSync(+ new URL('../../../../native/xbox-gamepad/switch2_usb.c', import.meta.url),+ 'utf8',+ );+ expect(source).toContain('CFSetApplyFunction');+ expect(source).not.toContain('CFSetGetValues(devices, (const void **)&device)');+ });+});diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.tsnew file mode 100644index 0000000000..f6f35d15dd--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts@@ -0,0 +1,18 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { expect, it } from 'vitest';++// Guard tier (engineering-conventions §3.2): the long-lived sidebar owns the+// worker notification subscription. Moving it into the conditional ExpandedView+// loses completion/error notifications while collapsed. Hook behavior is tested+// by useWorkers.test.tsx; no isolated root-sidebar runtime harness exists, and+// mocking its expanded subtree would hide this mount-ownership regression.+it('owns worker attention in the sidebar root across collapsed-view unmounts', () => {+ const source = readFileSync(resolve(__dirname, '../features/cc-agent/CCAgentSidebarUpper.tsx'), 'utf8');+ const start = source.indexOf('export function CCAgentSidebarUpper()');+ const end = source.indexOf('function ExpandedView(', start);+ expect(start).toBeGreaterThanOrEqual(0);+ expect(end).toBeGreaterThan(start);+ expect(source.slice(start, end)).toContain('useOrcaWorkerAttentionWatcher(sessionsHook.sessions, activeSessionId);');+ expect(source.slice(end)).not.toContain('useOrcaWorkerAttentionWatcher(');+});diff --git a/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts b/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.tsnew file mode 100644index 0000000000..08c1c3ef10--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/userMessageSourceLabels.test.ts@@ -0,0 +1,28 @@+import fs from 'node:fs';+import path from 'node:path';+import { describe, expect, it } from 'vitest';++// Privacy contract (engineering-conventions §3.2): shareConversationImage tests+// strip a hand-built DOM, and MessageSourceLabels tests only its child component.+// Neither catches UserMessage dropping the actual author/plugin stripping marks.+// Keep these two cross-file contracts in required guard, separate from jsdom+// behavior tests. Minimal regression: remove either mark and exported shares+// expose a shared-task identity or retain a plugin-only bubble.+const source = fs.readFileSync(+ path.resolve(__dirname, '../components/chat/UserMessage.tsx'),+ 'utf8',+);++describe('UserMessage share-image privacy boundary', () => {+ it('marks the shared-task author line for stripping from share images', () => {+ expect(source).toMatch(+ /\{sharedAuthorName && \(\s*<span\s+\{\.\.\.\{ \[SHARE_SOURCE_ATTR\]: '' \}\}/,+ );+ });++ it('marks a bubble containing only a plugin annotation for stripping', () => {+ expect(source).toMatch(+ /\{\.\.\.\(inlineQuoteCount === 0 && !displayBubbleBody\.trim\(\)\s*\? \{ \[SHARE_SOURCE_ATTR\]: '' \}\s*: \{\}\)\}/,+ );+ });+});diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ImageLightboxAnnotate.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ImageLightboxAnnotate.test.tsxindex c549b617cb..f62ffda753 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/ImageLightboxAnnotate.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/ImageLightboxAnnotate.test.tsx@@ -95,6 +95,24 @@ afterEach(() => {});describe('ImageLightbox annotate mode', () => {+ // Replaces the deleted source scan: a background misclick during annotation+ // must preserve unsaved strokes (engineering-conventions §3.2, user data).+ it('keeps unsaved strokes and the lightbox open after a background click', () => {+ vi.useFakeTimers();+ const onClose = vi.fn();+ render(<ImageLightbox src={SRC} onClose={onClose} annotationEdit={{ onSave: vi.fn() }} />);+ loadImage(lightboxImage());+ openAnnotate();+ drawStroke({ x: 10, y: 10 }, { x: 90, y: 50 });+ act(() => vi.advanceTimersByTime(200));+ // FocusScope focuses the real overlay. Target that background itself so+ // the test cannot pass merely because an image child swallowed the click.+ fireEvent.click(document.activeElement!);+ act(() => vi.advanceTimersByTime(250));+ expect(onClose).not.toHaveBeenCalled();+ expect(committedPaths('stroke')).toHaveLength(1);+ });+it('draws with pointer events and saves normalized strokes', async () => {const onSave = vi.fn();render(diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsxindex b0dcc1b489..241ebe6aaf 100644--- a/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/chatInputAnnotationAbort.test.tsx@@ -13,10 +13,17 @@ import type { ProviderView } from '@cindy/model-providers';import { sshNativeCodexProvider, sshModel } from '@/features/cc-agent/__tests__/sshModelFixtures';import type { AttachedFile } from '@/lib/fileTypes';import { ChatInput } from '../ChatInput';+import { clearDraft, saveDraft } from '@/lib/composerDraftStore';+import type { AtMentionPanel } from '../AtMentionPanel';+import type { scanAtResources } from '@/lib/atResourceService';+import type { ExtraDirsButton } from '../ExtraDirsButton';const h = vi.hoisted(() => ({ t: (key: string) => key, confirm: vi.fn(), editor: null as Editor | null, listening: false, stop: vi.fn().mockResolvedValue(undefined),setModel: vi.fn(), selectModel: undefined as undefined | ((id: string) => Promise<void | boolean>), remoteProviders: [] as ProviderView[],remoteStatus: 'ready' as 'ready' | 'loading' | 'error',+ scan: vi.fn<typeof scanAtResources>(),+ atPanel: null as ComponentProps<typeof AtMentionPanel> | null,+ documentChanged: vi.fn(),}));vi.mock('react-i18next', async (original) => ({ ...await original<typeof import('react-i18next')>(), useTranslation: () => ({ t: h.t }) }));@@ -48,15 +55,19 @@ vi.mock('../ModelSelector', async (original) => ({ ...await original<typeof imporeturn <span data-testid="model-selector">{modelId}</span>;} }));vi.mock('@/hooks/useSshCodexProviders', () => ({ useSshCodexProviders: () => ({ providers: h.remoteProviders, status: h.remoteStatus, refresh: () => {} }) }));-vi.mock('../ExtraDirsButton', () => ({ ExtraDirsButton: () => null }));+vi.mock('../ExtraDirsButton', () => ({ ExtraDirsButton: ({ open, onOpenChange, panel }: ComponentProps<typeof ExtraDirsButton>) => <><button aria-label="test-suggestions" onClick={() => onOpenChange?.(!open)} />{open && panel}</> }));vi.mock('../PermissionSelector', () => ({ PermissionSelector: () => <span data-testid="permission-selector" /> }));vi.mock('../NewGoalDialog', () => ({ NewGoalDialog: () => null }));vi.mock('../FolderPickerPopover', () => ({ FolderPickerPopover: () => null, addRecentFolder: vi.fn() }));-vi.mock('../AtMentionPanel', () => ({ AtMentionPanel: () => null }));+vi.mock('../AtMentionPanel', () => ({ AtMentionPanel: (props: ComponentProps<typeof AtMentionPanel>) => { h.atPanel = props; return null; } }));+vi.mock('@/lib/atResourceService', async (original) => ({ ...await original<typeof import('@/lib/atResourceService')>(), scanAtResources: h.scan }));vi.mock('../SlashCommandPalette', () => ({ SlashCommandPalette: () => null }));vi.mock('@/voice-input/VoiceInputPointerHintLayer', () => ({ VoiceInputPointerHintLayer: ({ children }: { children: import('react').ReactNode }) => <>{children}</> }));vi.mock('@/voice-input/VoiceInputStatusNotice', () => ({ VoiceInputStatusNotice: () => null }));vi.mock('@/voice-input/useVoiceInput', () => ({ useVoiceInput: (editor: Editor | null) => {+ // Attach before ChatInput's first hydration effect so an empty-document+ // replacement on initial mount cannot hide from the regression assertion.+ if (editor && editor !== h.editor) editor.on('transaction', ({ transaction }) => { if (transaction.docChanged) h.documentChanged(); });h.editor = editor;return { state: h.listening ? 'listening' : 'idle', isListening: h.listening, isBusy: h.listening, draftText: '', start: vi.fn(), stop: h.stop, cancel: vi.fn() };} }));@@ -93,10 +104,103 @@ const annotatedImage: AttachedFile = {};beforeEach(() => {+ h.editor = null;+ h.documentChanged.mockClear();+ h.listening = false;+ h.atPanel = null;+ h.scan.mockReset().mockResolvedValue({ success: true, items: [], truncated: false });window.electronAPI = api;vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });});-afterEach(() => { cleanup(); h.remoteProviders = []; vi.unstubAllGlobals(); vi.restoreAllMocks(); });+afterEach(() => { cleanup(); clearDraft('composer-regression'); h.remoteProviders = []; vi.unstubAllGlobals(); vi.restoreAllMocks(); });++function renderComposer(extra: Partial<ComponentProps<typeof ChatInput>> = {}) {+ const attachmentState: ComponentProps<typeof ChatInput>['attachmentState'] = {+ attachments: [], hasAttachments: false, addFiles: vi.fn(), addClipboardImage: vi.fn(),+ rejections: [], dismissRejection: noOp, clearRejections: noOp, addFolderPath: noOp,+ pendingFoldersVersion: 0, consumePendingFolders: () => [], addFileMention: noOp,+ pendingFileMentionsVersion: 0, consumePendingFileMentions: () => [],+ removeFile: noOp, updateFile: noOp, discardFiles: noOp, clearFiles: noOp, restoreFiles: files => [...files],+ };+ const props = { draftKey: 'composer-regression', deviceLinkDeviceId: null,+ attachmentState,+ hideRuntimeControls: true, showFolderPicker: false, disableAutofocus: true,+ onSend: vi.fn().mockResolvedValue(true), ...extra };+ const view = render(<ChatInput {...props} />);+ return { ...view, props };+}++// Replaces the source-only guards with real editor transactions at the two+// external-draft boundaries. Empty paragraph JSON is the minimal #720 input;+// a document replacement would remap the live voice insertion anchor.+it('does not replace the empty editor after an external empty-draft notification', async () => {+ renderComposer();+ await waitFor(() => expect(h.editor).not.toBeNull());+ const changed = vi.fn();+ h.editor!.on('transaction', ({ transaction }) => { if (transaction.docChanged) changed(); });+ await act(async () => saveDraft('composer-regression', {+ text: { type: 'doc', content: [{ type: 'paragraph' }] }, attachments: [],+ }));+ expect(changed).not.toHaveBeenCalled();+ expect(h.editor!.state.selection.from).toBe(1);+});++it('does not rehydrate an empty stored document when voice busy state changes', async () => {+ saveDraft('composer-regression', { text: { type: 'doc', content: [{ type: 'paragraph' }] }, attachments: [] });+ const view = renderComposer();+ await waitFor(() => expect(h.editor).not.toBeNull());+ expect(h.documentChanged).not.toHaveBeenCalled();+ const changed = vi.fn();+ h.editor!.on('transaction', ({ transaction }) => { if (transaction.docChanged) changed(); });+ h.listening = true;+ view.rerender(<ChatInput {...view.props} />);+ h.listening = false;+ view.rerender(<ChatInput {...view.props} />);+ expect(changed).not.toHaveBeenCalled();+ expect(h.editor!.state.selection.from).toBe(1);+});++// A prompt preview hides the old draft. Its first key must only dismiss the+// preview; dispatch tests without a preview cannot catch this accidental send.+it('dismisses a preview on Enter without sending or changing the hidden draft', async () => {+ const view = renderComposer();+ await waitFor(() => expect(h.editor).not.toBeNull());+ await act(async () => { h.editor!.commands.setContent('<p>unsent draft</p>'); });+ view.rerender(<ChatInput {...view.props} previewPrompt="preview suggestion" />);+ expect(screen.getByText('preview suggestion')).toBeTruthy();+ fireEvent.keyDown(h.editor!.view.dom, { key: 'Enter', code: 'Enter' });+ expect(view.props.onSend).not.toHaveBeenCalled();+ expect(h.editor!.getText()).toBe('unsent draft');+ expect(screen.queryByText('preview suggestion')).toBeNull();+});++it('does not let a pending local resource scan repopulate an SSH composer', async () => {+ let finish!: (value: Awaited<ReturnType<typeof scanAtResources>>) => void;+ h.scan.mockReturnValue(new Promise(resolve => { finish = resolve; }));+ const view = renderComposer({ initialWorkingDir: '/workspace' });+ await waitFor(() => expect(h.editor).not.toBeNull());+ fireEvent.click(screen.getByRole('button', { name: 'test-suggestions' }));+ await waitFor(() => expect(h.scan).toHaveBeenCalled());+ h.atPanel = null;+ view.rerender(<ChatInput {...view.props} remoteHostId="ssh-host" />);+ // Synthetic + remains mounted for SSH, unlike the typed-@ panel. Require+ // fresh ready props so a stale captured value cannot make this test pass.+ const currentPanelState = () => h.atPanel?.state;+ await waitFor(() => expect(currentPanelState()).toEqual({ kind: 'ready', items: [], truncated: false }));+ await act(async () => finish({ success: true, items: [{ type: 'file', relPath: 'stale.txt', name: 'stale.txt' }], truncated: false }));+ expect(currentPanelState()).toEqual({ kind: 'ready', items: [], truncated: false });+});++it('keeps a remote draft with no directory local-scan-free, but searches nonempty queries remotely', async () => {+ renderComposer({ deviceLinkDeviceId: 'remote-device' });+ await waitFor(() => expect(h.editor).not.toBeNull());+ await act(async () => { h.editor!.commands.setContent('<p>@</p>'); h.editor!.commands.setTextSelection(2); });+ await waitFor(() => expect(h.atPanel).not.toBeNull());+ expect(h.scan).not.toHaveBeenCalled();+ await act(async () => { h.editor!.commands.insertContent('needle'); });+ await waitFor(() => expect(h.scan).toHaveBeenCalled());+ expect(h.scan).toHaveBeenLastCalledWith('', expect.any(String), 2000, 'needle', 'remote-device', expect.objectContaining({ includeLocalContext: false, includeTaskHistory: true }));+});it('restores text, attachments and strokes after an aborted annotated send', async () => {h.remoteProviders = [sshNativeCodexProvider([sshModel('remote-only')])];diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkerPanel.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkerPanel.test.tsxindex 1f45871fd7..0810d15ad6 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkerPanel.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/OrcaWorkerPanel.test.tsx@@ -20,6 +20,10 @@ const mocks = vi.hoisted(() => ({sessions: [] as Array<{ id: string; agentDeviceId?: string | null; orcaRole?: 'lead' }>,sessionsLoading: false,sidebarWindow: false,+ windowVisible: true,+ watchAttention: vi.fn(),+ refreshProjection: vi.fn(),+ refreshSettings: vi.fn(),workerAgentInput: null as Record<string, unknown> | null,workerAgentDevices: {leadAgentDeviceId: 'agent-pc' as string | null,@@ -41,19 +45,19 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({useRemoteProjectSessions: () => [],}));vi.mock('@/hooks/useWindowVisible', () => ({- useWindowVisible: () => true,+ useWindowVisible: () => mocks.windowVisible,useDocumentVisible: () => true,}));vi.mock('../hooks/useOrcaWorkerAttentionWatcher', () => ({- useOrcaWorkerAttentionByLeadIds: vi.fn(),+ useOrcaWorkerAttentionByLeadIds: mocks.watchAttention,}));vi.mock('../hooks/useStopOrcaCollab', () => ({useStopOrcaCollabWithoutNavigation: () => ({ requestStop: vi.fn() }),}));vi.mock('../hooks/workerProjectionStore', () => ({useWorkerProjectionOwner: vi.fn(),- revalidateActiveWorkersProjection: vi.fn(),- revalidateActiveWorkerSettings: vi.fn(),+ revalidateActiveWorkersProjection: mocks.refreshProjection,+ revalidateActiveWorkerSettings: mocks.refreshSettings,}));vi.mock('../../right-sidebar/plugins/orca-workers/actions', () => ({clearOrcaWorkersSelectionIntent: vi.fn(),@@ -316,6 +320,10 @@ describe('OrcaWorkersTabBody Lead Agent context', () => {};beforeEach(() => {+ mocks.windowVisible = true;+ mocks.watchAttention.mockClear();+ mocks.refreshProjection.mockClear();+ mocks.refreshSettings.mockClear();mocks.sessions = [];mocks.sessionsLoading = false;mocks.sidebarWindow = false;@@ -332,6 +340,31 @@ describe('OrcaWorkersTabBody Lead Agent context', () => {mocks.sidebarWindow = false;});+ // Detached tabs own their watcher even while hidden. Only an actually+ // visible collaboration view may clear attention or refresh its projection.+ // Hook tests alone cannot catch dropping these caller-side lifecycle inputs.+ it('keeps detached attention watching while hidden and refreshes only on visibility', () => {+ mocks.sidebarWindow = true;+ mocks.sessions = [{ id: 'lead-1', orcaRole: 'lead' }];+ mocks.windowVisible = false;+ const view = render(<OrcaWorkersTabBody ctx={ctx} state={{}} active />);+ expect(mocks.watchAttention).toHaveBeenLastCalledWith(['lead-1'], undefined);+ expect(mocks.toolbarProps.clearAttentionWhenVisible).toBe(false);+ expect(mocks.refreshProjection).not.toHaveBeenCalled();+ expect(mocks.refreshSettings).not.toHaveBeenCalled();++ mocks.windowVisible = true;+ view.rerender(<OrcaWorkersTabBody ctx={ctx} state={{}} active />);+ expect(mocks.watchAttention).toHaveBeenLastCalledWith(['lead-1'], 'lead-1');+ expect(mocks.toolbarProps.clearAttentionWhenVisible).toBe(true);+ expect(mocks.refreshProjection).toHaveBeenCalledWith('lead-1');+ expect(mocks.refreshSettings).toHaveBeenCalledWith('lead-1');++ view.rerender(<OrcaWorkersTabBody ctx={ctx} state={{}} active shellVisible={false} />);+ expect(mocks.watchAttention).toHaveBeenLastCalledWith(['lead-1'], undefined);+ expect(mocks.toolbarProps.clearAttentionWhenVisible).toBe(false);+ });+it.each([false, true])('hides execution devices for a remote Agent while keeping creation available (detached: %s)', async (detached) => {mocks.sidebarWindow = detached;mocks.sessions = [diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/RolePillDropdown.tabsScroll.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/RolePillDropdown.tabsScroll.test.tsxindex 1328194098..794ae44b4c 100644--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/RolePillDropdown.tabsScroll.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/RolePillDropdown.tabsScroll.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { WorkerInfo } from '../hooks/useWorkers';import { WorkerListToolbar, workerTabsScrollStep } from '../RolePillDropdown';+import { __resetWorkerAttentionStoreForTest, hasWorkerAttention, markWorkerAttention } from '../lib/workerAttentionStore';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -93,6 +94,7 @@ function setReducedMotion(reduced: boolean): void {describe('WorkerTabsList overflow scrolling', () => {beforeEach(() => {localStorage.clear();+ __resetWorkerAttentionStoreForTest();});afterEach(() => {@@ -100,6 +102,25 @@ describe('WorkerTabsList overflow scrolling', () => {vi.useRealTimers();});+ // Replaces RolePill's source-only clear guard with the real attention store:+ // hidden selection must retain the notification until its view is visible.+ it('retains hidden selected-worker attention and clears only the visible live worker', () => {+ const live = worker();+ const done = worker({ workerId: 'worker-done', sessionId: 'session-done', status: 'done', focused: false });+ markWorkerAttention(live.workerId);+ markWorkerAttention(done.workerId);+ const props = { worker: live, workers: [live, done], selectedWorkerId: live.workerId,+ activeWorkerCount: 1, softLimit: 5, hardLimit: 8, onSwitchFocus: vi.fn(),+ onOpenCreate: vi.fn(), onArchiveWorker: vi.fn() };+ const view = render(<WorkerListToolbar {...props} clearAttentionWhenVisible={false} />);+ expect(hasWorkerAttention(live.workerId)).toBe(true);+ view.rerender(<WorkerListToolbar {...props} clearAttentionWhenVisible />);+ expect(hasWorkerAttention(live.workerId)).toBe(false);+ expect(hasWorkerAttention(done.workerId)).toBe(true);+ view.rerender(<WorkerListToolbar {...props} selectedWorkerId={done.workerId} clearAttentionWhenVisible />);+ expect(hasWorkerAttention(done.workerId)).toBe(true);+ });+it('uses a bounded step that fits the visible tab strip', () => {expect(workerTabsScrollStep(200)).toBe(140);expect(workerTabsScrollStep(40)).toBe(80);diff --git a/docs/dev-rules/desktop-unit-test-performance.md b/docs/dev-rules/desktop-unit-test-performance.mdindex 0e6455e73f..24ca448248 100644--- a/docs/dev-rules/desktop-unit-test-performance.md+++ b/docs/dev-rules/desktop-unit-test-performance.md@@ -63,7 +63,7 @@ Vitest 每片切 `ceil(文件数 / 分片数)` 个文件,分片多于 2 个时每片的 worker 时间里,收集(导入模块)约 325–350 秒,执行测试 250–480 秒,环境初始化 105–127 秒,准备约 46 秒;后三项主要来自逐文件隔离。整体切换隔离方式会破坏正确性,所以改为逐个修掉开销最大的-文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 449 个+文件,并用 `pnpm check:test-hygiene` 阻止新增逐用例重置、真实等待和普通单测读源码文本(基线 438 个文件,只减不增,见 engineering-conventions.md §3.2「性能预算」)。修完 `codexProxyHost` 后,最慢的单个文件从 138 秒降到约 32 秒,不再由一个文件决定分片下限。@@ -88,15 +88,20 @@ CI 时长仍要用首次 4 分片 CI 实测确认。- 初始删除 81 个文件(488 条用例);独立审查发现其中包含缺少等价覆盖的权限、竞态、远程路由和设计契约,已恢复 30 个完整文件,并从 `homeUsageDashboardSource.test.ts` 保留账号隔离的 3 条- 契约(含同步主干时保留的 `botChatSurface.test.ts`)。最终相对原始基线删除 49 个文件,+ 契约(含同步主干时保留的 `botChatSurface.test.ts`)。后续逐文件复核另保留分享脱敏的两条契约、+ 侧栏折叠时通知订阅归属的一条契约。最终相对原始基线删除 47 个文件,不能沿用最初的「488 条无效用例」结论。`FileTreeView.horizontalScroll.test.tsx` 真实挂载组件并断言可见宽度,已恢复。+ IM 启动补全、空草稿水合与语音切换、预览误发送、远程扫描旧回包、图片标注误关闭、+ Orca 隐藏/可见时的通知生命周期,改由真实生产入口或组件行为回归覆盖。+ 原生源码检测包含 Swift、C/C++、Rust 等;必要的跨原生协议、权限与生命周期契约进入+ required guard,执行脚本和 JSON/二进制资源不作为源码字面量断言。- 207 个 PARTIAL 文件(2,874 条用例,其中约 991 条是静态或重复接线候选)保留:它们与续跑、设备链、账户切换、Pi、权限和竞速回归混在一起,只能在补上等价的生产入口测试后逐项替换,不能按字符串模式批量删除。- 最初迁移 27 个静态契约文件;审查恢复与扫描器补漏后,Desktop 和 Mobile 的跨文件安全、权限、主题或文案契约统一迁到各自 `guard` allowlist,由 CI 的 `pnpm test:guard` 执行。最终名单只在- `scripts/test-workspaces.config.mjs` 维护(Desktop 84、Mobile 28),由 runner 从 unit 排除;+ `scripts/test-workspaces.config.mjs` 维护(Desktop 92、Mobile 29),由 runner 从 unit 排除;不要在 `apps/desktop/vitest.config.ts` 的项目 exclude 里重复排除,否则 guard 层自己也收集不到这些文件(2026-10-16 发现 29 个 allowlist 文件实际只跑了 2 个,已修复)。- 缺少 timing 的文件是 `src/main/cindy-brain/__tests__/pluginModelPrefsIpc.test.ts`。diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjsindex a781b1da62..642350012d 100644--- a/scripts/__tests__/check-test-hygiene.test.mjs+++ b/scripts/__tests__/check-test-hygiene.test.mjs@@ -119,6 +119,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"import { x } from '../x.ts';\nvi.mock('../y.ts');\nreadFileSync(join(__dirname, 'fixtures', 'a.ts'));",{ sourceReads: 0 },],+ ...['swift', 'm', 'mm', 'h', 'cpp', 'rs', 'go', 'kt', 'java', 'cs', 'py'].map(extension => [+ `native and other production source: ${extension}`,+ `const source = readFileSync(new URL('../helper.${extension}', import.meta.url), 'utf8');`,+ { sourceReads: 1 },+ ]),+ [+ "data and binary resources are not production source",+ "readFileSync(new URL('../data.json', import.meta.url)); readFileSync(new URL('../helper.bin', import.meta.url));",+ { sourceReads: 0 },+ ],["multi-line source path declared before the read","const sourcePath = resolve(\n __dirname,\n '..',\n 'Image.tsx',\n);\nconst source = readFileSync(sourcePath, 'utf8');",@@ -129,6 +139,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {"const script = join(\n dirname(fileURLToPath(import.meta.url)),\n '../scripts/test-share.mjs',\n);\nspawnSync(process.execPath, [script]);\nreadFileSync(template, 'utf8');",{ sourceReads: 0 },],+ [+ "inline executable paths are not source reads",+ "const installer = resolve(__dirname, '../install.sh'); spawnSync('bash', [resolve(__dirname, '../register.sh')]); readFileSync(logPath, 'utf8');",+ { sourceReads: 0 },+ ],+ [+ "a multi-line native source URL is read through its binding",+ "const sourceUrl = new URL(\n '../helper.swift',\n import.meta.url,\n); const source = readFileSync(sourceUrl, 'utf8');",+ { sourceReads: 1 },+ ],["source read through a typed helper","const read = (relative: string): string => readFileSync(resolve(__dirname, relative), 'utf8');\nconst source = read('../ChatInput.tsx');",diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjsindex f2d4003472..3143985ea2 100644--- a/scripts/check-test-hygiene.mjs+++ b/scripts/check-test-hygiene.mjs@@ -306,7 +306,9 @@ function countRealWaits(code, lines) {}const IMPORT_CONTEXT = /(?:\bfrom|\bimport|\brequire|\.mock|\.doMock|\.unmock|\.importActual|\.importMock|\.glob)\s*\(?\s*$/;-const SOURCE_EXT = /\.(?:tsx?|mts|cts|css|mjs|cjs|jsx?)$/;+const SOURCE_EXTENSION = '(?:tsx?|mts|cts|css|mjs|cjs|jsx?|swift|[cmh]|mm|cc|cpp|cxx|hh|hpp|hxx|rs|go|kts?|java|cs|py|rb|sh|bash|zsh|html|vue|svelte|scss|sass|less)';+const SOURCE_EXT = new RegExp('\\.' + SOURCE_EXTENSION + '$', 'i');+const SOURCE_LITERAL = new RegExp('\\.' + SOURCE_EXTENSION + '[\'"]', 'i');// Only anchors that point into the checkout count; generic names such as `root`// usually hold an mkdtemp() directory whose fake source files are test input.const REPO_ANCHOR = /__dirname|import\.meta\.(?:url|dirname)|\b(?:REPO_ROOT|repoRoot|desktopRoot)\b/;@@ -363,14 +365,15 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {const helperCall = prefix.match(/\b([A-Za-z_$][\w$]*)\s*\(\s*$/)?.[1];if (helperCall && sourceReadHelpers.has(helperCall)) return true;// resolve(__dirname, '..', 'Sidebar.tsx') or new URL('../x.ts', import.meta.url).- if (REPO_ANCHOR.test(line)) return true;+ if (REPO_ANCHOR.test(line) && findEnclosingReadCall(code, match.index) >= 0) return true;// A separately declared sourcePath may be formatted over several lines before// it is passed to readFileSync. Keep that equivalent to the inline path form.- const pathStart = findEnclosingReadCall(code, match.index, /\b(?:resolve|join)\s*\(/g);+ const pathStart = findEnclosingReadCall(code, match.index, /\b(?:resolve|join|URL)\s*\(/g);if (pathStart >= 0) {- const pathContext = code.slice(pathStart, match.index + match[0].length);+ const pathEnd = code.indexOf(')', match.index + match[0].length);+ const pathContext = code.slice(pathStart, pathEnd < 0 ? match.index + match[0].length : pathEnd + 1);const binding = code.slice(Math.max(0, pathStart - 150), pathStart)- .match(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:[A-Za-z_$][\w$]*\.)?$/)?.[1];+ .match(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:new\s+)?(?:[A-Za-z_$][\w$]*\.)?$/)?.[1];const readBinding = binding && new RegExp('\\breadFile(?:Sync)?\\s*\\(\\s*' + binding + '\\b').test(code);if (readBinding && REPO_ANCHOR.test(pathContext) && !/fixture/i.test(pathContext)) return true;}@@ -381,11 +384,11 @@ function isSourcePathLiteral(code, match, sourceReadHelpers = new Set()) {if (callStart >= 0) {const callContext = code.slice(callStart, match.index + match[0].length);const previousContext = callContext.slice(0, -match[0].length);- const hasPriorSourceLiteral = /\.(?:tsx?|mts|cts|css|mjs|cjs|jsx?)['"]/.test(previousContext);+ const hasPriorSourceLiteral = SOURCE_LITERAL.test(previousContext);if (/\n/.test(callContext) && !hasPriorSourceLiteral && !/[;{}]/.test(callContext) && REPO_ANCHOR.test(callContext) && !/fixture/i.test(callContext)) return true;}// readFileSync('../x.ts') reads relative to the test process, i.e. the checkout.- return /\breadFile(?:Sync)?\s*\(/.test(line) && (value.startsWith('./') || value.startsWith('../'));+ return callStart >= 0 && (value.startsWith('./') || value.startsWith('../'));}/** Count unjustified rule hits in one unit test file. */diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.jsonindex 1b99af3a23..f9608314f7 100644--- a/scripts/test-hygiene-baseline.json+++ b/scripts/test-hygiene-baseline.json@@ -96,7 +96,7 @@},"apps/desktop/src/main/__tests__/lifecycle.test.ts": {"resetModules": 2,- "sourceReads": 3+ "sourceReads": 2},"apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts": {"sourceReads": 3@@ -107,9 +107,6 @@"apps/desktop/src/main/__tests__/makerOrcaRoleMarking.test.ts": {"sourceReads": 2},- "apps/desktop/src/main/__tests__/messagesAroundClientIdIpc.test.ts": {- "sourceReads": 3- },"apps/desktop/src/main/__tests__/modelPricingPrewarmOrdering.test.ts": {"sourceReads": 1},@@ -141,8 +138,7 @@"sourceReads": 1},"apps/desktop/src/main/__tests__/sessionDragReleaseNativeHost.test.ts": {- "resetModules": 1,- "sourceReads": 2+ "resetModules": 1},"apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts": {"sourceReads": 1@@ -183,9 +179,6 @@"apps/desktop/src/main/__tests__/windowsDiagnosticsTrayWiring.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/__tests__/windowsIconAssets.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/__tests__/windowsTaskbarNative.test.ts": {"resetModules": 2},@@ -208,9 +201,6 @@"apps/desktop/src/main/agent-island/__tests__/layoutPreferenceStore.test.ts": {"resetModules": 2},- "apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts": {- "sourceReads": 2- },"apps/desktop/src/main/agent-island/__tests__/service.test.ts": {"sourceReads": 1},@@ -255,8 +245,7 @@"resetModules": 1},"apps/desktop/src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts": {- "resetModules": 1,- "sourceReads": 1+ "resetModules": 1},"apps/desktop/src/main/computer-permission-guide/__tests__/switch-target.test.ts": {"resetModules": 1@@ -274,13 +263,13 @@"resetModules": 1},"apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/device-link/__tests__/sharedTaskAccountBoundary.test.ts": {"sourceReads": 1},"apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts": {- "sourceReads": 3+ "sourceReads": 2},"apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts": {"sourceReads": 1@@ -394,7 +383,7 @@"sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/cindyMakeFeatureGate.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts": {"sourceReads": 1@@ -415,13 +404,13 @@"sourceReads": 2},"apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/orcaProviderRoutingSnapshotWiring.test.ts": {"sourceReads": 2},"apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts": {"sourceReads": 2@@ -478,7 +467,7 @@"sourceReads": 2},"apps/desktop/src/main/mcp-integrations/__tests__/forgeIconConversionPackaging.test.ts": {- "sourceReads": 4+ "sourceReads": 3},"apps/desktop/src/main/mcp-integrations/__tests__/pluginTaskHelperScope.test.ts": {"sourceReads": 1@@ -490,7 +479,7 @@"sourceReads": 1},"apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts": {"sourceReads": 1@@ -528,9 +517,6 @@"apps/desktop/src/main/remote-desktop/__tests__/linuxPackaging.test.ts": {"sourceReads": 1},- "apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts": {- "sourceReads": 1- },"apps/desktop/src/main/remote-desktop/__tests__/viewerDisplaySupport.test.ts": {"resetModules": 1},@@ -553,13 +539,13 @@"sourceReads": 1},"apps/desktop/src/main/resource-usage-window/__tests__/windowSecurity.test.ts": {- "sourceReads": 5+ "sourceReads": 4},"apps/desktop/src/main/reviewer/__tests__/reviewExternalInputWiring.test.ts": {"sourceReads": 2},"apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts": {- "sourceReads": 7+ "sourceReads": 6},"apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts": {"realWaits": 1@@ -630,9 +616,6 @@"apps/desktop/src/main/worktree/__tests__/precreatedCancellation.test.ts": {"resetModules": 1},- "apps/desktop/src/main/xbox-gamepad/__tests__/host.test.ts": {- "sourceReads": 5- },"apps/desktop/src/main/xbox-gamepad/__tests__/index.test.ts": {"resetModules": 1},@@ -663,9 +646,6 @@"apps/desktop/src/renderer/__tests__/agentDeviceModelMemory.test.ts": {"resetModules": 2},- "apps/desktop/src/renderer/__tests__/agentIslandVisibleSessionRoute.test.ts": {- "sourceReads": 5- },"apps/desktop/src/renderer/__tests__/attachmentFileCard.test.ts": {"sourceReads": 1},@@ -676,7 +656,7 @@"sourceReads": 4},"apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts": {- "sourceReads": 25+ "sourceReads": 1},"apps/desktop/src/renderer/__tests__/automationGroupCollapse.test.ts": {"resetModules": 2@@ -781,7 +761,7 @@"resetModules": 1},"apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts": {- "sourceReads": 2+ "sourceReads": 1},"apps/desktop/src/renderer/__tests__/historyPrefetch.test.ts": {"sourceReads": 1@@ -965,9 +945,6 @@"apps/desktop/src/renderer/__tests__/selectedMachineOwnerState.test.ts": {"resetModules": 1},- "apps/desktop/src/renderer/__tests__/selectionQuoteUserMessage.test.ts": {- "sourceReads": 3- },"apps/desktop/src/renderer/__tests__/sentInlineAtomBody.test.tsx": {"sourceReads": 1},@@ -1181,9 +1158,6 @@"apps/mobile/src/__tests__/clientEndpointStartup.test.ts": {"resetModules": 12},- "apps/mobile/src/__tests__/codeHighlight.test.ts": {- "sourceReads": 1- },"apps/mobile/src/__tests__/CompanionMemoryPage.test.tsx": {"realWaits": 2},@@ -1205,9 +1179,6 @@"apps/mobile/src/__tests__/endpointManifestLoader.test.ts": {"resetModules": 2},- "apps/mobile/src/__tests__/fingerprintConfig.test.ts": {- "sourceReads": 1- },"apps/mobile/src/__tests__/incomingShareFeedbackScript.test.ts": {"resetModules": 1},@@ -1235,9 +1206,6 @@"apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts": {"resetModules": 1},- "apps/mobile/src/__tests__/newSession.test.ts": {- "sourceReads": 1- },"apps/mobile/src/__tests__/outboxHistoryCache.test.ts": {"realWaits": 1,"sourceReads": 1@@ -1266,9 +1234,6 @@"apps/mobile/src/debug/localDiagnostics.test.ts": {"resetModules": 1},- "packages/design-tokens/src/__tests__/classification.test.ts": {- "sourceReads": 1- },"packages/design-tokens/src/__tests__/zero-wiring.test.ts": {"sourceReads": 8},diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 894544794e..6ad4d12e90 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -96,6 +96,8 @@ const desktopE2eInclude = ['src/main/maker-host/__tests__/*.e2e.test.ts',];const mobileGuardInclude = [+ // CSP must be applied at the WebView and download call sites, not only in its helper.+ 'src/__tests__/htmlPreviewCsp.test.ts','src/auth/__tests__/loginHandoffState.test.ts','src/__tests__/accountDeletion.test.ts','src/__tests__/androidSessionInteractionParity.test.tsx',@@ -129,6 +131,18 @@ const mobileGuardInclude = [// in the explicit guard tier. Keeping an exact allowlist makes it impossible// for a new source scan to silently become part of the ordinary unit gate.const desktopGuardInclude = [+ 'src/renderer/__tests__/orcaWorkerAttentionWatcherMount.test.ts',+ 'src/renderer/__tests__/userMessageSourceLabels.test.ts',+ // These native host suites also protect cross-runtime privacy/permission+ // and packaging contracts unavailable through a JS-only helper fake.+ 'src/main/__tests__/sessionDragReleaseNativeHost.test.ts',+ 'src/main/computer-permission-guide/__tests__/MacComputerPermissionGuideNativeHost.test.ts',+ 'src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts',+ 'src/main/agent-island/__tests__/nativeContracts.test.ts',+ 'src/main/xbox-gamepad/__tests__/nativeContracts.test.ts',+ // Native input caller authentication plus its production Forge/fuse boundary.+ // macOS executes the native probe; other platforms enforce the packaging contract.+ 'src/main/remote-desktop/__tests__/macosInput.test.ts','src/main/__tests__/authCaptchaIpcSecurity.test.ts','src/main/__tests__/appearanceUtilityWindowRegistration.test.ts','src/main/__tests__/authSameOwnerRefreshUi.test.ts',