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): 校验 macOS 输入调用者并停止撤权后的重连

Dashba1b946104c4
diff --git a/apps/desktop/native/remote-desktop/README.md b/apps/desktop/native/remote-desktop/README.md
new file mode 100644
index 0000000000..223882193c
--- /dev/null
+++ b/apps/desktop/native/remote-desktop/README.md
@@ -0,0 +1,34 @@
+# macOS input helper trust boundary
+
+The input helper authenticates its caller before inspecting any command or
+requesting Accessibility permission. Node's macOS stdio socket pairs carry kernel
+audit tokens; stdin, stdout and stderr must all belong to the direct Main parent
+and the current user. A regular pipe, redirected channel, missing identity or
+failed signature check exits with status 77 without returning clipboard content.
+
+Packaged builds require an Apple-signed, hardened Cindy Main executable in the
+same application bundle and with the helper's signing team. The application must
+seal the exact helper bytes in its signed resources. This prevents transplanting
+the helper into an older signed application with weaker Electron fuses. The
+existing package configuration disables RunAsNode, NODE_OPTIONS and CLI inspector
+arguments and enforces the sealed ASAR. Input batches and the watchdog recheck
+the audit-token-bound process; loss of its identity releases held inputs and exits.
+Existing Main remote-control permissions, leases and system TCC checks still apply.
+
+Source development is a different trust boundary: generic Electron loads writable
+JavaScript and exposes debugging facilities. `inputHost.ts` explicitly compiles a
+development variant bound to that Electron executable's path and designated code
+requirement, retaining kernel channel checks. This does **not** protect against
+arbitrary code already running in that development runtime. Its cache identity is
+stable across Main restarts. Neither CLI arguments nor environment variables can
+enable this variant in a packaged helper; failed production authentication never
+falls back to it. Ad-hoc/unsigned packaged builds fail closed and are not a
+substitute for the development workflow or a properly signed distribution.
+
+The native tests exercise real audit-token and Security APIs without posting
+events, reading selections or prompting for permissions. They cover ordinary
+process calls to every production command, channel redirection, forged runtime
+development flags, stale audit tokens, and signed-resource helper replacement.
+The resource fixture is ad-hoc signed: it verifies resource sealing, **not** the
+production Apple/team acceptance path. A signed application launch and TCC flow
+must still be checked during release validation.
diff --git a/apps/desktop/native/remote-desktop/macos-input.swift b/apps/desktop/native/remote-desktop/macos-input.swift
index 48fe46ab4d..d6643edf8a 100644
--- a/apps/desktop/native/remote-desktop/macos-input.swift
+++ b/apps/desktop/native/remote-desktop/macos-input.swift
@@ -2,6 +2,110 @@ import Foundation
import ApplicationServices
import AppKit
import IOKit.graphics
+import Security
+
+// libuv creates AF_UNIX socket pairs for child stdio on macOS. Authenticate
+// their kernel-supplied audit tokens, not argv, environment, PID alone or a
+// caller-supplied secret. All three channels must belong to the same Main.
+struct DesktopInputCaller {
+ let token: Data
+ let parent: pid_t
+ let requirement: SecRequirement
+
+ static func signingInfo(_ code: SecCode) -> [String: Any]? {
+ var value: SecStaticCode?
+ var information: CFDictionary?
+ guard SecCodeCopyStaticCode(code, [], &value) == errSecSuccess, let value = value,
+ SecCodeCopySigningInformation(value, SecCSFlags(rawValue: kSecCSSigningInformation), &information) == errSecSuccess else { return nil }
+ return information as? [String: Any]
+ }
+
+ static func hasSealedHelper(_ code: SecCode, executable: URL) -> Bool {
+ var value: SecStaticCode?
+ guard SecCodeCopyStaticCode(code, [], &value) == errSecSuccess, let value = value,
+ let bytes = try? Data(contentsOf: executable) else { return false }
+ // Bind the shipped pair: a same-team older app must not gain this helper's
+ // privileges by transplanting it into an app with weaker Electron fuses.
+ return SecCodeValidateFileResource(value,
+ "Resources/tools/remote-desktop/cindy-macos-desktop-input" as CFString,
+ bytes as CFData, []) == errSecSuccess
+ }
+
+ static func peer(_ descriptor: Int32) -> Data? {
+ var token = audit_token_t()
+ var size = socklen_t(MemoryLayout<audit_token_t>.size)
+ guard getsockopt(descriptor, 0 /* SOL_LOCAL */, 6 /* LOCAL_PEERTOKEN */, &token, &size) == 0,
+ size == MemoryLayout<audit_token_t>.size else { return nil }
+ return withUnsafeBytes(of: token) { Data($0) }
+ }
+
+ func code() -> SecCode? {
+ guard getppid() == parent else { return nil }
+ var code: SecCode?
+ let attributes = [kSecGuestAttributeAudit: token] as CFDictionary
+ guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &code) == errSecSuccess,
+ let code = code, SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { return nil }
+ return code
+ }
+
+ static func authenticate() -> DesktopInputCaller? {
+ guard let token = peer(STDIN_FILENO), peer(STDOUT_FILENO) == token,
+ peer(STDERR_FILENO) == token else { return nil }
+ let words = token.withUnsafeBytes { Array($0.bindMemory(to: UInt32.self)) }
+ let parent = getppid()
+ guard parent > 1, words[5] == UInt32(parent), words[1] == geteuid() else { return nil }
+ var requirement: SecRequirement?
+ let executable: URL
+#if DESKTOP_INPUT_DEVELOPMENT
+ // Development runs writable JS in generic Electron with an inspector.
+ // This is only an exact runtime binding, NOT a production security boundary.
+ // Main fills this compile-time value; no environment/CLI downgrade exists.
+ let encodedExecutable = "DESKTOP_INPUT_DEVELOPMENT_EXECUTABLE"
+ guard let data = Data(base64Encoded: encodedExecutable),
+ let value = String(data: data, encoding: .utf8), value.hasPrefix("/") else { return nil }
+ executable = URL(fileURLWithPath: value).resolvingSymlinksInPath()
+ var expected: SecStaticCode?
+ guard SecStaticCodeCreateWithPath(executable as CFURL, [], &expected) == errSecSuccess,
+ let expected = expected,
+ SecCodeCopyDesignatedRequirement(expected, [], &requirement) == errSecSuccess else { return nil }
+#else
+ var own: SecCode?
+ guard SecCodeCopySelf([], &own) == errSecSuccess, let own = own,
+ SecCodeCheckValidity(own, [], nil) == errSecSuccess,
+ let info = signingInfo(own),
+ let team = info[kSecCodeInfoTeamIdentifier as String] as? String,
+ team.range(of: "^[A-Z0-9]+$", options: .regularExpression) != nil,
+ let ownExecutable = info[kSecCodeInfoMainExecutable as String] as? URL else { return nil }
+ // Only the Main executable in this helper's enclosing, signed app may call
+ // it. Another signed application (even from our team) is not Cindy Main.
+ var appURL = ownExecutable.resolvingSymlinksInPath()
+ for _ in 0..<5 { appURL.deleteLastPathComponent() }
+ guard let bundle = Bundle(url: appURL), let identifier = bundle.bundleIdentifier,
+ ["com.xd.cindy", "com.xd.cindycn"].contains(identifier),
+ let mainExecutable = bundle.executableURL else { return nil }
+ executable = mainExecutable.resolvingSymlinksInPath()
+ let rule = "anchor apple generic and identifier \"\(identifier)\" and certificate leaf[subject.OU] = \"\(team)\""
+ guard SecRequirementCreateWithString(rule as CFString, [], &requirement) == errSecSuccess else { return nil }
+#endif
+ guard let requirement = requirement else { return nil }
+ let caller = DesktopInputCaller(token: token, parent: parent, requirement: requirement)
+ guard let code = caller.code(), let info = signingInfo(code),
+ let actual = info[kSecCodeInfoMainExecutable as String] as? URL,
+ actual.resolvingSymlinksInPath() == executable else { return nil }
+#if !DESKTOP_INPUT_DEVELOPMENT
+ guard let flags = info[kSecCodeInfoFlags as String] as? UInt32,
+ flags & 0x10000 /* kSecCodeSignatureRuntime */ != 0,
+ flags & 0x0002 /* kSecCodeSignatureAdhoc */ == 0,
+ hasSealedHelper(code, executable: ownExecutable) else { return nil }
+#endif
+ return caller
+ }
+}
+
+#if !DESKTOP_INPUT_TEST
+// This guard precedes every entrypoint, including selection and permission UI.
+guard let inputCaller = DesktopInputCaller.authenticate() else { exit(77) }
+#endif
// Expose only the clipboard change counter, never clipboard content on stdout.
if CommandLine.arguments.count == 2 && ["--clipboard-version", "--clipboard-content-version"].contains(CommandLine.arguments[1]) {
@@ -193,6 +297,7 @@ let watchdog = DispatchSource.makeTimerSource(queue: .global())
watchdog.schedule(deadline: .now() + 1, repeating: 1)
watchdog.setEventHandler {
lock.lock(); defer { lock.unlock() }
+ if inputCaller.code() == nil { releaseAll(); exit(77) }
if !AXIsProcessTrusted() { releaseAll(); print("error"); fflush(stdout); exit(2) }
if Date().timeIntervalSince(lastSeen) > 5 { releaseAll() }
}
@@ -202,6 +307,7 @@ let termination = DispatchSource.makeSignalSource(signal: SIGTERM, queue: .globa
termination.setEventHandler { lock.lock(); releaseAll(); lock.unlock(); exit(0) }
termination.resume()
while let line = readLine() {
+ guard inputCaller.code() != nil else { lock.lock(); releaseAll(); lock.unlock(); exit(77) }
guard line.utf8.count <= 65536, let data = line.data(using: .utf8), let events = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { continue }
lock.lock(); lastSeen = Date()
for event in events { apply(event) }
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts
index 2ae4a1850d..5d207eff78 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/macosInput.test.ts
@@ -1,5 +1,5 @@
-import { execFile } from 'node:child_process';
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { execFile, spawn, spawnSync } from 'node:child_process';
+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
@@ -27,3 +27,132 @@ it.skipIf(process.platform !== 'darwin')(
},
130_000,
);
+
+it.skipIf(process.platform !== 'darwin')(
+ 'authenticates kernel stdio peers before any privileged entrypoint',
+ async () => {
+ const directory = await mkdtemp(path.join(tmpdir(), 'cindy-input-caller-'));
+ try {
+ const native = path.resolve(import.meta.dirname, '../../../../native/remote-desktop');
+ const source = await readFile(path.join(native, 'macos-input.swift'), 'utf8');
+ const binary = path.join(directory, 'input');
+ await exec('swiftc', [path.join(native, 'macos-input.swift'), '-o', binary], {
+ timeout: 120_000,
+ });
+ for (const args of [
+ [],
+ ['--check'],
+ ['--request-permission'],
+ ['--clipboard-version'],
+ ['--clipboard-content-version'],
+ ['--clipboard-selection'],
+ ['--clipboard-content-selection'],
+ ['--display-modes', '1'],
+ ['--display-mode', '1', '1'],
+ ['--dev', '--check'],
+ ]) {
+ const result = spawnSync(binary, args, {
+ encoding: 'utf8',
+ timeout: 5000,
+ env: { ...process.env, DESKTOP_INPUT_DEVELOPMENT: '1' },
+ });
+ expect(result.status, args.join(' ')).toBe(77);
+ expect(result.stdout).toBe('');
+ expect(result.stderr).toBe('');
+ }
+
+ // Exercise the real audit-token/SecCode APIs with a harmless probe. It
+ // contains only authentication, never AX reads, input or permission UI.
+ const prefix = source
+ .slice(0, source.indexOf('#if !DESKTOP_INPUT_TEST'))
+ .replace(
+ '"DESKTOP_INPUT_DEVELOPMENT_EXECUTABLE"',
+ JSON.stringify(Buffer.from(process.execPath).toString('base64')),
+ );
+ const main = path.join(directory, 'main.swift');
+ const probe = path.join(directory, 'probe');
+ await writeFile(
+ main,
+ `${prefix}
+if CommandLine.arguments.count == 2 {
+ var own: SecCode?
+ guard SecCodeCopySelf([], &own) == errSecSuccess, let own = own,
+ DesktopInputCaller.hasSealedHelper(own, executable: URL(fileURLWithPath: CommandLine.arguments[1])) else { exit(79) }
+ print("sealed"); exit(0)
+}
+guard let caller = DesktopInputCaller.authenticate(), caller.code() != nil else { exit(77) }
+var staleToken = caller.token
+staleToken.withUnsafeMutableBytes { $0.bindMemory(to: UInt32.self)[7] &+= 1 }
+guard DesktopInputCaller(token: staleToken, parent: caller.parent, requirement: caller.requirement).code() == nil else { exit(78) }
+print("authenticated")
+`,
+ );
+ await exec('swiftc', ['-D', 'DESKTOP_INPUT_DEVELOPMENT', main, '-o', probe], {
+ timeout: 120_000,
+ });
+ expect((await exec(probe, [], { timeout: 5000 })).stdout.trim()).toBe('authenticated');
+ for (const stream of [0, 1, 2]) {
+ const stdio: ('pipe' | 'ignore')[] = ['pipe', 'pipe', 'pipe'];
+ stdio[stream] = 'ignore';
+ // Keep the other socket peers open, as Main does; a closed stdin would
+ // otherwise mask failures specific to stdout/stderr authentication.
+ const status = await new Promise<number | null>((resolve, reject) => {
+ const child = spawn(probe, [], { stdio, timeout: 5000 });
+ child.stdout?.resume();
+ child.stderr?.resume();
+ child.once('error', reject);
+ child.once('close', resolve);
+ });
+ expect(status).toBe(77);
+ }
+ const pipe = await exec('/bin/sh', ['-c', 'printf "" | "$1"', 'sh', probe], {
+ timeout: 5000,
+ }).catch((error: { code: number }) => error);
+ expect(pipe).toMatchObject({ code: 77 });
+
+ // Ad-hoc fixture exercises resource sealing only; it is deliberately
+ // insufficient to pass production's Apple/team identity requirement.
+ const bundle = path.join(directory, 'Fixture.app');
+ const contents = path.join(bundle, 'Contents');
+ const tools = path.join(contents, 'Resources/tools/remote-desktop');
+ const executable = path.join(contents, 'MacOS/Fixture');
+ const helper = path.join(tools, 'cindy-macos-desktop-input');
+ await mkdir(tools, { recursive: true });
+ await mkdir(path.dirname(executable), { recursive: true });
+ await copyFile(probe, executable);
+ await copyFile(binary, helper);
+ await writeFile(
+ path.join(contents, 'Info.plist'),
+ `<?xml version="1.0" encoding="UTF-8"?>
+<plist version="1.0"><dict><key>CFBundleIdentifier</key><string>invalid.cindy.input-auth-fixture</string>
+<key>CFBundleExecutable</key><string>Fixture</string><key>CFBundlePackageType</key><string>APPL</string></dict></plist>`,
+ );
+ await exec('/usr/bin/codesign', ['--force', '--sign', '-', bundle], { timeout: 10_000 });
+ expect((await exec(executable, [helper], { timeout: 5000 })).stdout.trim()).toBe('sealed');
+ await copyFile(probe, helper);
+ expect(spawnSync(executable, [helper], { timeout: 5000 }).status).toBe(79);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ },
+ 260_000,
+);
+
+it('keeps production authentication and hardened Electron fuses in packaged builds', async () => {
+ const forge = await readFile(
+ path.resolve(import.meta.dirname, '../../../../forge.config.ts'),
+ 'utf8',
+ );
+ expect(forge).not.toContain('DESKTOP_INPUT_DEVELOPMENT');
+ expect(forge).not.toContain('DESKTOP_INPUT_TEST');
+ for (const flag of [
+ 'RunAsNode',
+ 'EnableNodeOptionsEnvironmentVariable',
+ 'EnableNodeCliInspectArguments',
+ ]) {
+ expect(forge).toContain(`[FuseV1Options.${flag}]: false`);
+ }
+ for (const flag of ['EnableEmbeddedAsarIntegrityValidation', 'OnlyLoadAppFromAsar']) {
+ expect(forge).toContain(`[FuseV1Options.${flag}]: true`);
+ }
+});
diff --git a/apps/desktop/src/main/remote-desktop/inputHost.ts b/apps/desktop/src/main/remote-desktop/inputHost.ts
index b8d366ee5e..649249c50b 100644
--- a/apps/desktop/src/main/remote-desktop/inputHost.ts
+++ b/apps/desktop/src/main/remote-desktop/inputHost.ts
@@ -34,6 +34,7 @@ async function resolveBinary(prepare = true): Promise<string> {
.update(await fs.readFile(source))
.update(process.arch)
.update('v1-O');
+ if (process.platform === 'darwin') digest.update(process.execPath).update('dev-caller-v1');
if (process.platform === 'win32') {
digest.update(await fs.readFile(path.join(sourceRoot, 'windows-input', 'src', 'desktop.rs')));
digest.update(
@@ -55,7 +56,22 @@ async function resolveBinary(prepare = true): Promise<string> {
await fs.mkdir(directory, { recursive: true });
const temporary = `${binary}.${process.pid}.tmp`;
if (process.platform === 'darwin') {
- await exec('swiftc', [source, '-O', '-o', temporary], { timeout: 120_000 });
+ // Only source-mode Electron uses this build. Packaged helpers always use
+ // Apple's signing identity check; no runtime flag can downgrade it.
+ const buildDirectory = await fs.mkdtemp(path.join(directory, 'compile-'));
+ try {
+ const main = path.join(buildDirectory, 'main.swift');
+ const program = (await fs.readFile(source, 'utf8')).replace(
+ '"DESKTOP_INPUT_DEVELOPMENT_EXECUTABLE"',
+ JSON.stringify(Buffer.from(process.execPath).toString('base64')),
+ );
+ await fs.writeFile(main, program);
+ await exec('swiftc', ['-D', 'DESKTOP_INPUT_DEVELOPMENT', main, '-O', '-o', temporary], {
+ timeout: 120_000,
+ });
+ } finally {
+ await fs.rm(buildDirectory, { recursive: true, force: true });
+ }
} else {
const manifest = path.join(sourceRoot, 'windows-input', 'Cargo.toml');
await exec(
@@ -345,16 +361,31 @@ export async function readDesktopClipboardVersion(portable = false): Promise<str
if (process.platform !== 'darwin' && process.platform !== 'win32')
throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
try {
- const { stdout } = await exec(await resolveBinary(), [portable && process.platform === 'darwin' ? '--clipboard-content-version' : '--clipboard-version'], {
- timeout: 2000,
- maxBuffer: 128,
- windowsHide: true,
- });
+ const { stdout } = await exec(
+ await resolveBinary(),
+ [
+ portable && process.platform === 'darwin'
+ ? '--clipboard-content-version'
+ : '--clipboard-version',
+ ],
+ {
+ timeout: 2000,
+ maxBuffer: 128,
+ windowsHide: true,
+ },
+ );
const version = stdout.trim();
if (!/^[0-9]+$/.test(version)) throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
return version;
} catch (error) {
- if (portable && process.platform === 'darwin' && error && typeof error === 'object' && 'code' in error && error.code === 3)
+ if (
+ portable &&
+ process.platform === 'darwin' &&
+ error &&
+ typeof error === 'object' &&
+ 'code' in error &&
+ error.code === 3
+ )
throw new Error('CLIPBOARD_UNSUPPORTED');
throw new Error('DESKTOP_CLIPBOARD_UNAVAILABLE');
}
@@ -362,11 +393,15 @@ export async function readDesktopClipboardVersion(portable = false): Promise<str
export async function readDesktopSelection(portable = false): Promise<string> {
try {
- const { stdout } = await exec(await resolveBinary(), [portable ? '--clipboard-content-selection' : '--clipboard-selection'], {
- timeout: 3000,
- maxBuffer: 128_000,
- windowsHide: true,
- });
+ const { stdout } = await exec(
+ await resolveBinary(),
+ [portable ? '--clipboard-content-selection' : '--clipboard-selection'],
+ {
+ timeout: 3000,
+ maxBuffer: 128_000,
+ windowsHide: true,
+ },
+ );
const value: unknown = JSON.parse(stdout);
if (
!value ||
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 5329c6e6e2..ff651d4c93 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -370,25 +370,29 @@ export default function RemoteDesktopScreen() {
typeof cause.code === "string"
? cause.code
: message.match(
- /\b(?:DESKTOP|CHANNEL|DEVICE|INVOKE|REMOTE)_[A-Z_]+\b/,
+ /\b(?:DESKTOP|CHANNEL|DEVICE|INVOKE|REMOTE|ACCESS)_[A-Z_]+\b/,
)?.[0];
// Keep diagnostics free of device names, input and signaling payloads.
console.debug("[remote-desktop] connection failed", {
code: code && /^[A-Z_]+$/.test(code) ? code : "UNKNOWN",
});
const blocked =
- code === "DESKTOP_BUSY"
- ? "connectionBusy"
- : code === "CHANNEL_NOT_ALLOWED"
- ? "upgrade"
- : message.includes("DESKTOP_DISABLED")
- ? "disabled"
- : message.includes("PERMISSION") ||
- message.includes("ACCESSIBILITY")
- ? "permissionHint"
- : message.includes("DESKTOP_STOPPED")
- ? "disconnected"
- : null;
+ code === "ACCESS_REVOKED"
+ ? "accessRevoked"
+ : code === "REMOTE_DISABLED"
+ ? "remoteDisabled"
+ : code === "DESKTOP_BUSY"
+ ? "connectionBusy"
+ : code === "CHANNEL_NOT_ALLOWED"
+ ? "upgrade"
+ : message.includes("DESKTOP_DISABLED")
+ ? "disabled"
+ : message.includes("PERMISSION") ||
+ message.includes("ACCESSIBILITY")
+ ? "permissionHint"
+ : message.includes("DESKTOP_STOPPED")
+ ? "disconnected"
+ : null;
stop(!blocked);
setError(blocked);
if (blocked) recovery.current.enabled = false;
@@ -1288,7 +1292,9 @@ export default function RemoteDesktopScreen() {
accessibilityRole={error ? "alert" : undefined}
style={styles.caption}
>
- {t(`remoteDesktop.${error === "connectionBusy" && caps?.connectionTakeover ? "connectionBusyTakeover" : error ?? status}`)}
+ {t(error === "accessRevoked" || error === "remoteDisabled"
+ ? `deviceLink.remoteError.${error}`
+ : `remoteDesktop.${error === "connectionBusy" && caps?.connectionTakeover ? "connectionBusyTakeover" : error ?? status}`)}
</Text>
)}
{error &&
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index d0df469a6d..fea44c3293 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -568,6 +568,36 @@ describe("remote desktop controls", () => {
expect(fixture.invoke).toHaveBeenCalledTimes(1);
expect(requests().some((r) => r.op === "start")).toBe(false);
});
+ it.each([
+ ["ACCESS_REVOKED", "accessRevoked"],
+ ["REMOTE_DISABLED", "remoteDisabled"],
+ ])("stops automatic recovery for %s while retaining manual retry", async (code, hint) => {
+ const original = fixture.invoke.getMockImplementation()!;
+ for (const structured of [false, true]) {
+ for (const stage of ["openLink", "invoke"] as const) {
+ const failure = structured
+ ? Object.assign(new Error("Rejected by host"), { code })
+ : new Error(`Remote invoke failed: ${code}`);
+ fixture.openLink.mockResolvedValue({});
+ fixture.invoke.mockImplementation(original);
+ if (stage === "openLink") fixture.openLink.mockRejectedValue(failure);
+ else fixture.invoke.mockRejectedValue(failure);
+ await connect();
+ act(() => button("connect").click());
+ await act(async () => {});
+ expect(host.textContent).toContain(`deviceLink.remoteError.${hint}`);
+ const calls = fixture.openLink.mock.calls.length;
+ await act(async () => vi.advanceTimersByTimeAsync(30_000));
+ expect(fixture.openLink).toHaveBeenCalledTimes(calls);
+ fixture.openLink.mockResolvedValue({});
+ fixture.invoke.mockImplementation(original);
+ act(() => button("connect").click());
+ await act(async () => {});
+ expect(fixture.openLink.mock.calls.length).toBeGreaterThan(calls);
+ expect(host.textContent).not.toContain(`deviceLink.remoteError.${hint}`);
+ }
+ }
+ });
it("marks retries as recovery even when the first start reply was lost", async () => {
const original = fixture.invoke.getMockImplementation()!;
fixture.invoke.mockImplementation((...args) =>