-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-executor.ts
More file actions
261 lines (235 loc) · 8.88 KB
/
Copy pathcommand-executor.ts
File metadata and controls
261 lines (235 loc) · 8.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import type { CommandRequest, MouseButton } from '../../shared/protocol';
import {
MAX_POINTER_DELTA,
MAX_SCROLL_DELTA,
MAX_SHORTCUT_KEYS,
MAX_TEXT_LENGTH,
PROTOCOL_VERSION
} from '../../shared/protocol';
import type { DesktopInputAdapter } from './desktop-input-adapter';
import { DesktopInputError } from './desktop-input-adapter';
export type CommandExecutionResult =
| { ok: true }
| { ok: false; code: 'unsupported_command' | 'unsafe_payload' | 'adapter_failure'; message: string };
export type CursorOverlayNotifier = {
show(event: 'move' | 'click'): void;
hide?(): void;
markControlActive?(): void;
};
export class DesktopCommandExecutor {
private pointerActionQueue: Promise<void> = Promise.resolve();
private activeDragButton: MouseButton | null = null;
private pendingRealtimeMove: { dx: number; dy: number } | null = null;
private realtimeMoveFlush: Promise<CommandExecutionResult> | null = null;
constructor(
private readonly adapter: DesktopInputAdapter,
private readonly cursorOverlay?: CursorOverlayNotifier
) {}
async execute(command: CommandRequest): Promise<CommandExecutionResult> {
if (command.type === 'mouse.move' && command.responseMode === 'none') {
return this.enqueueCoalescedMouseMove(command);
}
if (isPointerAction(command)) {
return this.enqueuePointerAction(command);
}
return this.executeNow(command);
}
async releaseHeldMouseButtons(): Promise<void> {
const release = this.pointerActionQueue.then(async () => {
if (!this.activeDragButton) return;
const button = this.activeDragButton;
await this.adapter.setMouseButtonDown(button, false);
this.activeDragButton = null;
});
this.pointerActionQueue = release.then(
() => undefined,
() => undefined
);
await release;
}
private async enqueuePointerAction(
command: CommandRequest & { type: 'mouse.move' | 'mouse.dragStart' | 'mouse.dragEnd' }
): Promise<CommandExecutionResult> {
const result = this.pointerActionQueue.then(() => this.executeNow(command));
this.pointerActionQueue = result.then(
() => undefined,
() => undefined
);
return result;
}
private enqueueCoalescedMouseMove(command: CommandRequest & { type: 'mouse.move' }): Promise<CommandExecutionResult> {
this.pendingRealtimeMove = addMouseDeltas(this.pendingRealtimeMove, command.payload);
if (this.realtimeMoveFlush) {
return Promise.resolve({ ok: true });
}
const result = this.pointerActionQueue.then(() => this.flushRealtimeMouseMoves());
this.realtimeMoveFlush = result;
this.pointerActionQueue = result.then(
() => undefined,
() => undefined
);
return result;
}
private async flushRealtimeMouseMoves(): Promise<CommandExecutionResult> {
try {
while (this.pendingRealtimeMove) {
const payload = this.pendingRealtimeMove;
this.pendingRealtimeMove = null;
const result = await this.executeNow({
version: PROTOCOL_VERSION,
id: 'realtime-move',
deviceId: 'realtime',
timestamp: Date.now(),
type: 'mouse.move',
payload,
auth: '',
responseMode: 'none'
});
if (!result.ok) {
return result;
}
}
return { ok: true };
} finally {
this.realtimeMoveFlush = null;
if (this.pendingRealtimeMove) {
const result = this.pointerActionQueue.then(() => this.flushRealtimeMouseMoves());
this.realtimeMoveFlush = result;
this.pointerActionQueue = result.then(
() => undefined,
() => undefined
);
}
}
}
private async executeNow(command: CommandRequest): Promise<CommandExecutionResult> {
try {
if (isMouseCommand(command)) {
this.cursorOverlay?.markControlActive?.();
} else {
this.cursorOverlay?.hide?.();
}
switch (command.type) {
case 'mouse.move':
assertBoundedNumber(command.payload.dx, MAX_POINTER_DELTA, 'dx');
assertBoundedNumber(command.payload.dy, MAX_POINTER_DELTA, 'dy');
await this.adapter.moveMouseBy(command.payload);
this.cursorOverlay?.show('move');
return { ok: true };
case 'mouse.dragStart':
await this.startDrag(command.payload.button);
this.cursorOverlay?.show('move');
return { ok: true };
case 'mouse.dragEnd':
await this.endDrag(command.payload.button);
this.cursorOverlay?.show('move');
return { ok: true };
case 'mouse.click':
await this.adapter.clickMouse(command.payload.button);
this.cursorOverlay?.show('click');
return { ok: true };
case 'mouse.doubleClick':
await this.adapter.doubleClickMouse(command.payload.button);
this.cursorOverlay?.show('click');
return { ok: true };
case 'mouse.rightClick':
await this.adapter.clickMouse('right');
this.cursorOverlay?.show('click');
return { ok: true };
case 'mouse.scroll':
assertBoundedNumber(command.payload.dx, MAX_SCROLL_DELTA, 'dx');
assertBoundedNumber(command.payload.dy, MAX_SCROLL_DELTA, 'dy');
await this.adapter.scrollMouse(command.payload);
return { ok: true };
case 'keyboard.key':
await this.adapter.pressKey(command.payload.key);
return { ok: true };
case 'keyboard.shortcut':
if (command.payload.keys.length === 0 || command.payload.keys.length > MAX_SHORTCUT_KEYS) {
return unsafe('Shortcut key count is invalid.');
}
await this.adapter.pressShortcut(command.payload.keys);
return { ok: true };
case 'keyboard.typeText':
if (command.payload.text.length > MAX_TEXT_LENGTH) {
return unsafe('Text payload is too long.');
}
await this.adapter.typeText(command.payload.text);
return { ok: true };
case 'media.control':
await this.adapter.mediaControl(command.payload.action);
return { ok: true };
case 'window.control':
await this.adapter.controlWindow(command.payload.action);
return { ok: true };
case 'connection.ping':
return { ok: true };
case 'connection.disconnecting':
return { ok: false, code: 'unsupported_command', message: 'Disconnect intent must be handled by the server.' };
case 'pointer.profile':
return { ok: false, code: 'unsupported_command', message: 'Pointer profile must be handled by the server.' };
}
} catch (error) {
if (error instanceof DesktopInputError) {
return { ok: false, code: error.code, message: error.message };
}
return {
ok: false,
code: 'adapter_failure',
message: error instanceof Error ? error.message : 'Desktop input failed.'
};
}
}
private async startDrag(button: MouseButton): Promise<void> {
if (this.activeDragButton === button) return;
if (this.activeDragButton) {
const previousButton = this.activeDragButton;
await this.adapter.setMouseButtonDown(previousButton, false);
this.activeDragButton = null;
}
await this.adapter.setMouseButtonDown(button, true);
this.activeDragButton = button;
}
private async endDrag(_button: MouseButton): Promise<void> {
if (!this.activeDragButton) return;
const buttonToRelease = this.activeDragButton;
await this.adapter.setMouseButtonDown(buttonToRelease, false);
this.activeDragButton = null;
}
}
function assertBoundedNumber(value: number, maxAbsValue: number, label: string): void {
if (!Number.isFinite(value) || Math.abs(value) > maxAbsValue) {
throw new DesktopInputError('unsafe_payload', `${label} is outside allowed bounds.`);
}
}
function unsafe(message: string): CommandExecutionResult {
return { ok: false, code: 'unsafe_payload', message };
}
function addMouseDeltas(
current: { dx: number; dy: number } | null,
next: { dx: number; dy: number }
): { dx: number; dy: number } {
return {
dx: clampDelta((current?.dx ?? 0) + next.dx),
dy: clampDelta((current?.dy ?? 0) + next.dy)
};
}
function clampDelta(value: number): number {
return Math.max(-MAX_POINTER_DELTA, Math.min(MAX_POINTER_DELTA, value));
}
function isPointerAction(
command: CommandRequest
): command is CommandRequest & { type: 'mouse.move' | 'mouse.dragStart' | 'mouse.dragEnd' } {
return command.type === 'mouse.move' || command.type === 'mouse.dragStart' || command.type === 'mouse.dragEnd';
}
function isMouseCommand(command: CommandRequest): boolean {
return (
command.type === 'mouse.move' ||
command.type === 'mouse.click' ||
command.type === 'mouse.doubleClick' ||
command.type === 'mouse.rightClick' ||
command.type === 'mouse.scroll' ||
command.type === 'mouse.dragStart' ||
command.type === 'mouse.dragEnd'
);
}