-
Notifications
You must be signed in to change notification settings - Fork 16.4k
Expand file tree
/
Copy pathremoteControlServer.tsx
More file actions
279 lines (246 loc) · 7.84 KB
/
Copy pathremoteControlServer.tsx
File metadata and controls
279 lines (246 loc) · 7.84 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { type ChildProcess } from 'child_process';
import { resolve } from 'path';
import * as React from 'react';
import { useEffect, useState } from 'react';
import { getBridgeDisabledReason } from '../../bridge/bridgeEnabled.js';
import { getBridgeAccessToken } from '../../bridge/bridgeConfig.js';
import { BRIDGE_LOGIN_INSTRUCTION } from '../../bridge/types.js';
import { Dialog } from '../../components/design-system/Dialog.js';
import { ListItem } from '../../components/design-system/ListItem.js';
import { useRegisterOverlay } from '../../context/overlayContext.js';
import { Box, Text } from '@anthropic/ink';
import { useKeybindings } from '../../keybindings/useKeybinding.js';
import { buildCliLaunch, spawnCli } from '../../utils/cliLaunch.js';
import type { ToolUseContext } from '../../Tool.js';
import type { LocalJSXCommandContext, LocalJSXCommandOnDone } from '../../types/command.js';
import { errorMessage } from '../../utils/errors.js';
type ServerStatus = 'stopped' | 'starting' | 'running' | 'error';
type Props = {
onDone: LocalJSXCommandOnDone;
};
/**
* /remote-control-server command — manages the daemon-backed persistent bridge server.
*
* When invoked, it starts the daemon supervisor as a child process, which in
* turn spawns remoteControl workers that run headless bridge loops. The server
* accepts multiple concurrent remote sessions.
*
* If the server is already running, shows a management dialog with status
* and options to stop or continue.
*/
// Module-level state to track the daemon process across invocations
let daemonProcess: ChildProcess | null = null;
let daemonStatus: ServerStatus = 'stopped';
let daemonLogs: string[] = [];
const MAX_LOG_LINES = 50;
function RemoteControlServer({ onDone }: Props): React.ReactNode {
const [status, setStatus] = useState<ServerStatus>(daemonStatus);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// If already running, show management dialog
if (daemonProcess && !daemonProcess.killed) {
setStatus('running');
return;
}
let cancelled = false;
void (async () => {
// Pre-flight checks
const checkError = await checkPrerequisites();
if (cancelled) return;
if (checkError) {
onDone(checkError, { display: 'system' });
return;
}
// Start the daemon
setStatus('starting');
try {
startDaemon();
if (!cancelled) {
setStatus('running');
daemonStatus = 'running';
onDone('Remote Control Server started. Use /remote-control-server to manage.', { display: 'system' });
}
} catch (err) {
if (!cancelled) {
const msg = errorMessage(err);
setStatus('error');
setError(msg);
daemonStatus = 'error';
onDone(`Remote Control Server failed to start: ${msg}`, {
display: 'system',
});
}
}
})();
return () => {
cancelled = true;
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps
if (status === 'running' && daemonProcess && !daemonProcess.killed) {
return <ServerManagementDialog onDone={onDone} />;
}
if (status === 'error' && error) {
return null;
}
return null;
}
/**
* Dialog shown when /remote-control-server is used while the daemon is running.
*/
function ServerManagementDialog({ onDone }: Props): React.ReactNode {
useRegisterOverlay('remote-control-server-dialog');
const [focusIndex, setFocusIndex] = useState(2);
const logPreview = daemonLogs.slice(-5);
function handleStop(): void {
stopDaemon();
onDone('Remote Control Server stopped.', { display: 'system' });
}
function handleRestart(): void {
stopDaemon();
try {
startDaemon();
onDone('Remote Control Server restarted.', { display: 'system' });
} catch (err) {
onDone(`Failed to restart: ${errorMessage(err)}`, { display: 'system' });
}
}
function handleContinue(): void {
onDone(undefined, { display: 'skip' });
}
const ITEM_COUNT = 3;
useKeybindings(
{
'select:next': () => setFocusIndex(i => (i + 1) % ITEM_COUNT),
'select:previous': () => setFocusIndex(i => (i - 1 + ITEM_COUNT) % ITEM_COUNT),
'select:accept': () => {
if (focusIndex === 0) {
handleStop();
} else if (focusIndex === 1) {
handleRestart();
} else {
handleContinue();
}
},
},
{ context: 'Select' },
);
return (
<Dialog title="Remote Control Server" onCancel={handleContinue} hideInputGuide>
<Box flexDirection="column" gap={1}>
<Text>
Remote Control Server is{' '}
<Text bold color="success">
running
</Text>
{daemonProcess ? ` (PID: ${daemonProcess.pid})` : ''}
</Text>
{logPreview.length > 0 && (
<Box flexDirection="column">
<Text dimColor>Recent logs:</Text>
{logPreview.map((line, i) => (
<Text key={i} dimColor>
{line}
</Text>
))}
</Box>
)}
<Box flexDirection="column">
<ListItem isFocused={focusIndex === 0}>
<Text>Stop server</Text>
</ListItem>
<ListItem isFocused={focusIndex === 1}>
<Text>Restart server</Text>
</ListItem>
<ListItem isFocused={focusIndex === 2}>
<Text>Continue</Text>
</ListItem>
</Box>
<Text dimColor>Enter to select · Esc to continue</Text>
</Box>
</Dialog>
);
}
/**
* Check prerequisites for starting the Remote Control Server.
*/
async function checkPrerequisites(): Promise<string | null> {
const disabledReason = await getBridgeDisabledReason();
if (disabledReason) {
return disabledReason;
}
if (!getBridgeAccessToken()) {
return BRIDGE_LOGIN_INSTRUCTION;
}
return null;
}
/**
* Start the daemon supervisor as a child process.
*/
function startDaemon(): void {
const dir = resolve('.');
const launch = buildCliLaunch(['daemon', 'start', `--dir=${dir}`]);
const child = spawnCli(launch, {
cwd: dir,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false,
});
daemonProcess = child;
daemonLogs = [];
child.stdout?.on('data', (data: Buffer) => {
const lines = data.toString().trimEnd().split('\n');
for (const line of lines) {
daemonLogs.push(line);
if (daemonLogs.length > MAX_LOG_LINES) {
daemonLogs.shift();
}
}
});
child.stderr?.on('data', (data: Buffer) => {
const lines = data.toString().trimEnd().split('\n');
for (const line of lines) {
daemonLogs.push(`[err] ${line}`);
if (daemonLogs.length > MAX_LOG_LINES) {
daemonLogs.shift();
}
}
});
child.on('exit', (code: number | null, signal: NodeJS.Signals | null) => {
daemonProcess = null;
daemonStatus = 'stopped';
daemonLogs.push(`[daemon] exited (code=${code ?? 'unknown'}, signal=${signal})`);
});
child.on('error', (err: Error) => {
daemonProcess = null;
daemonStatus = 'error';
daemonLogs.push(`[daemon] error: ${err.message}`);
});
}
/**
* Stop the daemon supervisor.
*/
function stopDaemon(): void {
if (daemonProcess && !daemonProcess.killed) {
daemonProcess.kill('SIGTERM');
// Force kill after 10s grace
const pid = daemonProcess.pid;
setTimeout(() => {
try {
if (pid) process.kill(pid, 0); // Check if still alive
if (daemonProcess && !daemonProcess.killed) {
daemonProcess.kill('SIGKILL');
}
} catch {
// Process already gone
}
}, 10_000);
}
daemonProcess = null;
daemonStatus = 'stopped';
}
export async function call(
onDone: LocalJSXCommandOnDone,
_context: ToolUseContext & LocalJSXCommandContext,
_args: string,
): Promise<React.ReactNode> {
return <RemoteControlServer onDone={onDone} />;
}