forked from mxx1111/remote-code-mobile
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoteShellDemo.tsx
More file actions
1414 lines (1327 loc) · 52.3 KB
/
Copy pathRemoteShellDemo.tsx
File metadata and controls
1414 lines (1327 loc) · 52.3 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client";
import {
FormEvent,
KeyboardEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
type Project = {
id: string;
name: string;
shortName: string;
machine: string;
path: string;
branch: string;
activity: string;
status: "running" | "idle" | "offline";
color: string;
connected: boolean;
};
type MessageStatus = "running" | "completed" | "failed" | "stopped";
type ChatMode = "shell" | "codex" | "claude";
type ClaudePermissionMode = "manual" | "acceptEdits" | "plan" | "auto";
type ChatMessage = {
id: string;
role: "user" | "assistant";
content: string;
createdAt?: number;
output?: boolean;
runId?: string;
mode?: ChatMode;
status?: MessageStatus;
exitCode?: number | null;
streaming?: boolean;
turnId?: string;
updatedAt?: number;
};
type ServerRun = {
activity: string;
assistantMessageId?: string | null;
id: string;
mode: ChatMode;
output: string;
permissionMode?: ClaudePermissionMode | null;
running: boolean;
interrupted: boolean;
exitCode: number | null;
turnId?: string | null;
updatedAt?: number;
userMessageId?: string | null;
};
type ClaudeConversationSnapshot = {
activeRun: ServerRun | null;
hasSession: boolean;
messages: ChatMessage[];
updatedAt: number | null;
};
type ProjectCatalogResponse = {
projects: Project[];
root: string;
terminalPort: number;
};
type MessagesByMode = Record<ChatMode, ChatMessage[]>;
type MessagesByProject = Record<string, MessagesByMode>;
const FALLBACK_PROJECT: Project = {
activity: "正在连接",
branch: "loading",
color: "violet",
connected: false,
id: "__loading__",
machine: "This Mac",
name: "正在读取项目",
path: "~/Projects",
shortName: "RS",
status: "offline",
};
const PINNED_PROJECTS_KEY = "remote-shell-pinned-projects";
const SELECTED_PROJECT_KEY = "remote-shell-selected-project";
const CLAUDE_PERMISSION_MODE_KEY = "remote-shell-claude-permission-mode";
const IOS_INSTALL_HINT_KEY = "remote-shell-ios-install-hint-dismissed";
const CLAUDE_PERMISSION_MODES: Array<{
label: string;
value: ClaudePermissionMode;
}> = [
{ label: "Manual", value: "manual" },
{ label: "Edits", value: "acceptEdits" },
{ label: "Plan", value: "plan" },
{ label: "Auto", value: "auto" },
];
function isClaudePermissionMode(value: string | null): value is ClaudePermissionMode {
return CLAUDE_PERMISSION_MODES.some((mode) => mode.value === value);
}
async function fetchProjectCatalog(refresh = false): Promise<ProjectCatalogResponse> {
const response = await fetch(`/api/projects${refresh ? "?refresh=1" : ""}`);
const payload = await response.json() as ProjectCatalogResponse | { error?: string };
if (!response.ok || !("projects" in payload)) {
throw new Error("error" in payload && payload.error ? payload.error : "无法读取 Mac 项目");
}
return payload;
}
async function fetchClaudeConversation(
projectId: string,
signal?: AbortSignal,
): Promise<ClaudeConversationSnapshot> {
const response = await fetch(
`/api/projects/${encodeURIComponent(projectId)}/conversations/claude`,
{ signal },
);
const payload = await response.json() as ClaudeConversationSnapshot | { error?: string };
if (!response.ok || !("messages" in payload)) {
throw new Error("error" in payload && payload.error ? payload.error : "无法恢复 Claude 对话");
}
return payload;
}
function initialMessagesForMode(mode: ChatMode): ChatMessage[] {
if (mode === "codex") {
return [
{
id: "codex-ready",
role: "assistant",
mode,
content: "Codex 独立会话已就绪。这里只显示 Codex 的对话;输入 claude 或 shell 可以切换工作方式。",
},
];
}
if (mode === "claude") {
return [
{
id: "claude-ready",
role: "assistant",
mode,
content: "Claude 独立会话已就绪。这里只显示 Claude 的对话;输入 codex 或 shell 可以切换工作方式。",
},
];
}
return [
{
id: "shell-ready",
role: "assistant",
mode,
content:
"移动工作台已经连接。输入 codex、claude 或 shell 就能切换工作方式,也可以直接输入“codex 帮我检查改动”。",
},
];
}
function createInitialMessagesByMode(): MessagesByMode {
return {
shell: initialMessagesForMode("shell"),
codex: initialMessagesForMode("codex"),
claude: initialMessagesForMode("claude"),
};
}
const SHELL_QUICK_COMMANDS = [
{ label: "当前位置", command: "pwd" },
{ label: "当前改动", command: "git status --short" },
{ label: "最近提交", command: "git log -5 --oneline" },
];
const CODEX_QUICK_PROMPTS = [
{ label: "打个招呼", command: "你好,简单介绍一下你能在这个项目里做什么。" },
{ label: "检查改动", command: "检查当前项目改动并总结,先不要修改文件。" },
{ label: "了解项目", command: "快速了解这个项目的结构并简要说明。" },
];
const CLAUDE_QUICK_PROMPTS = [
{ label: "打个招呼", command: "你好,简单介绍一下你能在这个项目里做什么。" },
{ label: "检查改动", command: "检查当前项目改动并总结,先不要修改文件。" },
{ label: "继续任务", command: "查看当前项目状态,告诉我接下来适合做什么。" },
];
const TERMINAL_KEYS = [
{ key: "escape", label: "Esc", ariaLabel: "Escape" },
{ key: "tab", label: "Tab", ariaLabel: "Tab" },
{ key: "shift-tab", label: "⇧Tab", ariaLabel: "Shift Tab" },
{ key: "ctrl-c", label: "⌃C", ariaLabel: "Control C" },
{ key: "up", label: "↑", ariaLabel: "方向上" },
{ key: "down", label: "↓", ariaLabel: "方向下" },
{ key: "clear", label: "清屏", ariaLabel: "Control L 清屏" },
];
function makeId(prefix: string) {
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function runStatus(run: ServerRun): MessageStatus {
if (run.running) return "running";
if (run.interrupted) return "stopped";
return run.exitCode === 0 ? "completed" : "failed";
}
function resultLabel(message: ChatMessage) {
if (message.status === "stopped") return "已停止";
if (message.status === "completed") {
if (message.mode === "codex") return "Codex 已回复";
if (message.mode === "claude") return "Claude 已回复";
return "执行完成";
}
if (message.status === "failed") return `退出码 ${message.exitCode ?? 1}`;
return "执行中";
}
export function RemoteShellDemo() {
const [projects, setProjects] = useState<Project[]>([FALLBACK_PROJECT]);
const [pinnedProjectIds, setPinnedProjectIds] = useState<string[]>([FALLBACK_PROJECT.id]);
const [selectedProjectId, setSelectedProjectId] = useState(FALLBACK_PROJECT.id);
const [mobileScreen, setMobileScreen] = useState<"projects" | "chat">("projects");
const [viewMode, setViewMode] = useState<"chat" | "terminal">("chat");
const [chatMode, setChatMode] = useState<ChatMode>("shell");
const [claudePermissionMode, setClaudePermissionMode] = useState<ClaudePermissionMode>("auto");
const [messagesByProject, setMessagesByProject] = useState<MessagesByProject>(() => ({
[FALLBACK_PROJECT.id]: createInitialMessagesByMode(),
}));
const [draft, setDraft] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
const [isStopping, setIsStopping] = useState(false);
const [isResettingSession, setIsResettingSession] = useState(false);
const [isHydratingClaude, setIsHydratingClaude] = useState(false);
const [activeActivity, setActiveActivity] = useState("");
const [activeTab, setActiveTab] = useState<"projects" | "activity" | "settings">(
"projects",
);
const [terminalBaseUrl, setTerminalBaseUrl] = useState("");
const [terminalPort, setTerminalPort] = useState(7681);
const [terminalFrameLoaded, setTerminalFrameLoaded] = useState(false);
const [terminalReady, setTerminalReady] = useState(false);
const [terminalKeyError, setTerminalKeyError] = useState("");
const [projectRootLabel, setProjectRootLabel] = useState("~/java/project");
const [projectSearch, setProjectSearch] = useState("");
const [projectLoadError, setProjectLoadError] = useState("");
const [isLoadingProjects, setIsLoadingProjects] = useState(false);
const [showProjectPicker, setShowProjectPicker] = useState(false);
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [showIosInstallHint, setShowIosInstallHint] = useState(false);
const [installHintNeedsHttps, setInstallHintNeedsHttps] = useState(false);
const feedRef = useRef<HTMLDivElement | null>(null);
const draftRef = useRef<HTMLTextAreaElement | null>(null);
const eventSourceRef = useRef<EventSource | null>(null);
const claudeHydrationRef = useRef(0);
const pendingClaudeStartRef = useRef(false);
const stickToBottomRef = useRef(true);
const activeRunRef = useRef<{
runId: string;
messageId: string;
mode: ChatMode;
projectId: string;
} | null>(
null,
);
const selectedProject = useMemo(
() => projects.find((project) => project.id === selectedProjectId) ?? projects[0] ?? FALLBACK_PROJECT,
[projects, selectedProjectId],
);
const visibleProjects = useMemo(() => {
const byId = new Map(projects.map((project) => [project.id, project]));
const pinned = pinnedProjectIds.map((id) => byId.get(id)).filter(Boolean) as Project[];
if (!pinned.some((project) => project.id === selectedProject.id)) pinned.unshift(selectedProject);
return pinned;
}, [pinnedProjectIds, projects, selectedProject]);
const filteredProjects = useMemo(() => {
const keyword = projectSearch.trim().toLocaleLowerCase("zh-CN");
if (!keyword) return projects;
return projects.filter((project) =>
`${project.name} ${project.path} ${project.branch}`.toLocaleLowerCase("zh-CN").includes(keyword),
);
}, [projectSearch, projects]);
const terminalUrl = selectedProject.connected && terminalBaseUrl
? `${terminalBaseUrl}:${terminalPort}/`
: null;
const projectConnected = selectedProject.connected;
const messages = messagesByProject[selectedProject.id]?.[chatMode] ?? initialMessagesForMode(chatMode);
const chatModeName = chatMode === "codex" ? "Codex" : chatMode === "claude" ? "Claude" : "Shell";
const claudePermissionLabel = CLAUDE_PERMISSION_MODES.find(
(mode) => mode.value === claudePermissionMode,
)?.label ?? "Auto";
const loadProjects = useCallback(async (refresh = false) => {
setIsLoadingProjects(true);
setProjectLoadError("");
try {
const payload = await fetchProjectCatalog(refresh);
setProjects(payload.projects);
setProjectRootLabel(payload.root);
setTerminalPort(payload.terminalPort);
setSelectedProjectId((current) => {
const next = payload.projects.some((project) => project.id === current)
? current
: payload.projects.find((project) => project.id === FALLBACK_PROJECT.id)?.id
?? payload.projects[0]?.id
?? current;
window.localStorage.setItem(SELECTED_PROJECT_KEY, next);
return next;
});
setPinnedProjectIds((current) => {
const availableIds = new Set(payload.projects.map((project) => project.id));
const availablePinned = current.filter((id) => availableIds.has(id));
const next = availablePinned.length
? availablePinned
: payload.projects.find((project) => project.id === FALLBACK_PROJECT.id)
? [FALLBACK_PROJECT.id]
: payload.projects[0]
? [payload.projects[0].id]
: current;
window.localStorage.setItem(PINNED_PROJECTS_KEY, JSON.stringify(next));
return next;
});
} catch (error) {
setProjectLoadError(error instanceof Error ? error.message : "无法读取 Mac 项目");
} finally {
setIsLoadingProjects(false);
}
}, []);
useEffect(() => {
setTerminalBaseUrl(`${window.location.protocol}//${window.location.hostname}`);
const storedMode = window.localStorage.getItem("remote-shell-chat-mode");
if (storedMode === "shell" || storedMode === "codex" || storedMode === "claude") {
setChatMode(storedMode);
}
const storedClaudePermissionMode = window.localStorage.getItem(CLAUDE_PERMISSION_MODE_KEY);
if (isClaudePermissionMode(storedClaudePermissionMode)) {
setClaudePermissionMode(storedClaudePermissionMode);
}
const storedProject = window.localStorage.getItem(SELECTED_PROJECT_KEY);
if (storedProject) setSelectedProjectId(storedProject);
try {
const storedProjects = JSON.parse(window.localStorage.getItem(PINNED_PROJECTS_KEY) ?? "[]");
if (Array.isArray(storedProjects) && storedProjects.every((id) => typeof id === "string")) {
setPinnedProjectIds(storedProjects);
}
} catch {
// Ignore an incomplete device-local preference and keep the default project.
}
void loadProjects();
return () => eventSourceRef.current?.close();
}, [loadProjects]);
useEffect(() => {
const navigatorWithStandalone = window.navigator as Navigator & { standalone?: boolean };
const isIos = /iPad|iPhone|iPod/.test(window.navigator.userAgent)
|| (window.navigator.platform === "MacIntel" && window.navigator.maxTouchPoints > 1);
const isStandalone = window.matchMedia("(display-mode: standalone)").matches
|| navigatorWithStandalone.standalone === true;
const hintDismissed = window.localStorage.getItem(IOS_INSTALL_HINT_KEY) === "1";
setInstallHintNeedsHttps(!window.isSecureContext);
setShowIosInstallHint(isIos && !isStandalone && !hintDismissed);
}, []);
useEffect(() => {
const feed = feedRef.current;
if (!feed || !stickToBottomRef.current) return;
feed.scrollTop = feed.scrollHeight;
setShowScrollToBottom(false);
}, [messages, isStreaming, viewMode, mobileScreen]);
useEffect(() => {
const input = draftRef.current;
if (!input) return;
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 128)}px`;
}, [draft]);
useEffect(() => {
if (!showProjectPicker) return;
const closeOnEscape = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") setShowProjectPicker(false);
};
window.addEventListener("keydown", closeOnEscape);
return () => window.removeEventListener("keydown", closeOnEscape);
}, [showProjectPicker]);
useEffect(() => {
setTerminalFrameLoaded(false);
setTerminalReady(false);
setTerminalKeyError("");
if (viewMode !== "terminal" || !projectConnected) return;
let cancelled = false;
void fetch(
`/api/projects/${encodeURIComponent(selectedProject.id)}/terminal/activate`,
{ method: "POST" },
).then(async (response) => {
if (!response.ok) {
const payload = await response.json().catch(() => ({})) as { error?: string };
throw new Error(payload.error || "无法打开项目终端");
}
if (!cancelled) setTerminalReady(true);
}).catch((error) => {
if (!cancelled) setTerminalKeyError(error instanceof Error ? error.message : "无法打开项目终端");
});
return () => {
cancelled = true;
};
}, [projectConnected, selectedProject.id, viewMode]);
const openProject = (projectId: string) => {
if ((isStreaming || isResettingSession) && projectId !== selectedProject.id) return;
setPinnedProjectIds((current) => {
const next = [projectId, ...current.filter((id) => id !== projectId)].slice(0, 10);
window.localStorage.setItem(PINNED_PROJECTS_KEY, JSON.stringify(next));
return next;
});
setMessagesByProject((current) => current[projectId]
? current
: { ...current, [projectId]: createInitialMessagesByMode() });
setSelectedProjectId(projectId);
window.localStorage.setItem(SELECTED_PROJECT_KEY, projectId);
setMobileScreen("chat");
setActiveTab("projects");
setViewMode("chat");
setProjectSearch("");
setShowProjectPicker(false);
};
const handleFeedScroll = () => {
const feed = feedRef.current;
if (!feed) return;
const nearBottom = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 96;
stickToBottomRef.current = nearBottom;
setShowScrollToBottom(!nearBottom);
};
const scrollToLatest = () => {
const feed = feedRef.current;
if (!feed) return;
stickToBottomRef.current = true;
setShowScrollToBottom(false);
feed.scrollTop = feed.scrollHeight;
};
const updateModeMessages = useCallback((
projectId: string,
mode: ChatMode,
updater: (current: ChatMessage[]) => ChatMessage[],
) => {
setMessagesByProject((current) => {
const projectMessages = current[projectId] ?? createInitialMessagesByMode();
return {
...current,
[projectId]: {
...projectMessages,
[mode]: updater(projectMessages[mode]),
},
};
});
}, []);
const replaceClaudeMessages = useCallback((
projectId: string,
messages: ChatMessage[],
hasSession = false,
) => {
const restoredMessages = messages.length
? messages
: hasSession
? [
{
id: "claude-session-restored",
role: "assistant" as const,
mode: "claude" as const,
content: "Claude 主会话已恢复。此前的模型上下文仍在;从现在起,新的对话记录也会保存在这台 Mac 上。",
},
]
: initialMessagesForMode("claude");
setMessagesByProject((current) => {
const projectMessages = current[projectId] ?? createInitialMessagesByMode();
return {
...current,
[projectId]: {
...projectMessages,
claude: restoredMessages,
},
};
});
}, []);
const updateRunMessage = useCallback((projectId: string, messageId: string, run: ServerRun) => {
const agentName = run.mode === "codex" ? "Codex" : run.mode === "claude" ? "Claude" : "";
const content = run.output || (run.running
? agentName ? `${agentName} 正在思考…` : "命令正在运行,等待终端输出…"
: agentName ? `${agentName} 已完成,但没有返回文本。` : "命令执行完成,没有产生输出。");
if (run.running) setActiveActivity(run.activity);
updateModeMessages(projectId, run.mode, (current) =>
current.map((message) =>
message.id === messageId
? {
...message,
content,
exitCode: run.exitCode,
mode: run.mode,
output: run.mode === "shell",
runId: run.id,
status: runStatus(run),
streaming: run.running,
}
: message,
),
);
}, [updateModeMessages]);
const watchRun = useCallback((
projectId: string,
runId: string,
messageId: string,
mode: ChatMode,
) => {
const settle = (source: EventSource, settledRunId: string) => {
source.close();
if (eventSourceRef.current === source) eventSourceRef.current = null;
if (activeRunRef.current?.runId === settledRunId) activeRunRef.current = null;
setActiveActivity("");
setIsStreaming(false);
setIsStopping(false);
};
const connect = (nextRunId: string, nextMessageId: string, nextMode: ChatMode) => {
eventSourceRef.current?.close();
const source = new EventSource(
`/api/projects/${encodeURIComponent(projectId)}/runs/${encodeURIComponent(nextRunId)}/events`,
);
let recoveryProbePending = false;
eventSourceRef.current = source;
source.addEventListener("output", (event) => {
const run = JSON.parse((event as MessageEvent).data) as ServerRun;
updateRunMessage(projectId, nextMessageId, run);
});
source.addEventListener("done", (event) => {
const run = JSON.parse((event as MessageEvent).data) as ServerRun;
updateRunMessage(projectId, nextMessageId, run);
settle(source, nextRunId);
});
source.onerror = () => {
if (activeRunRef.current?.runId !== nextRunId) {
source.close();
return;
}
setActiveActivity("连接中断,正在自动重连");
if (recoveryProbePending) return;
recoveryProbePending = true;
void (async () => {
try {
const response = await fetch(
`/api/projects/${encodeURIComponent(projectId)}/runs/${encodeURIComponent(nextRunId)}`,
);
if (response.ok) {
const run = await response.json() as ServerRun;
updateRunMessage(projectId, nextMessageId, run);
if (!run.running) {
settle(source, nextRunId);
} else if (source.readyState === EventSource.CLOSED) {
source.close();
window.setTimeout(() => {
if (activeRunRef.current?.runId === nextRunId) {
connect(nextRunId, nextMessageId, nextMode);
}
}, 750);
}
return;
}
if (response.status === 404 && nextMode === "claude") {
const snapshot = await fetchClaudeConversation(projectId);
replaceClaudeMessages(projectId, snapshot.messages, snapshot.hasSession);
const recoveredRun = snapshot.activeRun;
const recoveredMessageId = recoveredRun?.assistantMessageId
?? snapshot.messages.find((message) => message.runId === recoveredRun?.id)?.id;
if (recoveredRun?.running && recoveredMessageId) {
source.close();
activeRunRef.current = {
messageId: recoveredMessageId,
mode: "claude",
projectId,
runId: recoveredRun.id,
};
updateRunMessage(projectId, recoveredMessageId, recoveredRun);
connect(recoveredRun.id, recoveredMessageId, "claude");
return;
}
settle(source, nextRunId);
}
} catch {
// EventSource keeps retrying while the phone or Mac network is temporarily unavailable.
if (
source.readyState === EventSource.CLOSED
&& activeRunRef.current?.runId === nextRunId
) {
window.setTimeout(() => {
if (activeRunRef.current?.runId === nextRunId) {
connect(nextRunId, nextMessageId, nextMode);
}
}, 1_500);
}
} finally {
recoveryProbePending = false;
}
})();
};
};
connect(runId, messageId, mode);
}, [replaceClaudeMessages, updateRunMessage]);
useEffect(() => {
const hydrationId = ++claudeHydrationRef.current;
if (chatMode !== "claude" || !projectConnected || pendingClaudeStartRef.current) {
setIsHydratingClaude(false);
return;
}
const projectId = selectedProject.id;
const controller = new AbortController();
setIsHydratingClaude(true);
void fetchClaudeConversation(projectId, controller.signal)
.then((snapshot) => {
if (claudeHydrationRef.current !== hydrationId) return;
replaceClaudeMessages(projectId, snapshot.messages, snapshot.hasSession);
const activeRun = snapshot.activeRun;
const assistantMessageId = activeRun?.assistantMessageId
?? snapshot.messages.find((message) => message.runId === activeRun?.id)?.id;
if (!activeRun?.running || !assistantMessageId) return;
activeRunRef.current = {
messageId: assistantMessageId,
mode: "claude",
projectId,
runId: activeRun.id,
};
updateRunMessage(projectId, assistantMessageId, activeRun);
setActiveActivity(activeRun.activity || "正在恢复 Claude 输出");
setIsStreaming(true);
setIsStopping(false);
watchRun(projectId, activeRun.id, assistantMessageId, "claude");
})
.catch((error) => {
if (controller.signal.aborted || claudeHydrationRef.current !== hydrationId) return;
updateModeMessages(projectId, "claude", (current) => [
...current,
{
id: makeId("claude-restore-error"),
role: "assistant",
mode: "claude",
content: error instanceof Error ? error.message : "无法恢复 Claude 对话",
status: "failed",
},
]);
})
.finally(() => {
if (claudeHydrationRef.current === hydrationId) setIsHydratingClaude(false);
});
return () => controller.abort();
}, [
chatMode,
projectConnected,
replaceClaudeMessages,
selectedProject.id,
updateModeMessages,
updateRunMessage,
watchRun,
]);
const changeChatMode = (mode: ChatMode) => {
stickToBottomRef.current = true;
setShowScrollToBottom(false);
setDraft("");
setChatMode(mode);
window.localStorage.setItem("remote-shell-chat-mode", mode);
};
const cycleClaudePermissionMode = () => {
if (isStreaming || isResettingSession || isHydratingClaude) return;
setClaudePermissionMode((current) => {
const currentIndex = CLAUDE_PERMISSION_MODES.findIndex((mode) => mode.value === current);
const next = CLAUDE_PERMISSION_MODES[(currentIndex + 1) % CLAUDE_PERMISSION_MODES.length].value;
window.localStorage.setItem(CLAUDE_PERMISSION_MODE_KEY, next);
return next;
});
};
const runCommand = async (rawCommand: string) => {
const enteredCommand = rawCommand.trim();
if (!enteredCommand || isStreaming || isResettingSession || isHydratingClaude) return;
const projectId = selectedProject.id;
const routeMatch = enteredCommand.match(/^(codex|claude|shell)(?:\s+([\s\S]+))?$/iu);
const requestedMode = routeMatch
? routeMatch[1].toLowerCase() as ChatMode
: chatMode;
const command = routeMatch?.[2]?.trim() || (routeMatch ? "" : enteredCommand);
const startsClaudeFromAnotherMode = Boolean(
routeMatch && requestedMode === "claude" && chatMode !== "claude" && command,
);
if (startsClaudeFromAnotherMode) pendingClaudeStartRef.current = true;
if (routeMatch) changeChatMode(requestedMode);
if (!command) {
const modeName = requestedMode === "codex" ? "Codex" : requestedMode === "claude" ? "Claude" : "Shell";
setDraft("");
updateModeMessages(projectId, requestedMode, (current) => [
...current,
{ id: makeId("user"), role: "user", content: enteredCommand, mode: requestedMode },
{
id: makeId("mode"),
role: "assistant",
content: requestedMode === "shell"
? "已切换到 Shell。接下来输入的内容会作为真实命令执行。"
: `已进入 ${modeName}。接下来直接输入自然语言即可继续这个项目的会话。`,
mode: requestedMode,
},
]);
return;
}
const turnId = requestedMode === "claude" ? makeId("claude-turn") : null;
const userMessage: ChatMessage = {
id: turnId ? `${turnId}-user` : makeId("user"),
role: "user",
content: routeMatch ? command : enteredCommand,
mode: requestedMode,
turnId: turnId ?? undefined,
};
const assistantMessageId = turnId ? `${turnId}-assistant` : makeId("terminal");
const assistantMessage: ChatMessage = {
id: assistantMessageId,
role: "assistant",
content: requestedMode === "codex"
? "正在连接 Codex…"
: requestedMode === "claude"
? "正在连接 Claude…"
: "正在连接 Mac 终端…",
mode: requestedMode,
output: requestedMode === "shell",
status: "running",
streaming: true,
turnId: turnId ?? undefined,
};
stickToBottomRef.current = true;
setShowScrollToBottom(false);
setDraft("");
updateModeMessages(projectId, requestedMode, (current) => [
...current,
userMessage,
assistantMessage,
]);
setIsStreaming(true);
setIsStopping(false);
setActiveActivity(requestedMode === "codex"
? "正在启动 Codex"
: requestedMode === "claude"
? "正在启动 Claude"
: "正在启动终端命令");
try {
const response = await fetch(
`/api/projects/${encodeURIComponent(projectId)}/runs`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
command,
mode: requestedMode,
permissionMode: requestedMode === "claude" ? claudePermissionMode : undefined,
turnId,
}),
},
);
const payload = await response.json() as ServerRun | { error?: string };
if (!response.ok || !("id" in payload)) {
throw new Error("error" in payload && payload.error ? payload.error : "无法启动命令");
}
if (startsClaudeFromAnotherMode) {
try {
const snapshot = await fetchClaudeConversation(projectId);
replaceClaudeMessages(projectId, snapshot.messages, snapshot.hasSession);
} catch {
// The new turn is already visible locally; normal SSE updates can continue.
}
}
updateRunMessage(projectId, assistantMessageId, payload);
activeRunRef.current = {
messageId: assistantMessageId,
mode: requestedMode,
projectId,
runId: payload.id,
};
watchRun(projectId, payload.id, assistantMessageId, requestedMode);
} catch (error) {
updateModeMessages(projectId, requestedMode, (current) =>
current.map((message) =>
message.id === assistantMessageId
? {
...message,
content: error instanceof Error ? error.message : "无法连接终端服务",
status: "failed",
streaming: false,
}
: message,
),
);
setIsStreaming(false);
setIsStopping(false);
setActiveActivity("");
} finally {
if (startsClaudeFromAnotherMode) pendingClaudeStartRef.current = false;
}
};
const handleSubmit = (event?: FormEvent) => {
event?.preventDefault();
void runCommand(draft);
};
const handleComposerKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
if (chatMode === "claude" && event.key === "Tab" && event.shiftKey) {
event.preventDefault();
cycleClaudePermissionMode();
return;
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
handleSubmit();
}
};
const stopRun = async () => {
const active = activeRunRef.current;
if (!active || isStopping) return;
setIsStopping(true);
try {
const response = await fetch(
`/api/projects/${encodeURIComponent(active.projectId)}/runs/${encodeURIComponent(active.runId)}/interrupt`,
{ method: "POST" },
);
if (!response.ok) throw new Error("停止命令失败");
} catch (error) {
setIsStopping(false);
updateModeMessages(active.projectId, active.mode, (current) => [
...current,
{
id: makeId("stop-error"),
role: "assistant",
content: error instanceof Error ? error.message : "停止命令失败",
},
]);
}
};
const exitAgentSession = async () => {
if (isStreaming) {
await stopRun();
return;
}
if (chatMode === "shell" || isResettingSession || isHydratingClaude) return;
const exitingMode = chatMode;
const agentName = exitingMode === "codex" ? "Codex" : "Claude";
const confirmed = window.confirm(
exitingMode === "claude"
? "结束并清空当前项目的 Claude 主会话记录?下次发送消息时会创建全新会话。"
: "结束当前项目的 Codex 会话?下次发送消息时会创建全新会话。",
);
if (!confirmed) return;
const projectId = selectedProject.id;
setIsResettingSession(true);
try {
const response = await fetch(
`/api/projects/${encodeURIComponent(projectId)}/agents/${exitingMode}/session`,
{ method: "DELETE" },
);
if (!response.ok) {
const payload = await response.json().catch(() => ({})) as { error?: string };
throw new Error(payload.error || `无法退出 ${agentName} 会话`);
}
setMessagesByProject((current) => {
const projectMessages = current[projectId] ?? createInitialMessagesByMode();
return {
...current,
[projectId]: {
...projectMessages,
[exitingMode]: initialMessagesForMode(exitingMode),
shell: [
...projectMessages.shell,
{
id: makeId("session-exited"),
role: "assistant",
mode: "shell",
content: `${agentName} 会话已退出。下次进入 ${agentName} 时会从新会话开始。`,
},
],
},
};
});
changeChatMode("shell");
} catch (error) {
updateModeMessages(projectId, exitingMode, (current) => [
...current,
{
id: makeId("session-exit-error"),
role: "assistant",
mode: exitingMode,
content: error instanceof Error ? error.message : `无法退出 ${agentName} 会话`,
},
]);
} finally {
setIsResettingSession(false);
}
};
const sendTerminalKey = async (key: string) => {
setTerminalKeyError("");
try {
const response = await fetch(
`/api/projects/${encodeURIComponent(selectedProject.id)}/terminal/keys`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key }),
},
);
if (!response.ok) throw new Error("快捷键发送失败");
} catch (error) {
setTerminalKeyError(error instanceof Error ? error.message : "快捷键发送失败");
}
};
const renderProjectList = () => (
<section className="project-panel" aria-label="项目列表">
<header className="brand-header">
<div>
<p className="eyebrow">REMOTE SHELL</p>
<h1>你的工作台</h1>
</div>
<button className="profile-button" type="button" aria-label="工作台设置">
RS
</button>
</header>
{showIosInstallHint && (
<aside className="ios-install-card" aria-label="安装到 iPhone 主屏幕">
<span className="ios-install-icon" aria-hidden="true" />
<div>
<strong>{installHintNeedsHttps ? "先切换到 HTTPS 地址" : "添加到 iPhone 主屏幕"}</strong>
<p>
{installHintNeedsHttps
? "请先用 Tailscale HTTPS 地址打开,再从 Safari 分享菜单添加。"
: "在 Safari 点分享,选择“添加到主屏幕”,并开启“作为网页 App 打开”。"}
</p>
</div>
<button
aria-label="关闭安装提示"
onClick={() => {
window.localStorage.setItem(IOS_INSTALL_HINT_KEY, "1");
setShowIosInstallHint(false);
}}
type="button"
>
×
</button>
</aside>
)}
<div className="machine-overview">
<div className="machine-topline">
<span className="machine-icon" aria-hidden="true">⌘</span>
<span className="online-label"><i /> {isLoadingProjects ? "正在读取项目" : `${projects.length} 个项目可选`}</span>
</div>
<strong>用消息调用终端</strong>
<p>从 Mac 选择项目后,Codex、Claude 和终端都会在对应目录中工作。</p>
<div className="machine-meta">
<span>{selectedProject.machine} · 本机服务</span>
<span>{projectRootLabel}</span>
</div>