Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-desktop): 隔离 Linux 音频故障并同步主干
Dash Huang353a54535ca0
diff --cc apps/desktop/src/main/__tests__/devStartupStatus.test.tsindex 1dfcdfe253,f713e925a4..1f80d7fa31--- a/apps/desktop/src/main/__tests__/devStartupStatus.test.ts+++ b/apps/desktop/src/main/__tests__/devStartupStatus.test.ts@@@ -52,21 -53,27 +53,25 @@@ describe('devStartupStatus', () =>startedAtMs: 100,});+ const ready = vi.fn();+ observeDesktopStartupResult(ready);- markDesktopDevWindowReady();+ markDesktopDevWindowReady(4343);+ expect(ready).not.toHaveBeenCalled();expect(JSON.parse(fs.readFileSync(statusPath, 'utf8'))).toMatchObject({state: 'window-ready',});- expect(JSON.parse(fs.readFileSync(- path.join(tempDir, '.dev-instances', '4242.json'),- 'utf8',- ))).toMatchObject({ state: 'starting' });+ expect(+ JSON.parse(fs.readFileSync(path.join(tempDir, '.dev-instances', '4242.json'), 'utf8')),+ ).toMatchObject({ state: 'starting' });markDesktopDevReady();+ expect(ready).toHaveBeenCalledExactlyOnceWith(true);const external = JSON.parse(fs.readFileSync(statusPath, 'utf8'));- const persistent = JSON.parse(fs.readFileSync(- path.join(tempDir, '.dev-instances', '4242.json'),- 'utf8',- ));+ const persistent = JSON.parse(+ fs.readFileSync(path.join(tempDir, '.dev-instances', '4242.json'), 'utf8'),+ );expect(external).toMatchObject({ state: 'ready', instance: { commit: 'abc123' } });expect(persistent).toMatchObject({state: 'ready',diff --cc apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsindex 3358ac6a89,c2436bda14..36a29e3b66--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@@ -11,10 -11,10 +11,10 @@@ const registerSource = readFileSync(res/\r\n?/g,'\n',);--const deviceLinkHostSource = readFileSync(resolve(mainRoot, 'device-link/index.ts'), 'utf8').replace(-- /\r\n?/g,-- '\n',--);++const deviceLinkHostSource = readFileSync(++ resolve(mainRoot, 'device-link/index.ts'),++ 'utf8',++).replace(/\r\n?/g, '\n');const makerSendSource = readFileSync(resolve(mainRoot, 'maker-ipc/makerSendTransaction.ts'),'utf8',@@@ -30,8 -30,17 +30,19 @@@ function handlerBody(source: string, chdescribe('session runtime control wiring', () => {it('replays Windows attention after the main window is shown independently of inventory loading', () => {- const body = handlerBody(bootstrapSource, "mainWindow.once('ready-to-show'", 'if (!app.isPackaged) markDesktopDevWindowReady(');- expect(body.indexOf('refreshWindowsAppBadge();')).toBeGreaterThan(body.indexOf('showMainWindowAndRestoreFullscreen('));+ const body = handlerBody(+ bootstrapSource,+ "mainWindow.once('ready-to-show'",+ 'void runComputerUseSmokeIfRequested();',+ );+ const shown = body.indexOf('showMainWindowAndRestoreFullscreen(');+ const badge = body.indexOf('refreshWindowsAppBadge();');+ expect(shown).toBeGreaterThan(-1);+ expect(badge).toBeGreaterThan(shown);- expect(body.indexOf('markDesktopDevWindowReady();')).toBeGreaterThan(badge);- expect(body).toContain('if (!app.isPackaged || isCindyVersionLaunchPending()) markDesktopDevWindowReady();');++ expect(body.indexOf('markDesktopDevWindowReady(')).toBeGreaterThan(badge);++ expect(body).toMatch(++ /if \(!app.isPackaged \|\| isCindyVersionLaunchPending\(\)\)\s+markDesktopDevWindowReady\(mainWindow.webContents.getOSProcessId\(\)\);/,++ );});it('advertises host-side model-window protection to remote controllers', () => {const capabilities = handlerBody(@@@ -74,9 -83,9 +85,7 @@@expect(body).toContain('stampTrustedDesktopQueuedOrigin(');}expect(makerSendSource).toContain('clientId: explicitUserItem.clientId');-- expect(makerSendSource).toContain(-- 'persistedContent: explicitUserItem.persistedContent',-- );++ expect(makerSendSource).toContain('persistedContent: explicitUserItem.persistedContent');expect(makerSendSource).toContain('if (deviceLinkInvoke || !canTrustDesktopPiCommand(item)) return explicitUserItem',);@@@ -123,7 -132,7 +132,10 @@@['MAKER_IPC_INVOKE.PI_COMPACTION_GET_PCT', 'MAKER_IPC_INVOKE.PI_COMPACTION_GET_STATE'],['MAKER_IPC_INVOKE.PI_COMPACTION_GET_STATE', 'MAKER_IPC_INVOKE.PI_COMPACTION_RESET_PCT'],['MAKER_IPC_INVOKE.PI_COMPACTION_RESET_PCT', 'MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT'],-- ['MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT', 'WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL'],++ [++ 'MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT',++ 'WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL',++ ],] as const) {const body = handlerBody(bootstrapSource, channel, nextChannel);const guard = body.indexOf('assertTrustedAppRendererEvent(event);');@@@ -154,13 -163,13 +166,21 @@@['MAKER_IPC_INVOKE.COMPACTION_RESET_PCT', 'MAKER_IPC_INVOKE.COMPACTION_SET_PCT'],['MAKER_IPC_INVOKE.COMPACTION_SET_PCT', 'MAKER_IPC_INVOKE.PI_COMPACTION_GET_PCT'],['MAKER_IPC_INVOKE.PI_COMPACTION_RESET_PCT', 'MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT'],-- ['MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT', 'WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL'],++ [++ 'MAKER_IPC_INVOKE.PI_COMPACTION_SET_PCT',++ 'WINDOW_BEHAVIOR_SET_SWALLOW_ACTIVATION_CLICK_CHANNEL',++ ],] as const) {const body = handlerBody(bootstrapSource, channel, nextChannel);const stamp = body.indexOf('assertCompactionMutationOwner(owner);');expect(stamp).toBeGreaterThan(-1);const write = Math.min(-- ...['writeCompactionPct(', 'resetCompactionPct()', 'writePiCompactionPct(', 'resetPiCompactionPct()']++ ...[++ 'writeCompactionPct(',++ 'resetCompactionPct()',++ 'writePiCompactionPct(',++ 'resetPiCompactionPct()',++ ].map((needle) => body.indexOf(needle)).filter((index) => index >= 0),);@@@ -213,9 -222,9 +233,7 @@@[fast, 'return await applyFastMode();'],] as const) {expect(body).toContain('withSendToSessionLock(sessionId');-- expect(body.indexOf('withSendToSessionLock(sessionId')).toBeLessThan(-- body.indexOf(applyCall),-- );++ expect(body.indexOf('withSendToSessionLock(sessionId')).toBeLessThan(body.indexOf(applyCall));expect(body).toContain('await resolvePendingRuntimeAxisPatch(sessionId, livePatch)');expect(body).toContain('recordUserSessionRuntimeAxisMutation(sessionId, livePatch, pendingPatch)',@@@ -278,10 -287,10 +296,14 @@@expect(syncLibrary).toContain('libraryExtraDirSyncTargets(');expect(syncLibrary).toContain('listActiveSessions()');expect(syncLibrary).toContain('sessionIsRemote(sessionId)');-- expect(syncLibrary).toContain('!remote && grantRoot && sessionId === focused ? grantRoot : null');++ expect(syncLibrary).toContain(++ '!remote && grantRoot && sessionId === focused ? grantRoot : null',++ );expect(syncLibrary).toContain("return 'superseded'");expect(syncLibrary).not.toContain("throw new Error('library extraDirs sync superseded')");-- expect(syncLibrary).toContain("throw new Error('library extraDirs not granted to focused session')");++ expect(syncLibrary).toContain(++ "throw new Error('library extraDirs not granted to focused session')",++ );expect(syncLibrary).toContain('if (!remote && nextRoot && sessionId === focused) throw error');expect(syncLibrary).toContain('libraryExtraDirSyncChain.then(run, run)');expect(syncLibrary).toContain('applied?.some(isLibraryExtraDirSlot)');@@@ -302,7 -311,7 +324,9 @@@const ingress = setModel.indexOf('registerSessionSetModelHandler(makerSessionRegistry, {');expect(ingress).toBeGreaterThan(-1);expect(setModel.slice(0, ingress)).not.toContain('assertTrustedAppRendererEvent(');-- expect(setModel.slice(ingress)).toContain('assertTrustedSender: (event) => assertTrustedAppRendererEvent(');++ expect(setModel.slice(ingress)).toContain(++ 'assertTrustedSender: (event) => assertTrustedAppRendererEvent(',++ );expect(setModel.slice(ingress)).toContain('isDeviceLinkInvoke,');expect(setModel).toContain('!isSupportedRuntimeEffort(selectionEffort)');expect(setModel).toContain("internalOptions.source !== 'user'");@@@ -353,18 -362,18 +377,14 @@@);const axisValidation = setModel.indexOf('if (atomicSelection) {');expect(axisValidation).toBeGreaterThan(-1);-- expect(setModel).not.toContain(-- "if (internalOptions.source !== 'user' && atomicSelection)",-- );++ expect(setModel).not.toContain("if (internalOptions.source !== 'user' && atomicSelection)");expect(setModel).toContain("internalOptions.source === 'user' || internalOptions.effortExplicit === true",);expect(setModel).toContain("internalOptions.source === 'user' || internalOptions.fastExplicit === true",);-- expect(setModel).toContain(-- "allowFixedEffortPlaceholder: internalOptions.source === 'user'",-- );++ expect(setModel).toContain("allowFixedEffortPlaceholder: internalOptions.source === 'user'");expect(axisValidation).toBeLessThan(setModel.indexOf('applyRuntimeSetModelChange({'));expect(axisValidation).toBeLessThan(setModel.indexOf('persistSessionFields(sessionId'));});@@@ -381,14 -390,14 +401,15 @@@resolveAxes,);const commitEffort = persistRoute.indexOf('setSessionEffort(sessionId, finalEffort);', persist);-- const commitFast = persistRoute.indexOf('setSessionFastMode(sessionId, finalFastMode);', persist);++ const commitFast = persistRoute.indexOf(++ 'setSessionFastMode(sessionId, finalFastMode);',++ persist,++ );const broadcast = persistRoute.indexOf('broadcastSessionPatched(sessionId, patch);', persist);expect(persistRoute).toContain('const [desiredRow] = await getDbClient()');expect(persistRoute).toContain('const restoringPreviousRoute =');-- expect(persistRoute).toContain(-- 'let finalEffort = restoringPreviousRoute && route.effort',-- );++ expect(persistRoute).toContain('let finalEffort = restoringPreviousRoute && route.effort');expect(persistRoute).toContain('let finalFastMode = restoringPreviousRoute && route.fastMode !== undefined',);@@@ -426,9 -435,9 +447,7 @@@expect(setModel).toContain('atomicSelection.effort === null');expect(setModel).toContain('isDeviceLinkInvoke() ||');-- expect(setModel).toContain(-- "(atomicSelection?.effort === null && runtimeAgentKind !== 'pi')",-- );++ expect(setModel).toContain("(atomicSelection?.effort === null && runtimeAgentKind !== 'pi')");expect(setModel).toContain('!rebuildLiveOrcaWorker && !atomicSelection');expect(setModel).toContain('{ wake: false }');expect(setModel).toContain("runtimeAgentKind !== 'pi' &&");@@@ -471,9 -480,9 +490,7 @@@expect(registerSource).toContain('function localModelWindowSwitchErrorCode(code: IpcErrorCode): IpcErrorCode',);-- expect(registerSource).toContain(-- "return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;",-- );++ expect(registerSource).toContain("return isDeviceLinkInvoke() ? 'PRECONDITION_FAILED' : code;");expect(setModel).toContain('await maker.getSessionMeta(sessionId)');expect(setModel).toContain('liveSessionBeforeRouteChange?.model ?? persistedSessionMeta?.model',@@@ -498,13 -507,13 +515,13 @@@expect(setModel).toContain('return deferLockedSelection()');expect(setModel).toContain("preparation === 'remote-unsupported'");expect(setModel).toContain('beforeClose: () => {');-- expect(setModel).toContain('clearPendingCredentialSwitchForSession(sessionId, { wake: false })');++ expect(setModel).toContain(++ 'clearPendingCredentialSwitchForSession(sessionId, { wake: false })',++ );expect(setModel).toContain('sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)');expect(setModel).toContain('modelWindowRebuilt ||');expect(setModel).toContain('patch.contextWindow = targetContextWindow;');-- expect(setModel).toContain(-- '(rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection)',-- );++ expect(setModel).toContain('(rebuildLiveOrcaWorker || modelWindowRebuilt || atomicSelection)');expect(setModel).toContain('wakeSessionInputAfterCredentialSwitch(sessionId);');});@@@ -600,7 -609,7 +617,10 @@@// sessions.effort 列是 NOT NULL——把 null 写进 DB patch 会让整个模型切换被// NOT NULL 约束炸掉(issue #3691)。持久化 patch 必须省略该字段,内存 store// 照常清 null,重启后按目标模型能力重新归一化。-- const atomicPatch = setModel.indexOf('if (atomicSelection) {', setModel.indexOf('const patch: Record<string, unknown>'));++ const atomicPatch = setModel.indexOf(++ 'if (atomicSelection) {',++ setModel.indexOf('const patch: Record<string, unknown>'),++ );expect(atomicPatch).toBeGreaterThan(-1);const persistCall = setModel.indexOf('persistSessionFields(sessionId', atomicPatch);expect(persistCall).toBeGreaterThan(atomicPatch);@@@ -707,11 -716,11 +727,17 @@@expect(terminalGuard).toBeGreaterThan(setModel.indexOf('const applyLocked = async () => {'));expect(terminalGuard).toBeLessThan(setModel.indexOf('acceptSessionRuntimeMutation({'));expect(terminalGuard).toBeLessThan(setModel.indexOf('applyRuntimeSetModelChange({'));-- expect(setModel).toContain('internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked)');++ expect(setModel).toContain(++ 'internalOptions.sessionLockHeld ? applyLocked() : withSendToSessionLock(sessionId, applyLocked)',++ );});it('stages user routes before every runtime mutation and prevents remote persistence of the source route', () => {-- const body = handlerBody(registerSource, 'const handleSetModel = async (', 'const recoverRemoteRuntimeAxisPersistence');++ const body = handlerBody(++ registerSource,++ 'const handleSetModel = async (',++ 'const recoverRemoteRuntimeAxisPersistence',++ );const stage = body.indexOf('agentSwitchPending.set(sessionId, intent)');expect(stage).toBeGreaterThan(body.indexOf('assertModelRouteUsable('));expect(stage).toBeGreaterThan(body.indexOf('resolveSessionRuntimeAxes('));@@@ -723,11 -732,11 +749,17 @@@expect(early).toContain('markRemoteSettingPersistedInsideHandler(response)');expect(early).not.toContain('persistSessionFields(');expect(early).not.toContain('closeSession(');-- expect(body).toContain("internalOptions.source === 'user' && agentSwitchPending.get(sessionId)?.sameAgentSelection");++ expect(body).toContain(++ "internalOptions.source === 'user' && agentSwitchPending.get(sessionId)?.sameAgentSelection",++ );});it('resumes native Codex history across credentials and reserves window rebuilding for send', () => {-- const body = handlerBody(registerSource, 'const handleSetModel = async (', 'const recoverRemoteRuntimeAxisPersistence');++ const body = handlerBody(++ registerSource,++ 'const handleSetModel = async (',++ 'const recoverRemoteRuntimeAxisPersistence',++ );expect(body).not.toContain('forkSdkSession(');expect(body).not.toContain('relinkCodexProviderThread(');expect(body).not.toContain('prepareNativeSessionRecovery(');@@@ -735,7 -744,7 +767,9 @@@expect(body).toContain('confirmedTargetPressure:');expect(body).toContain('internalOptions.applyingUserSelectionOnSend === true');expect(body).toContain('if (atomicSelection.effort !== null)');-- expect(registerSource).toContain('sessionLockHeld: true, applyingUserSelectionOnSend: applyNow');++ expect(registerSource).toContain(++ 'sessionLockHeld: true, applyingUserSelectionOnSend: applyNow',++ );});it('rejects terminal tasks before effort or Fast mutations recreate runtime state', () => {@@@ -903,7 -912,7 +937,6 @@@});// persists Pi runtime-verified windows without catalog replacement: covered by the executable sessionEventPipeline tests.--it('counts fallback eligibility across the whole interrupted-turn episode', () => {expect(registerSource).toContain('decision.episodeAttempt,\n decision.attemptToken,',@@@ -1002,7 -1011,7 +1035,9 @@@'setSessionProvider(sessionId, previousRuntime.providerId);',);expect(restoreControlStores).toContain('setSessionEffort(sessionId, previousRuntime.effort);');-- expect(restoreControlStores).toContain('setSessionFastMode(sessionId, previousRuntime.fastMode);');++ expect(restoreControlStores).toContain(++ 'setSessionFastMode(sessionId, previousRuntime.fastMode);',++ );expect(rollback).not.toContain('.send(');expect(rollback).toContain('throw persistenceError;');});@@@ -1050,9 -1059,9 +1085,9 @@@const apply = setModel.indexOf('await applyRuntimeSetModelChange({');expect(setModel.indexOf('return deferLockedSelection()')).toBeLessThan(apply);-- expect(-- setModel.indexOf('cold remote Pi runtime cannot verify the target window'),-- ).toBeLessThan(apply);++ expect(setModel.indexOf('cold remote Pi runtime cannot verify the target window')).toBeLessThan(++ apply,++ );expect(setModel).toContain("runtimeAgentKind === 'pi' && runtimeRouteChanged");expect(setModel).not.toContain('busy Pi task cannot change runtime selection');expect(setModel).toContain('finalPiWindow < verifiedCurrentWindow!');@@@ -1115,7 -1124,7 +1150,9 @@@finalWindow,);expect(finalRemotePressureRejection).toBeGreaterThan(finalWindow);-- expect(setModel).toContain('targetContextWindow = confirmedContextWindow ?? targetContextWindow');++ expect(setModel).toContain(++ 'targetContextWindow = confirmedContextWindow ?? targetContextWindow',++ );expect(setModel).toContain('confirmedContextWindow === targetContextWindow');expect(setModel).toContain('confirmedContextWindow === finalPiWindow');expect(finalPreparation).toBeGreaterThan(smallerFinalWindow);@@@ -1134,13 -1143,13 +1171,13 @@@'const recoverRemoteRuntimeAxisPersistence',);const refreshStart = setModel.indexOf(-- "if (!response.deferred) {\n try {\n const currentAgentKind =",++ 'if (!response.deferred) {\n try {\n const currentAgentKind =',);const refreshEnd = setModel.indexOf('const projectionMeta =', refreshStart);const refresh = setModel.slice(refreshStart, refreshEnd);expect(setModel).toContain(-- "effectiveProviderId === undefined\n ? (previousRuntime.pendingCredentialSwitch?.providerId ?? currentProviderId)",++ 'effectiveProviderId === undefined\n ? (previousRuntime.pendingCredentialSwitch?.providerId ?? currentProviderId)',);expect(refresh).toContain('model,\n targetRouteProviderId,');expect(refresh).not.toContain(@@@ -1159,9 -1168,9 +1196,9 @@@const contextSnapshot = setModel.indexOf('await recordSessionContextSnapshot(');expect(runtimeCommit).toBeGreaterThan(-1);expect(contextSnapshot).toBeGreaterThan(runtimeCommit);-- expect(setModel.indexOf('recordUserSessionRuntimeMutation(sessionId)', runtimeCommit)).toBeLessThan(-- contextSnapshot,-- );++ expect(++ setModel.indexOf('recordUserSessionRuntimeMutation(sessionId)', runtimeCommit),++ ).toBeLessThan(contextSnapshot);expect(setModel.indexOf('settlePendingSessionRuntimeMutation(', runtimeCommit)).toBeLessThan(contextSnapshot,);@@@ -1216,7 -1225,7 +1253,9 @@@expect(setModel).toContain('acceptSessionRuntimeAxisMutation({');expect(setModel).toContain("runtimeAgentKind !== 'pi' &&");expect(setModel).toContain('(routeExplicit || internalOptions.effortExplicit === true)');-- expect(setModel).toContain('applyFastMode: routeExplicit || internalOptions.fastExplicit === true');++ expect(setModel).toContain(++ 'applyFastMode: routeExplicit || internalOptions.fastExplicit === true',++ );});it('defers in-turn selections with the clicked effort/Fast snapshot', () => {diff --cc apps/desktop/src/main/bootstrap-electron.tsindex 8eef1cacdb,d8109809b4..3540219c6e--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@@ -292,7 -312,7 +312,10 @@@ import} from './rsb-browser-bridge/native-popup-surfaces.js';import { disposeAndroidAdb } from './mcp-integrations/android.js';import { shutdownCodexEnvironment } from './mcp-integrations/codexEnvironment.js';- import { shutdownPiEnvironment } from './mcp-integrations/piEnvironment.js';-import { invalidatePiEnvironment, shutdownPiEnvironment } from './mcp-integrations/piEnvironment.js';++import {++ invalidatePiEnvironment,++ shutdownPiEnvironment,++} from './mcp-integrations/piEnvironment.js';import { fetchRemoteMediaImageBytes } from './device-link/remoteMediaProtocol';import * as imageCacheStore from './imageCacheStore';import {@@@ -409,6 -456,8 +459,15 @@@ import} from './database-size-warning-settings';import { createDatabaseSizeWarningSettingsWatcher } from './database-size-warning-settings-watcher.js';import { createLocalDbMaintenanceIpcHandlers } from './localDb/ipc/maintenance';-import { createDialogueWorkspaceHandlers, checkDialogueDirectoryWritable, customDialogueWorkspaceRoot } from './dialogue-workspace-ipc.js';-import { readDialogueWorkspaceSettings, writeDialogueWorkspaceDirectory } from './dialogue-workspace-settings.js';++import {++ createDialogueWorkspaceHandlers,++ checkDialogueDirectoryWritable,++ customDialogueWorkspaceRoot,++} from './dialogue-workspace-ipc.js';++import {++ readDialogueWorkspaceSettings,++ writeDialogueWorkspaceDirectory,++} from './dialogue-workspace-settings.js';import { writeDbSlimmingDevRelaunchSignal } from './localDb/devDbSlimmingRelaunch';import {cancelDbSlimmingStartupProgress,@@@ -4034,7 -4102,7 +4112,8 @@@ const createWindow = () =>restoreFullscreen: shouldRestoreMacFullscreen,});refreshWindowsAppBadge();- if (!app.isPackaged) markDesktopDevWindowReady(mainWindow.webContents.getOSProcessId());- if (!app.isPackaged || isCindyVersionLaunchPending()) markDesktopDevWindowReady();++ if (!app.isPackaged || isCindyVersionLaunchPending())++ markDesktopDevWindowReady(mainWindow.webContents.getOSProcessId());void runComputerUseSmokeIfRequested();// 资源用量窗口不应与主窗口首帧争 CPU。主窗口可见后再后台完成 BrowserWindow、// renderer 和首份进程快照预热;回调绑定当代主窗口,重建/退出后不会创建孤儿窗。@@@ -8165,6 -8360,46 +8371,48 @@@ const registerIpcHandlers = () =>}),);+ // Native folder selection belongs to this computer; intentionally not exposed via device-link.+ const dialogueWorkspaceHandlers = createDialogueWorkspaceHandlers({+ captureScope: () => {+ if (!getActiveAppSession().dataOwnerId || isAppSessionBoundaryPending()) {+ throwIpcError('PRECONDITION_FAILED', 'dialogue workspace requires an active owner');+ }+ return activeOwnerScopeKey();+ },+ isScopeCurrent: (scope) => !isAppSessionBoundaryPending() && activeOwnerScopeKey() === scope,+ read: readDialogueWorkspaceSettings,+ write: writeDialogueWorkspaceDirectory,+ chooseDirectory: async () => {+ const options: Electron.OpenDialogOptions = {+ title: t('settings.about.storage.dialogueDirectoryChoose'),+ properties: ['openDirectory', 'createDirectory'],+ };+ const ownerWindow = BrowserWindow.getFocusedWindow() ?? mainWindowRef;- const result = ownerWindow && !ownerWindow.isDestroyed()- ? await dialog.showOpenDialog(ownerWindow, options)- : await dialog.showOpenDialog(options);++ const result =++ ownerWindow && !ownerWindow.isDestroyed()++ ? await dialog.showOpenDialog(ownerWindow, options)++ : await dialog.showOpenDialog(options);+ return result.canceled ? null : (result.filePaths[0] ?? null);+ },+ // Dedicated owner subtree prevents unrelated folders from being treated as managed tasks.- resolveDirectory: (selected) => customDialogueWorkspaceRoot(selected, path.basename(ownerScopedUserDataPath())),++ resolveDirectory: (selected) =>++ customDialogueWorkspaceRoot(selected, path.basename(ownerScopedUserDataPath())),+ checkWritable: checkDialogueDirectoryWritable,+ openDirectory: (directory) => shell.openPath(directory),+ });+ for (const action of ['get', 'choose', 'reset', 'open'] as const) {+ ipcMain.handle('dialogue-workspace:' + action, async (event) => {+ assertTrustedAppRendererEvent(event);+ try {+ return await dialogueWorkspaceHandlers[action]();+ } catch (error) {+ if (isIpcError(error)) throw error;+ dbClientLog.warn('dialogue workspace settings request failed', { action });+ throwIpcError('INTERNAL', 'dialogue workspace settings request failed');+ }+ });+ }+const localDbMaintenanceHandlers = createLocalDbMaintenanceIpcHandlers({captureOwner: () => {const ownerId = getActiveAppSession().dataOwnerId;diff --cc apps/desktop/src/main/remote-desktop/__tests__/linuxAudio.test.tsindex 9eda47899d,0000000000..cd597210b4mode 100644,000000..100644--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxAudio.test.ts+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxAudio.test.ts@@@ -1,71 -1,0 +1,98 @@@+import { EventEmitter } from 'node:events';+import { PassThrough } from 'node:stream';+import type { ChildProcessWithoutNullStreams } from 'node:child_process';+import { afterEach, expect, it, vi } from 'vitest';+import { LinuxDesktopAudio } from '../linuxAudio';++function fixture() {+ const child = Object.assign(new EventEmitter(), {+ stdin: new PassThrough(),+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ kill: vi.fn(),+ });+ const capture = new LinuxDesktopAudio(() => child as unknown as ChildProcessWithoutNullStreams);+ return { child, capture };+}+afterEach(() => vi.useRealTimers());+++it('contains synchronous launch failure and can start again without retaining old callbacks', () => {++ const old = fixture().child;++ const next = fixture().child;++ const launch = vi++ .fn()++ .mockReturnValueOnce(old)++ .mockImplementationOnce(() => {++ throw new Error('spawn failed');++ })++ .mockReturnValueOnce(next);++ const capture = new LinuxDesktopAudio(launch);++ try {++ capture.start();++ expect(() => capture.start()).not.toThrow();++ expect(old.kill).toHaveBeenCalledOnce();++ expect(() => capture.read()).toThrow('DESKTOP_AUDIO_UNAVAILABLE');++ capture.start();++ old.emit('error', new Error('late error'));++ old.emit('exit');++ next.stdout.write(Buffer.alloc(8, 42));++ expect([...capture.read()]).toEqual(Array(8).fill(42));++ expect(next.kill).not.toHaveBeenCalled();++ } finally {++ capture.stop();++ }++});+++it('retains sample alignment across chunks and bounds history to 100 ms', () => {+ const { child, capture } = fixture();+ try {+ capture.start();+ child.stdout.write(Buffer.from([1, 2, 3]));+ expect(capture.read()).toHaveLength(0);+ child.stdout.write(Buffer.from([4, 5, 6, 7, 8, 9]));+ expect([...capture.read()]).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);+ child.stdout.write(Buffer.alloc(80000, 42));+ expect(capture.read()).toHaveLength(38392);+ child.stdout.write(Buffer.alloc(7, 43));+ expect([...capture.read()]).toEqual([42, 43, 43, 43, 43, 43, 43, 43]);+ } finally {+ capture.stop();+ }+});++it('erases buffered sound on stop and ignores late callbacks', () => {+ const { child, capture } = fixture();+ capture.start();+ child.stdout.write(Buffer.alloc(80));+ capture.stop();+ child.stdout.write(Buffer.alloc(80));+ expect(() => capture.read()).toThrow('DESKTOP_AUDIO_UNAVAILABLE');+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+});++it('stops a producer when its renderer no longer consumes audio', () => {+ vi.useFakeTimers();+ const { child, capture } = fixture();+ capture.start();+ vi.advanceTimersByTime(4000);+ expect(child.kill).toHaveBeenCalledOnce();+ expect(() => capture.read()).toThrow('DESKTOP_AUDIO_UNAVAILABLE');+});++it('surfaces a native capture failure without exposing native diagnostics', () => {+ const { child, capture } = fixture();+ capture.start();+ child.emit('error', new Error('private native details'));+ expect(() => capture.read()).toThrow('DESKTOP_AUDIO_UNAVAILABLE');+});+it('fails a stalled producer even while the renderer keeps polling', () => {+ vi.useFakeTimers();+ const { child, capture } = fixture();+ capture.start();+ for (let i = 0; i < 6; i++) {+ capture.read();+ vi.advanceTimersByTime(1000);+ }+ expect(child.kill).toHaveBeenCalledOnce();+ expect(() => capture.read()).toThrow('DESKTOP_AUDIO_UNAVAILABLE');+});diff --cc apps/desktop/src/main/remote-desktop/linuxAudio.tsindex 240c48ace4,0000000000..963bdea9dbmode 100644,000000..100644--- a/apps/desktop/src/main/remote-desktop/linuxAudio.ts+++ b/apps/desktop/src/main/remote-desktop/linuxAudio.ts@@@ -1,103 -1,0 +1,110 @@@+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';+import { accessSync, constants } from 'node:fs';++const executable = '/usr/bin/pw-record';+const bytesPerFrame = 8; // Stereo float32, 48 kHz.+const maxBytes = 4800 * bytesPerFrame; // Never retain more than 100 ms.++export function supportsLinuxAudio(): boolean {+ if (process.platform !== 'linux') return false;+ try {+ accessSync(executable, constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++/** Ephemeral output-monitor capture owned by the authorized video lease.+ * PipeWire's sink capture policy follows the default output, never the microphone.+ * Bytes remain in memory and stale samples are dropped instead of building latency.+ */+export class LinuxDesktopAudio {+ private child: ChildProcessWithoutNullStreams | null = null;+ private samples: Buffer = Buffer.alloc(0);+ private failed = false;+ private lastRead = 0;+ private lastData = 0;+ private watchdog: ReturnType<typeof setInterval> | undefined;+ constructor(+ private readonly launch = () =>+ spawn(+ executable,+ [+ '--raw',+ '--format',+ 'f32',+ '--rate',+ '48000',+ '--channels',+ '2',+ '--latency',+ '20ms',+ '--properties',+ '{ stream.capture.sink=true node.name=cindy-desktop-audio media.role=Screen }',+ '-',+ ],+ { stdio: 'pipe' },+ ),+ ) {}++ start(): void {+ this.stop();+ this.failed = false;- const child = this.launch();++ let child: ChildProcessWithoutNullStreams;++ try {++ child = this.launch();++ } catch {++ // Audio is optional: surface failure through read(), never abort the video offer.++ this.failed = true;++ return;++ }+ this.child = child;+ this.lastRead = Date.now();+ this.lastData = this.lastRead;+ child.stderr.resume(); // Never expose native diagnostics or sampled content.+ child.stdin.on('error', () => {});+ child.stdout.on('data', (chunk: Buffer) => {+ if (this.child !== child) return;+ if (chunk.length) this.lastData = Date.now();+ const joined = Buffer.concat([this.samples, chunk]);+ const discard = Math.max(+ 0,+ Math.ceil((joined.length - maxBytes) / bytesPerFrame) * bytesPerFrame,+ );+ this.samples = Buffer.from(joined.subarray(discard));+ });+ const failed = () => {+ if (this.child !== child) return;+ this.stop();+ this.failed = true;+ };+ child.once('error', failed);+ child.once('exit', failed);+ this.watchdog = setInterval(() => {+ if (Date.now() - this.lastRead > 3000 || Date.now() - this.lastData > 5000) failed();+ }, 1000);+ this.watchdog.unref();+ }++ read(): Uint8Array {+ if (!this.child || this.failed) throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ this.lastRead = Date.now();+ const size = this.samples.length - (this.samples.length % bytesPerFrame);+ const result = Uint8Array.from(this.samples.subarray(0, size));+ this.samples = Buffer.from(this.samples.subarray(size));+ return result;+ }++ stop(): void {+ const child = this.child;+ this.child = null;+ this.samples = Buffer.alloc(0);+ clearInterval(this.watchdog);+ this.watchdog = undefined;+ if (child) {+ child.stdin.destroy();+ child.kill('SIGKILL');+ }+ }+}diff --cc apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.tsindex 8aeda9d618,8aeda9d618..4a8e95acbe--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/captureAudioRecovery.test.ts@@@ -72,6 -72,6 +72,8 @@@ function setup()let command!: (value: any) => void;const reply = vi.fn(async () => {});const api = {++ stop: vi.fn(async () => {}),++ nativeAudio: vi.fn(async () => new Uint8Array(0)),onCommand: (callback: typeof command) => {command = callback;return () => {};@@@ -80,7 -80,7 +82,7 @@@reply,};disposers.push(startDesktopCaptureHost(api as any));-- const offer = (audio = true, overlay = true) =>++ const offer = (audio = true, overlay = true, nativeAudio = false) =>command({id: 'offer',op: 'offer',@@@ -89,12 -89,12 +91,91 @@@attemptId: 'attempt',sourceId: 'screen:1',nativeCapture: true,++ nativeAudio,cursorOverlay: overlay,settings: { audio, fps: 30 },});-- return { video, nativeStop, peers, capture, reply, offer, stop: () => command({ op: 'stop' }) };++ return {++ api,++ video,++ nativeStop,++ peers,++ capture,++ reply,++ offer,++ stop: () => command({ op: 'stop' }),++ };++}++++function nativeSound() {++ const sound = media().sound;++ const close = vi.fn(async () => {});++ vi.stubGlobal(++ 'AudioContext',++ class {++ close = close;++ async resume() {}++ createMediaStreamDestination() {++ return { stream: { getTracks: () => [sound], getAudioTracks: () => [sound] } };++ }++ },++ );++ return { sound, close };}++it.each(['startup', 'connected'] as const)(++ 'isolates %s native audio failure from video and the lease',++ async (phase) => {++ const h = setup();++ const audio = nativeSound();++ if (phase === 'startup') h.api.nativeAudio.mockRejectedValueOnce(new Error('audio failed'));++ h.offer(true, true, true);++ await flush();++ expect(h.reply).toHaveBeenCalledWith('offer', 'answer');++ if (phase === 'connected') {++ h.api.nativeAudio.mockRejectedValueOnce(new Error('audio failed'));++ await vi.advanceTimersByTimeAsync(20);++ }++ expect(audio.sound.stop).toHaveBeenCalledOnce();++ expect(audio.close).toHaveBeenCalledOnce();++ expect(h.peers[0].close).not.toHaveBeenCalled();++ expect(h.nativeStop).not.toHaveBeenCalled();++ expect(h.video.video.stop).not.toHaveBeenCalled();++ expect(h.api.stop).not.toHaveBeenCalled();++ },++);++++it.each(['resolve', 'reject'] as const)(++ 'fences late native audio startup %s after a replacement offer',++ async (outcome) => {++ const h = setup();++ const old = nativeSound();++ let resolve!: (bytes: Uint8Array<ArrayBuffer>) => void;++ let reject!: (error: Error) => void;++ h.api.nativeAudio.mockImplementationOnce(++ () =>++ new Promise((yes, no) => {++ resolve = yes;++ reject = no;++ }),++ );++ h.offer(true, true, true);++ await flush();++ const current = nativeSound();++ h.offer(true, true, true);++ await flush();++ if (outcome === 'resolve') resolve(new Uint8Array(0));++ else reject(new Error('old audio failed'));++ await flush();++ expect(old.sound.stop).toHaveBeenCalledOnce();++ expect(current.sound.stop).not.toHaveBeenCalled();++ expect(h.peers).toHaveLength(1);++ expect(h.peers[0].close).not.toHaveBeenCalled();++ expect(h.api.stop).not.toHaveBeenCalled();++ expect(h.reply).toHaveBeenCalledTimes(1);++ },++);++it.each(['rejected', 'missing', 'without-overlay'])('keeps video after %s audio and restores only its audio sender when permission becomes ready',async (mode) => {diff --cc apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeAudioStream.test.tsindex 83c16ec67c,0000000000..4d6083270fmode 100644,000000..100644--- a/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeAudioStream.test.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/__tests__/nativeAudioStream.test.ts@@@ -1,70 -1,0 +1,69 @@@+import { afterEach, expect, it, vi } from 'vitest';+import { nativeAudioStream } from '../nativeAudioStream';++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});+function setup() {+ vi.useFakeTimers();+ const track = { stop: vi.fn() };+ const close = vi.fn(async () => {});+ const channels: Float32Array[] = [];+ const nodes: { stop: ReturnType<typeof vi.fn>; start: ReturnType<typeof vi.fn> }[] = [];+ vi.stubGlobal(+ 'AudioContext',+ class {+ currentTime = 0;+ close = close;+ async resume() {}+ createMediaStreamDestination() {+ return { stream: { getTracks: () => [track], getAudioTracks: () => [track] } };+ }+ createBuffer(_channels: number, frames: number) {+ const data = [new Float32Array(frames), new Float32Array(frames)];+ channels.push(...data);+ return { getChannelData: (channel: number) => data[channel] };+ }+ createBufferSource() {+ const node = { connect: vi.fn(), disconnect: vi.fn(), stop: vi.fn(), start: vi.fn() };+ nodes.push(node);+ return node;+ }+ },+ );+ return { track, close, channels, nodes };+}+it('deinterleaves bounded stereo PCM and erases sources and polling on stop', async () => {+ const h = setup();+ const pcm = new Uint8Array(new Float32Array([0.5, -0.25, NaN, 2]).buffer);+ const read = vi.fn(async () => pcm);- const owner = await nativeAudioStream(read, () => true, vi.fn());++ const owner = await nativeAudioStream(read, () => true);+ expect([...h.channels[0]]).toEqual([0.5, 0]);+ expect([...h.channels[1]]).toEqual([-0.25, 1]);+ owner.stop();+ await vi.advanceTimersByTimeAsync(100);+ expect(read).toHaveBeenCalledOnce();+ expect(h.track.stop).toHaveBeenCalledOnce();+ expect(h.nodes[0].stop).toHaveBeenCalledOnce();+ expect(h.close).toHaveBeenCalledOnce();+});+it('discards a read that completes after authorization ends', async () => {+ const h = setup();+ let valid = true;+ let finish!: (value: Uint8Array) => void;+ const pending = nativeAudioStream(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ () => valid,- vi.fn(),+ );+ const rejected = expect(pending).rejects.toThrow('DESKTOP_AUDIO_UNAVAILABLE');+ await Promise.resolve();+ valid = false;+ finish(new Uint8Array(80));+ await rejected;+ expect(h.nodes).toHaveLength(0);+ expect(h.close).toHaveBeenCalledOnce();+});diff --cc apps/desktop/src/renderer/features/remote-desktop/captureHost.tsindex b809a19f96,80584060d9..1ab7586fb0--- a/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/captureHost.ts@@@ -247,23 -220,6 +247,24 @@@ export function startDesktopCaptureHostreturn;}stream = captured;+ if (command.nativeAudio && command.settings?.audio && api.nativeAudio) {- const value = await nativeAudioStream(- () => api.nativeAudio!(lease),- () => current === generation,- () => {- stop();- void api.stop().catch(() => {});- },- );- if (current !== generation) {- value.stop();- return;++ try {++ const value = await nativeAudioStream(++ () => api.nativeAudio!(lease),++ () => current === generation,++ );++ if (current !== generation) {++ value.stop();++ return;++ }++ audio = value;++ captured.addTrack(value.track);++ } catch {++ // Optional audio owns only its resources; video and the lease stay alive.++ if (current !== generation) return;+ }- audio = value;- captured.addTrack(value.track);+ }+ stream = captured;const rtc = new RTCPeerConnection({iceServers: command.iceServers ?? REMOTE_DESKTOP_ICE_SERVERS,});diff --cc apps/desktop/src/renderer/features/remote-desktop/nativeAudioStream.tsindex 96fc1e7872,0000000000..af0d7a4ad4mode 100644,000000..100644--- a/apps/desktop/src/renderer/features/remote-desktop/nativeAudioStream.ts+++ b/apps/desktop/src/renderer/features/remote-desktop/nativeAudioStream.ts@@@ -1,73 -1,0 +1,71 @@@+/** Bounded PCM scheduling into the existing WebRTC stream; never plays locally. */+export async function nativeAudioStream(+ read: () => Promise<Uint8Array>,+ current: () => boolean,- failed: () => void,+): Promise<{ track: MediaStreamTrack; stop(): void }> {+ const context = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });+ const destination = context.createMediaStreamDestination();+ const sources = new Set<AudioBufferSourceNode>();+ let stopped = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let next = 0;+ const stop = () => {+ if (stopped) return;+ stopped = true;+ clearTimeout(timer);+ for (const source of sources) source.stop();+ sources.clear();+ destination.stream.getTracks().forEach((track) => track.stop());+ void context.close().catch(() => {});+ };+ const poll = async () => {+ if (stopped || !current()) return stop();+ try {+ const bytes = await read();+ if (stopped || !current()) return stop();+ if (!(bytes instanceof Uint8Array) || bytes.byteLength > 38400 || bytes.byteLength % 8)+ throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ if (bytes.length) {+ const frames = bytes.length / 8;+ const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const buffer = context.createBuffer(2, frames, 48000);+ for (let channel = 0; channel < 2; channel++) {+ const output = buffer.getChannelData(channel);+ for (let i = 0; i < frames; i++) {+ const value = data.getFloat32(i * 8 + channel * 4, true);+ output[i] = Number.isFinite(value) ? Math.max(-1, Math.min(1, value)) : 0;+ }+ }+ // Discard queued history after a renderer stall; preserve only live audio.+ if (next > context.currentTime + 0.15) {+ for (const source of sources) source.stop();+ sources.clear();+ next = 0;+ }+ next = Math.max(context.currentTime + 0.02, next);+ const source = context.createBufferSource();+ source.buffer = buffer;+ source.connect(destination);+ source.onended = () => {+ sources.delete(source);+ source.disconnect();+ };+ sources.add(source);+ source.start(next);+ next += frames / 48000;+ }+ timer = setTimeout(() => void poll(), 20);+ } catch {+ stop();- if (current()) failed();+ }+ };+ try {+ await context.resume();+ await poll();+ if (stopped) throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ return { track: destination.stream.getAudioTracks()[0], stop };+ } catch {+ stop();+ throw new Error('DESKTOP_AUDIO_UNAVAILABLE');+ }+}diff --cc docs/remote-desktop.mdindex 93f995beee,b0245b2594..0eca689cad--- a/docs/remote-desktop.md+++ b/docs/remote-desktop.md@@@ -503,20 -399,7 +503,23 @@@ System audio defaults on with the viewesingle-use display capture grant tied to the current offer, lease and trustedmain renderer. No microphone is captured. macOS packaging declaresNSAudioCaptureUsageDescription; development launchers must also have the OS-permission. Linux audio is not advertised.+permission. Hyprland hosts with `pw-record` capture the default PipeWire output+monitor as 48 kHz stereo float PCM. The trusted capture renderer schedules at most+150 ms into an AudioContext destination and adds its track to the existing WebRTC+stream; it never connects to local speakers. Main retains at most 100 ms of PCM,+checks the exact capture window and opted-in video lease on every read, and stops+the child on disconnect, capture failure, a stalled producer or absent consumer.++Native audio launch/read failures clean up only audio resources: the video answer,++connected video/control channel and lease remain valid. A later offer starts a new++audio capture; callbacks from a retired capture cannot affect its replacement.+This does not add audio to the compatibility JPEG transport.++Linux host mute uses PipeWire `softMute` on the playback branch, retaining the+monitor signal for the phone. It restores the original state of the exact output+object (including its serial), even if the default output changes; an unplugged+output cannot cause restoration to modify a reused node ID. Requires `pactl`,+`pw-dump` and `pw-cli`. A null-output integration test verifies that playback mute+leaves the captured tone nonzero; Chromium/WebRTC tests verify remote decoding.`displayModes` and `resolution` operate on the lease's display. macOS usesCoreGraphics mode enumeration and applies only an available mode ID for the