Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(remote-desktop): restore Linux host state after transitions

Dash Huang76e5ead7300c
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxMute.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxMute.test.ts
index 0325f39048..5f6726462e 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxMute.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxMute.test.ts
@@ -1,4 +1,5 @@
-import { expect, it, vi } from 'vitest';
+import { afterEach, expect, it, vi } from 'vitest';
+afterEach(() => vi.useRealTimers());
import { LinuxDesktopMute } from '../linuxMute';
function setup(muted = false) {
const sink = {
@@ -9,9 +10,10 @@ function setup(muted = false) {
},
};
let name = 'speakers';
+ const extra = new Map<string, typeof sink>();
const run = vi.fn(async (tool: string) => {
if (tool === 'pactl') return name;
- if (tool === 'pw-dump') return JSON.stringify([sink]);
+ if (tool === 'pw-dump') return JSON.stringify([sink, ...extra.values()]);
return '';
});
return {
@@ -21,6 +23,15 @@ function setup(muted = false) {
setDefault: (value: string) => {
name = value;
},
+ addSink: (value: string, id: number, serial: number) => {
+ extra.set(value, {
+ id,
+ info: {
+ props: { 'object.serial': serial, 'node.name': value, 'media.class': 'Audio/Sink' },
+ params: { Props: [{ softMute: false }] },
+ },
+ });
+ },
};
}
it('restores the original output after default changes and stop races mute', async () => {
@@ -35,6 +46,33 @@ it('restores the original output after default changes and stop races mute', asy
'{ softMute: false }',
]);
});
+
+it('mutes a newly selected default output and restores every changed sink', async () => {
+ vi.useFakeTimers();
+ const h = setup();
+ h.addSink('headphones', 63, 456);
+ await h.mute.set(true);
+ h.setDefault('headphones');
+ await vi.advanceTimersByTimeAsync(1000);
+ await h.mute.set(false);
+ const writes = h.run.mock.calls.filter(([tool]) => tool === 'pw-cli');
+ expect(writes).toContainEqual(['pw-cli', ['set-param', '62', 'Props', '{ softMute: false }']]);
+ expect(writes).toContainEqual(['pw-cli', ['set-param', '63', 'Props', '{ softMute: false }']]);
+ h.mute.stop();
+ vi.useRealTimers();
+});
+
+it('keeps retrying exact sink restoration after a transient failure', async () => {
+ vi.useFakeTimers();
+ const h = setup();
+ await h.mute.set(true);
+ h.run.mockRejectedValueOnce(new Error('temporary pw failure'));
+ await expect(h.mute.set(false)).rejects.toThrow('DESKTOP_HOST_MUTE_UNAVAILABLE');
+ await vi.advanceTimersByTimeAsync(250);
+ expect(h.run.mock.calls.filter(([tool]) => tool === 'pw-cli').length).toBeGreaterThan(1);
+ h.mute.stop();
+ vi.useRealTimers();
+});
it('preserves pre-existing mute and retries failed restoration', async () => {
const h = setup(true);
await h.mute.set(true);
@@ -49,10 +87,23 @@ it('preserves pre-existing mute and retries failed restoration', async () => {
]);
});
it('does not touch a different output which reused an unplugged output ID', async () => {
+ vi.useFakeTimers();
const h = setup();
await h.mute.set(true);
h.run.mockClear();
h.sink.info.props['object.serial'] = 456;
await h.mute.set(false);
+ await vi.advanceTimersByTimeAsync(10000);
expect(h.run.mock.calls.some((c) => c[0] === 'pw-cli')).toBe(false);
});
+it('stops polling while restoration fails and bounds restoration retries', async () => {
+ vi.useFakeTimers();
+ const h = setup();
+ await h.mute.set(true);
+ h.run.mockClear();
+ h.run.mockRejectedValue(new Error('offline'));
+ await expect(h.mute.set(false)).rejects.toThrow('DESKTOP_HOST_MUTE_UNAVAILABLE');
+ await vi.advanceTimersByTimeAsync(20000);
+ expect(h.run).toHaveBeenCalledTimes(6);
+ expect(h.run.mock.calls.every(([tool]) => tool === 'pw-dump')).toBe(true);
+});
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts
index 2f9d5ffffe..c4b0b713cf 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/linuxWindowActions.test.ts
@@ -76,6 +76,24 @@ it('toggles an empty workspace and restores it on disconnect', async () => {
await h.windows.stop();
expect(h.workspace()).toBe('1');
});
+it('retries a lock-deferred restore after the compositor unlocks', async () => {
+ const h = fixture();
+ await h.windows.request('desktop', undefined, 'hyprland:eDP-2', () => true);
+ h.unlocked.mockResolvedValue(false);
+ await expect(h.windows.stop()).rejects.toThrow('DESKTOP_INPUT_UNAVAILABLE');
+ expect(h.workspace()).toMatch(/^cindy-desktop-/);
+ h.unlocked.mockResolvedValue(true);
+ await h.windows.unlock();
+ expect(h.workspace()).toBe('1');
+});
+it('does not restore an active desktop toggle merely because the host unlocks', async () => {
+ const h = fixture();
+ await h.windows.request('desktop', undefined, 'hyprland:eDP-2', () => true);
+ await h.windows.unlock();
+ expect(h.workspace()).toMatch(/^cindy-desktop-/);
+ await h.windows.stop();
+ expect(h.workspace()).toBe('1');
+});
it('uses typed Lua dispatchers on current Omarchy without replaying actions', async () => {
const h = fixture(true);
await h.windows.request('desktop', undefined, 'hyprland:eDP-2', () => true);
diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.ts
index fd57f916aa..f40dc1f2fe 100644
--- a/apps/desktop/src/main/remote-desktop/index.ts
+++ b/apps/desktop/src/main/remote-desktop/index.ts
@@ -872,7 +872,10 @@ export function registerRemoteDesktopIpc(
}
};
powerMonitor.on('lock-screen', () => sessionChanged());
- powerMonitor.on('unlock-screen', () => sessionChanged(true));
+ powerMonitor.on('unlock-screen', () => {
+ sessionChanged(true);
+ void linuxWindows.unlock().catch(() => {});
+ });
ipcMain.handle(DESKTOP_LOCAL.NATIVE_FRAME, async (event, lease: unknown) => {
captureWindow.assertSender(event);
if (
diff --git a/apps/desktop/src/main/remote-desktop/linuxMute.ts b/apps/desktop/src/main/remote-desktop/linuxMute.ts
index 7a5e4e5b32..49e4870323 100644
--- a/apps/desktop/src/main/remote-desktop/linuxMute.ts
+++ b/apps/desktop/src/main/remote-desktop/linuxMute.ts
@@ -22,8 +22,15 @@ interface Sink {
/** Mute playback only, leaving the monitor branch audible remotely. Object
* serial protects against numeric ID reuse after unplug. Writes are serialized. */
export class LinuxDesktopMute {
- private original: Sink | null = null;
+ private original = new Map<string, Sink>();
private tail: Promise<void> = Promise.resolve();
+ private watchTimer: ReturnType<typeof setInterval> | undefined;
+ private restoreTimer: ReturnType<typeof setTimeout> | undefined;
+ private restoreAttempt = 0;
+ private enabled = false;
+ private key(sink: Sink): string {
+ return `${sink.id}:${sink.serial}`;
+ }
constructor(
private readonly run = async (tool: string, args: string[]) => {
const { stdout } = await exec(`/usr/bin/${tool}`, args, {
@@ -55,30 +62,76 @@ export class LinuxDesktopMute {
: [];
});
}
- set(enabled: boolean): Promise<void> {
+ private async apply(enabled: boolean): Promise<void> {
+ const sinks = await this.sinks();
+ if (enabled) {
+ const name = (await this.run('pactl', ['get-default-sink'])).trim();
+ const current = sinks.find((sink) => sink.name === name);
+ if (!current) {
+ if (this.original.size) return;
+ throw new Error('DESKTOP_HOST_MUTE_UNAVAILABLE');
+ }
+ this.original.set(this.key(current), this.original.get(this.key(current)) ?? current);
+ for (const sink of sinks) {
+ if (!this.original.has(this.key(sink))) continue;
+ await this.run('pw-cli', ['set-param', String(sink.id), 'Props', `{ softMute: true }`]);
+ }
+ return;
+ }
+ const present = new Set(sinks.map((sink) => this.key(sink)));
+ for (const key of this.original.keys()) {
+ if (!present.has(key)) this.original.delete(key);
+ }
+ for (const sink of sinks) {
+ const saved = this.original.get(this.key(sink));
+ if (!saved) continue;
+ await this.run('pw-cli', [
+ 'set-param',
+ String(sink.id),
+ 'Props',
+ `{ softMute: ${saved.muted ? 'true' : 'false'} }`,
+ ]);
+ this.original.delete(this.key(sink));
+ }
+ // A missing exact id/serial is conclusively unplugged and must not be
+ // applied to a replacement node.
+ if (this.original.size === 0) this.restoreAttempt = 0;
+ }
+ private startWatch(): void {
+ if (this.watchTimer) return;
+ this.watchTimer = setInterval(() => {
+ void this.enqueue(true, true).catch(() => {});
+ }, 1000);
+ this.watchTimer.unref?.();
+ }
+ private stopWatch(): void {
+ clearInterval(this.watchTimer);
+ this.watchTimer = undefined;
+ clearTimeout(this.restoreTimer);
+ this.restoreTimer = undefined;
+ this.restoreAttempt = 0;
+ this.original.clear();
+ }
+ private scheduleRestore(): void {
+ if (this.enabled || this.restoreTimer || !this.original.size || this.restoreAttempt >= 5)
+ return;
+ const delay = [250, 500, 1000, 2000, 4000][this.restoreAttempt++];
+ this.restoreTimer = setTimeout(() => {
+ this.restoreTimer = undefined;
+ void this.enqueue(false, true)
+ .then(() => {
+ if (this.original.size) this.scheduleRestore();
+ })
+ .catch(() => this.scheduleRestore());
+ }, delay);
+ this.restoreTimer.unref?.();
+ }
+ private enqueue(enabled: boolean, background = false): Promise<void> {
const result = this.tail
.then(async () => {
- if (!enabled && !this.original) return;
- const sinks = await this.sinks();
- if (!this.original) {
- const name = (await this.run('pactl', ['get-default-sink'])).trim();
- const sink = sinks.find((s) => s.name === name);
- if (!sink) throw new Error('DESKTOP_HOST_MUTE_UNAVAILABLE');
- this.original = sink;
- }
- const original = this.original;
- if (!sinks.some((s) => s.id === original.id && s.serial === original.serial)) {
- this.original = null;
- if (enabled) throw new Error('DESKTOP_HOST_MUTE_UNAVAILABLE');
- return;
- }
- await this.run('pw-cli', [
- 'set-param',
- String(original.id),
- 'Props',
- `{ softMute: ${enabled || original.muted ? 'true' : 'false'} }`,
- ]);
- if (!enabled) this.original = null;
+ if (background && enabled !== this.enabled) return;
+ if (!enabled && !this.original.size) return;
+ await this.apply(enabled);
})
.catch(() => {
throw new Error('DESKTOP_HOST_MUTE_UNAVAILABLE');
@@ -86,4 +139,24 @@ export class LinuxDesktopMute {
this.tail = result.catch(() => {});
return result;
}
+ set(enabled: boolean): Promise<void> {
+ this.enabled = enabled;
+ clearTimeout(this.restoreTimer);
+ this.restoreTimer = undefined;
+ this.restoreAttempt = 0;
+ if (enabled) {
+ const result = this.enqueue(true);
+ this.startWatch();
+ return result;
+ }
+ clearInterval(this.watchTimer);
+ this.watchTimer = undefined;
+ const result = this.enqueue(false);
+ void result.catch(() => this.scheduleRestore());
+ return result;
+ }
+ stop(): void {
+ this.enabled = false;
+ this.stopWatch();
+ }
}
diff --git a/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts b/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts
index d2ad78cead..6469a7572b 100644
--- a/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts
+++ b/apps/desktop/src/main/remote-desktop/linuxWindowActions.ts
@@ -32,6 +32,7 @@ type Monitor = { name: string; activeWorkspace: { id: number; name: string } };
export class LinuxWindowActions {
private tail: Promise<unknown> = Promise.resolve();
private generation = 0;
+ private restorePending = false;
private lua?: boolean;
private desktop?: { monitor: string; original: number; temporary: string };
constructor(
@@ -166,11 +167,23 @@ export class LinuxWindowActions {
await this.dispatch('workspace', String(saved.original), check);
}
this.desktop = undefined;
+ this.restorePending = false;
}
stop(): Promise<void> {
this.generation++;
+ this.restorePending = true;
const stopped = this.tail.catch(() => {}).then(() => this.restore());
this.tail = stopped;
return stopped;
}
+ /** Retry a lock-deferred workspace restore after the compositor unlocks. */
+ unlock(): Promise<void> {
+ const restored = this.tail
+ .catch(() => {})
+ .then(() => {
+ if (this.restorePending) return this.restore();
+ });
+ this.tail = restored;
+ return restored;
+ }
}
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 29a4b369ae..be0b87cf2b 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -520,9 +520,12 @@ video and control available. Locked or unknown compositor state denies audio rea
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`,
+monitor signal for the phone. While the generic remote-session `hostMute` lease is
+active, it follows default-output changes and tracks every exact output object
+(id plus serial), so newly selected outputs are muted too. On release it restores
+each saved `softMute` value; an unplugged output is discarded and cannot cause
+restoration to modify a reused node ID. Transient PipeWire failures use bounded
+backoff retries while the snapshots remain owned by the lease. 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.
@@ -625,7 +628,10 @@ monitor (`r-1` / `r+1`); the menu button uses Omarchy's own `menu toggle`, so a
second press closes it even when the menu was opened locally.
Linux's window picker supplies selection/switching, not macOS Mission Control's
-thumbnail animation. Quickshell auto-unlock remains unavailable under the
+thumbnail animation. Its temporary empty-workspace restore retains the snapshot
+when disconnect happens while locked and retries on unlock. This applies to
+Hyprland window actions independently of the optional Omarchy menu.
+Quickshell auto-unlock remains unavailable under the
existing-system-interface constraint. These differences and the unverified
physical phone scenarios must not be described as complete macOS parity.