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): 输入失败只收回控制,不再拆掉整个会话 (#4284)

Liziaeb2ef42a86e
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
index e63bb147f1..11cf442ce1 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureBoundary.test.ts
@@ -16,6 +16,9 @@ const h = vi.hoisted(() => ({
nativeFrame: vi.fn(async () => 'frame'),
input: vi.fn(),
viewHeartbeat: vi.fn(),
+ inputFailure: null as null | (() => void),
+ releaseControl: vi.fn(),
+ hostInput: vi.fn(),
iceConfig: vi.fn(async (): Promise<any[]> => [
{ urls: ['turn:relay.example.test:3478'], username: 'temporary', credential: 'test-only' },
]),
@@ -93,6 +96,9 @@ vi.mock('../controller', () => ({
stopByUser() {
this.stop();
}
+ releaseControl() {
+ h.releaseControl();
+ }
tick() {}
input = h.input;
viewHeartbeat = h.viewHeartbeat;
@@ -106,8 +112,11 @@ vi.mock('../nativeCapture', () => ({
}));
vi.mock('../inputHost', () => ({
DesktopInputHost: class {
+ constructor(onFailure: () => void) {
+ h.inputFailure = onFailure;
+ }
stop = vi.fn();
- input = vi.fn();
+ input = h.hostInput;
},
readDesktopDisplayModes: vi.fn(),
setDesktopDisplayMode: vi.fn(),
@@ -162,6 +171,9 @@ beforeEach(() => {
h.nativeFrame.mockClear();
h.input.mockReset();
h.viewHeartbeat.mockClear();
+ // The host is constructed once at module load; keep its captured callback.
+ h.releaseControl.mockClear();
+ h.hostInput.mockReset();
h.iceConfig.mockClear();
registerRemoteDesktopIpc();
});
@@ -294,6 +306,32 @@ it('drops view-only input without breaking heartbeats, but still rejects invalid
}
});
+it('turns an input-helper failure into a control release instead of a session stop', async () => {
+ const pending = offer();
+ h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
+ await flush();
+ h.handlers.get(DESKTOP_LOCAL.REPLY)(event(), h.owner.send.mock.calls[0][1].id, 'answer');
+ await pending;
+ expect(h.inputFailure).toBeTypeOf('function');
+ h.inputFailure?.();
+ // Input is a lease-scoped capability: the desktop session keeps its lease,
+ // its capture owner and its media when the helper dies.
+ expect(h.releaseControl).toHaveBeenCalledTimes(1);
+ expect(h.stop).not.toHaveBeenCalled();
+ expect(h.owner.dead).toBe(false);
+});
+
+it('releases control when the input host refuses a batch before injecting it', () => {
+ h.hostInput.mockImplementationOnce(() => {
+ throw new Error('DESKTOP_INPUT_UNAVAILABLE');
+ });
+ // The refusal still reaches its caller, but control no longer stays set: a
+ // later take-control must actually restart the helper.
+ expect(() => h.deps.input([{ kind: 'release' }])).toThrow('DESKTOP_INPUT_UNAVAILABLE');
+ expect(h.releaseControl).toHaveBeenCalledTimes(1);
+ expect(h.stop).not.toHaveBeenCalled();
+});
+
it('retains the capture owner on ICE timeout and rejects old-owner replies after replacement', async () => {
const pending = offer();
h.handlers.get(DESKTOP_LOCAL.REGISTER)(event());
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
index 24ce5aba52..c610adbe3d 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/controller.test.ts
@@ -537,6 +537,62 @@ describe('remote desktop authority and lifecycle', () => {
expect(h.deps.stopVideo).not.toHaveBeenCalled();
}
});
+ it('releases control after an input failure without ending the lease or its media', async () => {
+ const h = harness();
+ const lease = await h.start();
+ await h.controller.request('phone', { op: 'control', lease: lease.lease, enabled: true });
+ h.controller.input(lease.lease, 1, [{ kind: 'release' }]);
+ expect(h.deps.input).toHaveBeenCalledTimes(1);
+ // The helper died: control goes, the picture and the lease stay.
+ h.controller.releaseControl();
+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: false });
+ expect(h.controller.hasLease(lease.lease)).toBe(true);
+ expect(h.deps.stopInput).toHaveBeenCalledTimes(1);
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ expect(h.deps.changed).toHaveBeenCalled();
+ // The viewer learns the truth from its own heartbeat.
+ await expect(
+ h.controller.request('phone', { op: 'heartbeat', lease: lease.lease }),
+ ).resolves.toEqual({ controlling: false });
+ // Later input is an input problem, not a lease problem.
+ await expect(
+ h.controller.request('phone', {
+ op: 'input',
+ lease: lease.lease,
+ sequence: 2,
+ events: [{ kind: 'release' }],
+ }),
+ ).rejects.toThrow('VIEW_ONLY');
+ expect(h.deps.input).toHaveBeenCalledTimes(1);
+ await expect(h.controller.request('phone', { op: 'frame', lease: lease.lease })).resolves.toEqual(
+ { jpeg: 'jpeg' },
+ );
+ });
+ it('lets the same viewer take control again after a release without touching the media', async () => {
+ const h = harness();
+ const lease = await h.start();
+ await h.controller.request('phone', { op: 'control', lease: lease.lease, enabled: true });
+ h.controller.releaseControl();
+ await h.controller.request('phone', { op: 'control', lease: lease.lease, enabled: true });
+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: true });
+ // Taking control again restarts the input helper on the same lease.
+ expect(h.deps.startInput).toHaveBeenCalledTimes(2);
+ // A second viewer is still arbitrated by the same single-viewer rules.
+ await expect(h.controller.request('other', { op: 'start', displayId: '1' })).rejects.toThrow(
+ 'BUSY',
+ );
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ expect(h.deps.stopInput).toHaveBeenCalledTimes(1);
+ });
+ it('ignores a release when no viewer controls anything', async () => {
+ const h = harness();
+ const lease = await h.start();
+ h.controller.releaseControl();
+ expect(h.controller.state).toEqual({ peer: 'phone', controlling: false });
+ expect(h.deps.stopInput).not.toHaveBeenCalled();
+ expect(h.deps.stopVideo).not.toHaveBeenCalled();
+ expect(h.controller.hasLease(lease.lease)).toBe(true);
+ });
});
describe('human / Agent input ownership', () => {
it('excludes simultaneous input in both directions and releases on error', async () => {
diff --git a/apps/desktop/src/main/remote-desktop/controller.ts b/apps/desktop/src/main/remote-desktop/controller.ts
index e53e55dee9..48579c6a9a 100644
--- a/apps/desktop/src/main/remote-desktop/controller.ts
+++ b/apps/desktop/src/main/remote-desktop/controller.ts
@@ -133,6 +133,22 @@ export class RemoteDesktopController {
this.deps.stopVideo();
this.deps.changed();
}
+ /**
+ * Input injection failed while the lease is still valid. Input belongs to the
+ * control bit, so release control and keep everything else: ending the lease
+ * here would tear down capture and media, and every phone tap would surface as
+ * a reconnect even though the desktop session itself is healthy. The viewer
+ * observes the new state on its next heartbeat or input attempt.
+ */
+ releaseControl(): void {
+ const active = this.active;
+ if (!active?.controlling) return;
+ active.controlling = false;
+ this.controlGeneration++;
+ this.clipboardTransfer.reset();
+ this.deps.stopInput();
+ this.deps.changed();
+ }
/** Explicit local disconnect must not be undone by the phone's recovery. */
stopByUser(): void {
const target = this.active ?? this.lastEnded;
diff --git a/apps/desktop/src/main/remote-desktop/index.ts b/apps/desktop/src/main/remote-desktop/index.ts
index d85e34a292..89624a869a 100644
--- a/apps/desktop/src/main/remote-desktop/index.ts
+++ b/apps/desktop/src/main/remote-desktop/index.ts
@@ -121,7 +121,9 @@ let pending: {
reject(error: Error): void;
timer: ReturnType<typeof setTimeout>;
} | null = null;
-const input = new DesktopInputHost(() => remoteDesktop.stop());
+// A dead input helper or a refused injection is an input failure, not a session
+// failure: release control and keep the lease, capture and media running.
+const input = new DesktopInputHost(() => remoteDesktop.releaseControl());
function stopVideo(): void {
offerGeneration++;
videoAttempt = undefined;
@@ -368,7 +370,18 @@ export const remoteDesktop = new RemoteDesktopController({
displayModes: readDesktopDisplayModes,
resolution: setDesktopDisplayMode,
startInput: (displayId) => input.start(displayId),
- input: (events) => input.input(events),
+ input: (events) => {
+ try {
+ input.input(events);
+ } catch (error) {
+ // The input host refused before injecting anything (helper gone, or this
+ // lease's display is unavailable). Release control so the host and the
+ // viewer agree, and so taking control again genuinely restarts the
+ // helper instead of being skipped as "already controlling".
+ remoteDesktop.releaseControl();
+ throw error;
+ }
+ },
stopInput: () => input.stop(),
...(process.platform === 'darwin' ? {
lockScreen: async (isCurrent: () => boolean, signal: AbortSignal) => {
diff --git a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
index 600803231e..1c9d267079 100644
--- a/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
+++ b/apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx
@@ -30,6 +30,7 @@ import {
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { WebView, type WebViewMessageEvent } from "react-native-webview";
import { connectionDiagnostics } from "./connectionDiagnostics";
+import { controlFailureAction, remoteDesktopErrorCode } from "./controlFailure";
import { transferClipboardContent } from "./clipboardTransfer";
import * as Clipboard from "expo-clipboard";
import { RemoteDesktopClipboardButton } from "./RemoteDesktopClipboardButton";
@@ -205,6 +206,11 @@ export default function RemoteDesktopScreen() {
).current;
const active = useRef<RemoteDesktopLease | null>(null);
const wantsControl = useRef(true);
+ // Last control bit we asked the host for but have not confirmed. Overflow and
+ // take-control can time out after the local bit already moved; heartbeats use
+ // this to retry a release or restore local control instead of ignoring host-true.
+ const pendingHostControl = useRef<boolean | null>(null);
+ const controlInFlight = useRef(false);
const recovery = useRef({
enabled: true,
at: 0,
@@ -405,6 +411,8 @@ export default function RemoteDesktopScreen() {
presentationTimer.current = null;
void remotePresentation?.playback(false).catch(() => {});
connecting.current = false;
+ pendingHostControl.current = null;
+ controlInFlight.current = false;
const previous = active.current;
setExitLockPending(Boolean(previous && exiting && exitLock.current));
active.current = null;
@@ -463,18 +471,10 @@ export default function RemoteDesktopScreen() {
(cause: unknown) => {
if (!alive.current) return;
const message = cause instanceof Error ? cause.message : String(cause);
- const code =
- cause &&
- typeof cause === "object" &&
- "code" in cause &&
- typeof cause.code === "string"
- ? cause.code
- : message.match(
- /\b(?:DESKTOP|CHANNEL|DEVICE|INVOKE|REMOTE|ACCESS)_[A-Z_]+\b/,
- )?.[0];
+ const code = remoteDesktopErrorCode(cause);
// Keep diagnostics free of device names, input and signaling payloads.
console.debug("[remote-desktop] connection failed", {
- code: code && /^[A-Z_]+$/.test(code) ? code : "UNKNOWN",
+ code: code ?? "UNKNOWN",
});
const blocked =
code === "ACCESS_REVOKED"
@@ -504,6 +504,87 @@ export default function RemoteDesktopScreen() {
},
[stop],
);
+ /**
+ * The host owns the control bit. When it reports that this viewer no longer
+ * controls — input injection failed, the input helper went away, or control
+ * was retracted — drop to view only instead of rebuilding the session: the
+ * lease, the picture and the existing view-only hint all survive, and taking
+ * control again retries from where the user is.
+ */
+ const releaseControl = useCallback(() => {
+ const current = active.current;
+ if (!current?.controlling) return;
+ current.controlling = false;
+ heldKeys.current.clear();
+ send({ type: "control", enabled: false });
+ if (alive.current) {
+ setModifiers([]);
+ setKeyboard(false);
+ setLease({ ...current });
+ }
+ }, [send]);
+ /**
+ * Route a failed input or control request by its blast radius: a control-only
+ * fault drops to view only, an unknown outcome keeps everything as it is, and
+ * anything else rebuilds the session. Sitting next to the two actions it
+ * chooses between keeps the three call sites from drifting apart.
+ */
+ const resolveControlFailure = (cause: unknown) => {
+ switch (controlFailureAction(cause)) {
+ case "release":
+ releaseControl();
+ break;
+ case "ignore":
+ break;
+ default:
+ fail(cause);
+ }
+ };
+ const applyConfirmedControl = (
+ current: RemoteDesktopLease,
+ controlling: boolean,
+ ) => {
+ pendingHostControl.current = null;
+ wantsControl.current = controlling;
+ if (current.controlling !== controlling) {
+ current.controlling = controlling;
+ if (!controlling) {
+ heldKeys.current.clear();
+ if (alive.current) {
+ setModifiers([]);
+ setKeyboard(false);
+ }
+ }
+ if (alive.current) setLease({ ...current });
+ }
+ send({ type: "control", enabled: controlling });
+ };
+ const requestHostControl = (
+ current: RemoteDesktopLease,
+ enabled: boolean,
+ ) => {
+ if (controlInFlight.current) return;
+ controlInFlight.current = true;
+ pendingHostControl.current = enabled;
+ void request<{ controlling: boolean }>({
+ op: "control",
+ lease: current.lease,
+ enabled,
+ })
+ .then((result) => {
+ if (active.current !== current) return;
+ applyConfirmedControl(current, result.controlling);
+ })
+ .catch((cause) => {
+ if (active.current !== current) return;
+ resolveControlFailure(cause);
+ })
+ .finally(() => {
+ if (active.current === current) controlInFlight.current = false;
+ });
+ };
+ const requestHostControlRef = useRef(requestHostControl);
+ requestHostControlRef.current = requestHostControl;
const connect = useCallback(
async (displayId?: string, takeover = false) => {
if (
@@ -757,7 +838,31 @@ export default function RemoteDesktopScreen() {
)
return;
heartbeatBusy = current.lease;
- void request({ op: "heartbeat", lease: current.lease })
+ void request<{ controlling: boolean }>({
+ op: "heartbeat",
+ lease: current.lease,
+ })
+ .then((result) => {
+ // The host owns the control bit. Follow it when it retracts control;
+ // when a local transition timed out, retry a release or restore the
+ // local bit so a held key cannot stay down behind a view-only phone.
+ if (active.current !== current || presentation.current) return;
+ if (result.controlling === false) {
+ // startInput can still be settling while this heartbeat was in
+ // flight. Clearing a pending take-control here would leave later
+ // host-true beats with nothing to restore after a lost reply.
+ if (pendingHostControl.current === true) return;
+ pendingHostControl.current = null;
+ if (current.controlling) releaseControl();
+ return;
+ }
+ if (pendingHostControl.current === false) {
+ requestHostControlRef.current(current, false);
+ return;
+ }
+ if (!current.controlling && pendingHostControl.current === true)
+ applyConfirmedControl(current, true);
+ })
.catch((cause) => {
// A missing reply does not prove renewal failed; the next interval
// retries within the lease. Explicit host revocation still stops us.
@@ -857,7 +962,7 @@ export default function RemoteDesktopScreen() {
clearInterval(metrics);
stop();
};
- }, [request, fail, send, stop, pause]);
+ }, [request, fail, send, stop, pause, releaseControl]);
useEffect(() => {
// Route blur means leaving this desktop (including a native back swipe).
// App background/inactive events use pause() without the exit flag.
@@ -1190,9 +1295,15 @@ export default function RemoteDesktopScreen() {
});
break;
}
- case "inputOverflow":
- fail(new Error("DESKTOP_INPUT_UNAVAILABLE"));
+ case "inputOverflow": {
+ // The viewer replaced a stalled queue with a release, then this handler
+ // posts control:false, which clears that release without flushing it.
+ // Tell the host to drop control (stopInput still injects a native
+ // release) so a held key/button cannot stay down while we view only.
+ releaseControl();
+ requestHostControl(current, false);
break;
+ }
case "input": {
const ack = {
type: "ack",
@@ -1218,7 +1329,8 @@ export default function RemoteDesktopScreen() {
events: message.events,
})
.catch((cause) => {
- if (active.current === current) fail(cause);
+ if (active.current !== current) return;
+ resolveControlFailure(cause);
})
.finally(() => {
if (inputBusy.current === current.lease) inputBusy.current = null;
@@ -1230,33 +1342,44 @@ export default function RemoteDesktopScreen() {
};
const toggleControl = async () => {
const current = active.current;
- if (!current || busy) return;
+ if (!current || busy || controlInFlight.current) return;
setBusy(true);
setError(null);
+ controlInFlight.current = true;
try {
if (presentation.current) {
presentation.current = false;
send({ type: "presentation", enabled: false });
}
send({ type: "control", enabled: false });
+ const enabled = !current.controlling;
+ if (pendingHostControl.current === false && enabled) {
+ // Overflow timed out with an unconfirmed host release. Taking control
+ // first would skip stopInput while a key/button may still be held.
+ const released = await request<{ controlling: boolean }>({
+ op: "control",
+ lease: current.lease,
+ enabled: false,
+ });
+ if (active.current !== current) return;
+ applyConfirmedControl(current, released.controlling);
+ if (released.controlling) return;
+ }
+ pendingHostControl.current = enabled;
const result = await request<{ controlling: boolean }>({
op: "control",
lease: current.lease,
- enabled: !current.controlling,
+ enabled,
});
if (active.current !== current) return;
- wantsControl.current = result.controlling;
- current.controlling = result.controlling;
- setLease({ ...current });
- send({ type: "control", enabled: result.controlling });
- if (!result.controlling) {
- heldKeys.current.clear();
- setModifiers([]);
- setKeyboard(false);
- }
+ applyConfirmedControl(current, result.controlling);
} catch (cause) {
- if (active.current === current) fail(cause);
+ // Taking control can fail because this computer cannot inject input right
+ // now. Stay in view only and let the user retry; a session rebuild would
+ // cost the picture and the lease for a control-only fault.
+ if (active.current === current) resolveControlFailure(cause);
} finally {
+ controlInFlight.current = false;
if (alive.current) setBusy(false);
}
};
diff --git a/apps/mobile/src/remote-desktop/__tests__/controlFailure.test.ts b/apps/mobile/src/remote-desktop/__tests__/controlFailure.test.ts
new file mode 100644
index 0000000000..cdbdb1094c
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/__tests__/controlFailure.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import {
+ controlFailureAction,
+ remoteDesktopErrorCode,
+} from "../controlFailure";
+
+describe("remote desktop control failure classification", () => {
+ it("reads the code from the error field before falling back to the message", () => {
+ expect(
+ remoteDesktopErrorCode(
+ Object.assign(new Error("boom"), { code: "DESKTOP_VIEW_ONLY" }),
+ ),
+ ).toBe("DESKTOP_VIEW_ONLY");
+ expect(
+ remoteDesktopErrorCode(new Error("[DESKTOP_LEASE_EXPIRED] gone")),
+ ).toBe("DESKTOP_LEASE_EXPIRED");
+ expect(remoteDesktopErrorCode(new Error("network down"))).toBeUndefined();
+ expect(remoteDesktopErrorCode(undefined)).toBeUndefined();
+ });
+ it.each(["DESKTOP_VIEW_ONLY", "DESKTOP_INPUT_UNAVAILABLE"])(
+ "releases control for %s without rebuilding the session",
+ (code) => {
+ expect(controlFailureAction(new Error(code))).toBe("release");
+ },
+ );
+ it.each(["INVOKE_TIMEOUT", "DESKTOP_INPUT_BUSY"])(
+ "keeps the current state for the unknown outcome %s",
+ (code) => {
+ // A lost reply does not prove the host released control, and a batch that
+ // was injected must not be answered with a release that drops its key-up.
+ expect(controlFailureAction(new Error(code))).toBe("ignore");
+ },
+ );
+ it.each([
+ "DESKTOP_LEASE_EXPIRED",
+ "DESKTOP_STOPPED",
+ "DESKTOP_DISABLED",
+ "ACCESS_REVOKED",
+ "CHANNEL_NOT_ALLOWED",
+ "DESKTOP_VIDEO_UNAVAILABLE",
+ ])("still rebuilds the session for %s", (code) => {
+ expect(controlFailureAction(new Error(code))).toBe("rebuild");
+ });
+ it("rebuilds when there is no usable code at all", () => {
+ expect(controlFailureAction(new Error("network down"))).toBe("rebuild");
+ expect(controlFailureAction(undefined)).toBe("rebuild");
+ });
+});
diff --git a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
index a282b88a21..f602be6bef 100644
--- a/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
+++ b/apps/mobile/src/remote-desktop/__tests__/screen.test.tsx
@@ -1634,6 +1634,238 @@ describe("remote desktop controls", () => {
expect(sent().at(-1)).toEqual({ type: "mode", mode: "touch" });
expect(requests().filter((r) => r.op === "start")).toHaveLength(1);
});
+ it("keeps the session and the picture when the host refuses an input batch", async () => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "input"
+ ? Promise.reject(new Error("DESKTOP_VIEW_ONLY"))
+ : original(...args),
+ );
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "input",
+ epoch: "lease",
+ sequence: 1,
+ events: [{ kind: "button", button: 0, down: true, x: 0.5, y: 0.5 }],
+ }),
+ },
+ });
+ });
+ // The host retracted control: view only, no session rebuild.
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ expect(sent()).toContainEqual({ type: "control", enabled: false });
+ act(() => button("operations").click());
+ expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ });
+ it("keeps control and the session when an input reply is lost", async () => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "input"
+ ? Promise.reject(Object.assign(new Error("timeout"), { code: "INVOKE_TIMEOUT" }))
+ : original(...args),
+ );
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({
+ type: "input",
+ epoch: "lease",
+ sequence: 1,
+ events: [{ kind: "key", code: "KeyA", down: true }],
+ }),
+ },
+ });
+ });
+ // The batch may have been injected: releasing here would drop its key-up.
+ expect(sent()).not.toContainEqual({ type: "control", enabled: false });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
+ it("follows the host to view only when its heartbeat stops counting this viewer as controlling", async () => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) =>
+ args[2][0].op === "heartbeat"
+ ? Promise.resolve({ controlling: false })
+ : original(...args),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ expect(sent()).toContainEqual({ type: "control", enabled: false });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ act(() => button("operations").click());
+ expect(visibleInputHint()).toBe("remoteDesktop.viewOnlyHint");
+ });
+ it("releases a stalled input batch instead of rebuilding the session", async () => {
+ await connect();
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({ type: "inputOverflow", epoch: "lease" }),
+ },
+ });
+ });
+ expect(sent()).toContainEqual({ type: "control", enabled: false });
+ // The WebView overflow replaces pending with a release, then this handler
+ // posts control:false which clears that release without flushing it. The
+ // host must still drop control so a held key/button cannot stay down.
+ expect(requests()).toContainEqual({
+ op: "control",
+ lease: "lease",
+ enabled: false,
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
+ it("retries a timed-out overflow release when the host still reports control", async () => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) => {
+ const req = args[2][0];
+ if (req.op === "control" && req.enabled === false)
+ return Promise.reject(
+ Object.assign(new Error("timeout"), { code: "INVOKE_TIMEOUT" }),
+ );
+ if (req.op === "heartbeat")
+ return Promise.resolve({ controlling: true });
+ return original(...args);
+ });
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({ type: "inputOverflow", epoch: "lease" }),
+ },
+ });
+ });
+ const released = requests().filter(
+ (r) => r.op === "control" && r.enabled === false,
+ );
+ expect(released).toHaveLength(1);
+ expect(sent()).toContainEqual({ type: "control", enabled: false });
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ // Local view-only is not proof the host dropped control; retry the release
+ // so a held key cannot stay down behind a view-only phone.
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled === false),
+ ).toHaveLength(2);
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
+ it("finishes a timed-out overflow release before taking control again", async () => {
+ await connect();
+ const original = fixture.invoke.getMockImplementation()!;
+ let falseAttempts = 0;
+ fixture.invoke.mockImplementation((...args) => {
+ const req = args[2][0];
+ if (req.op === "control" && req.enabled === false) {
+ falseAttempts += 1;
+ if (falseAttempts === 1)
+ return Promise.reject(
+ Object.assign(new Error("timeout"), { code: "INVOKE_TIMEOUT" }),
+ );
+ return Promise.resolve({ controlling: false });
+ }
+ if (req.op === "heartbeat")
+ return Promise.resolve({ controlling: true });
+ return original(...args);
+ });
+ await act(async () => {
+ fixture.message!({
+ nativeEvent: {
+ data: JSON.stringify({ type: "inputOverflow", epoch: "lease" }),
+ },
+ });
+ });
+ expect(
+ requests().filter((r) => r.op === "control" && r.enabled === false),
+ ).toHaveLength(1);
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ const controlOps = requests()
+ .filter((r) => r.op === "control")
+ .map((r) => r.enabled);
+ // Overflow timed out with pending release. Take control must finish that
+ // release (host stopInput) before asking to enable, so the helper restarts.
+ expect(controlOps).toEqual([true, false, false, true]);
+ expect(sent().filter((m) => m.type === "control").at(-1)).toEqual({
+ type: "control",
+ enabled: true,
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
+ it("restores control when a take-control reply is lost but the host still holds it", async () => {
+ await connect();
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ const original = fixture.invoke.getMockImplementation()!;
+ fixture.invoke.mockImplementation((...args) => {
+ const req = args[2][0];
+ if (req.op === "control" && req.enabled === true)
+ return Promise.reject(
+ Object.assign(new Error("timeout"), { code: "INVOKE_TIMEOUT" }),
+ );
+ if (req.op === "heartbeat")
+ return Promise.resolve({ controlling: true });
+ return original(...args);
+ });
+ await act(async () => button("viewOnly").click());
+ expect(sent().filter((m) => m.type === "control").at(-1)).toEqual({
+ type: "control",
+ enabled: false,
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ expect(sent().filter((m) => m.type === "control").at(-1)).toEqual({
+ type: "control",
+ enabled: true,
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
+ it("keeps a take-control intent when a settling heartbeat still reports view-only", async () => {
+ await connect();
+ act(() => button("operations").click());
+ await act(async () => button("viewOnly").click());
+ const original = fixture.invoke.getMockImplementation()!;
+ let rejectTakeControl: ((cause: unknown) => void) | undefined;
+ let heartbeats = 0;
+ fixture.invoke.mockImplementation((...args) => {
+ const req = args[2][0];
+ if (req.op === "control" && req.enabled === true) {
+ return new Promise((_, reject) => {
+ rejectTakeControl = reject;
+ });
+ }
+ if (req.op === "heartbeat") {
+ heartbeats += 1;
+ // startInput is still settling on the first beat; the host only
+ // reports control after the lost take-control reply.
+ return Promise.resolve({ controlling: heartbeats > 1 });
+ }
+ return original(...args);
+ });
+ act(() => button("viewOnly").click());
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ await act(async () => {
+ rejectTakeControl!(
+ Object.assign(new Error("timeout"), { code: "INVOKE_TIMEOUT" }),
+ );
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(3000));
+ // A heartbeat issued while startInput was settling must not consume the
+ // pending take-control; after the reply is lost, host-true still restores.
+ expect(sent().filter((m) => m.type === "control").at(-1)).toEqual({
+ type: "control",
+ enabled: true,
+ });
+ expect(requests().filter((r) => r.op === "stop")).toHaveLength(0);
+ expect(host.textContent).not.toContain("remoteDesktop.reconnecting");
+ });
it("shows virtual mouse buttons outside the panel and hides them while viewing only", async () => {
await connect();
act(() => button("operations").click());
diff --git a/apps/mobile/src/remote-desktop/controlFailure.ts b/apps/mobile/src/remote-desktop/controlFailure.ts
new file mode 100644
index 0000000000..f6c66bf1e7
--- /dev/null
+++ b/apps/mobile/src/remote-desktop/controlFailure.ts
@@ -0,0 +1,57 @@
+/** Failure classification for mobile remote desktop.
+ *
+ * Control is a lease-scoped capability, not a session: the host can refuse,
+ * fail or retract input while the viewer keeps its lease, its video and its
+ * picture. Errors in that class must never rebuild the whole remote desktop —
+ * they release control and leave the session running. Failures whose outcome is
+ * unknown (a lost reply) are neither: guessing either way would either strand
+ * input or needlessly drop the picture.
+ */
+
+export type ControlFailureAction =
+ // The host no longer counts this viewer as controlling: drop to view only.
+ | "release"
+ // Unknown or transient: keep control and let the next attempt decide.
+ | "ignore"
+ // The lease itself is unusable: rebuild the session with the existing path.
+ | "rebuild";
+
+/** Failure codes that mean "this viewer lost control", not "the session died". */
+const CONTROL_LOSS_CODES = new Set([
+ // Host released control, typically because input injection failed.
+ "DESKTOP_VIEW_ONLY",
+ // Host has no usable input helper or display for this lease.
+ "DESKTOP_INPUT_UNAVAILABLE",
+]);
+
+/** Failure codes whose outcome is unknown: neither release nor rebuild. */
+const UNKNOWN_OUTCOME_CODES = new Set([
+ // The batch may or may not have been injected; the heartbeat owns liveness.
+ "INVOKE_TIMEOUT",
+ // Another control request for this lease is still settling.
+ "DESKTOP_INPUT_BUSY",
+]);
+
+/** Stable error code of a remote-desktop failure, or undefined when unknown. */
+export function remoteDesktopErrorCode(cause: unknown): string | undefined {
+ const message = cause instanceof Error ? cause.message : String(cause);
+ const code =
+ cause &&
+ typeof cause === "object" &&
+ "code" in cause &&
+ typeof cause.code === "string"
+ ? cause.code
+ : message.match(
+ /\b(?:DESKTOP|CHANNEL|DEVICE|INVOKE|REMOTE|ACCESS)_[A-Z_]+\b/,
+ )?.[0];
+ return code && /^[A-Z_]+$/.test(code) ? code : undefined;
+}
+
+/** What a failed input or control request should do to this viewer. */
+export function controlFailureAction(cause: unknown): ControlFailureAction {
+ const code = remoteDesktopErrorCode(cause);
+ if (code === undefined) return "rebuild";
+ if (CONTROL_LOSS_CODES.has(code)) return "release";
+ if (UNKNOWN_OUTCOME_CODES.has(code)) return "ignore";
+ return "rebuild";
+}
diff --git a/docs/remote-desktop.md b/docs/remote-desktop.md
index 6690b4baac..669fdd72ac 100644
--- a/docs/remote-desktop.md
+++ b/docs/remote-desktop.md
@@ -137,6 +137,54 @@ This harness does not validate WKWebView, Android WebView, carrier NAT, regional
STUN availability, TURN relay performance or Windows native capture. Those need
device/network verification before claiming a measured connection-success gain.
+## Input failure releases control (2026-09-11)
+
+Control is a lease-scoped capability, not the session itself. When the host can
+no longer inject input — the native helper died, it reported a failed injection,
+or its write path failed — it releases control and keeps everything else: the
+lease, the capture owner, the video track and the last picture. It does not call
+`stop()`, so an input fault can never surface as an ended desktop session.
+
+The host also releases control when its own input path refuses a batch before
+injecting anything, so the two sides cannot disagree about who controls: a later
+take-control genuinely restarts the helper instead of being skipped as "already
+controlling".
+
+The viewer follows the host's control bit instead of rebuilding the session. A
+rejected input batch, a failed control request or a heartbeat that reports
+`controlling: false` all drop the phone to view only with the existing view-only
+hint and take-control action; media and lease identity are untouched. A dropped
+stalled batch (WebView overflow) also asks the host to drop control: posting
+`control:false` to the WebView clears its queued release without flushing it, so
+only an explicit host `control enabled:false` (which stops the input helper and
+injects a native release) can let go of a held key or button. If that host
+request times out, the viewer keeps the intended control bit and the next
+heartbeat retries the release (or restores local control after a lost
+take-control reply) instead of ignoring a host-`true` while the phone stays
+view-only. A heartbeat that still reports view-only while `startInput()` is
+settling does not consume that pending take-control: only a later beat, after
+the transition, may reconcile. An unconfirmed overflow release stays
+authoritative until the host is view-only: taking control finishes that
+release (`stopInput`) before asking to enable, so the helper restarts. Errors whose outcome is unknown — a lost reply (`INVOKE_TIMEOUT`) or
+a control request that collides with one still settling — do not rebuild the
+session: a batch that may have been injected must not be answered with a
+release that discards its key-up, and the heartbeat still owns liveness. Errors
+that do mean the lease is gone (`DESKTOP_LEASE_EXPIRED`, `DESKTOP_STOPPED`,
+revocation, an unsupported channel) still recover the session as before.
+
+This matters most on Windows, where the SendInput helper reports a failed
+injection as a helper failure whereas the macOS helper posts events without a
+result path. On Windows the helper now costs control only; whether a specific
+machine can inject at all (elevated foreground window, secure desktop, a session
+worker outside the interactive window station) is a separate, still unverified
+question, and the helper's `error` line does not yet carry a reason.
+
+Deterministic tests cover the controller release (lease, media and single-viewer
+arbitration retained; later input refused as view-only; control can be taken
+again), the desktop wiring that turns a refused or failed input batch into a
+release rather than a stop, the failure classification (release, unknown outcome,
+rebuild), and the viewer paths that drop to view only without reconnecting.
+
## Authority and lifetime
On macOS, enabling remote desktop automatically checks screen recording in the