WebRemoteControlMobileShell.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
  2. import { ArrowLeft, LoaderIcon } from "lucide-react";
  3. import {
  4. resolveWebRemoteControlWorkspaceKey,
  5. type WebRemoteControlMobileNavigationIntent,
  6. type WebRemoteControlWorkspaceListResult,
  7. } from "@zcode/shared";
  8. import { Button } from "@/components/ui/button.js";
  9. import {
  10. WebRemoteControlMobileTaskHome,
  11. persistWebRemoteControlMobileTaskHomePreferences,
  12. readWebRemoteControlMobileTaskHomePreferences,
  13. type WebRemoteControlMobileTaskHomePreferences,
  14. } from "@/WebRemoteControlMobileTaskHome.js";
  15. import { WebRemoteControlThemeMenu } from "@/WebRemoteControlThemeMenu.js";
  16. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  17. import { logger } from "@/logger.js";
  18. import type { WebRemoteControlTerminalTransportState } from "@/root/types.js";
  19. import type { WebRemoteControlWorkspaceSwitcherApi } from "@/root/types.js";
  20. import { useWebRemoteControlTerminalTransportState } from "@/webRemoteControlTerminalTransportState.js";
  21. type WebRemoteControlMobilePage = "home" | "chat";
  22. interface WebRemoteControlMobileHistoryState {
  23. zcodeMobilePage?: WebRemoteControlMobilePage;
  24. }
  25. export function isWebRemoteControlMobileChatHistoryState(
  26. state: unknown,
  27. ): state is WebRemoteControlMobileHistoryState {
  28. return (
  29. typeof state === "object" &&
  30. state !== null &&
  31. (state as WebRemoteControlMobileHistoryState).zcodeMobilePage === "chat"
  32. );
  33. }
  34. function pushWebRemoteControlMobileChatHistory() {
  35. if (typeof window === "undefined") {
  36. return;
  37. }
  38. if (isWebRemoteControlMobileChatHistoryState(window.history.state)) {
  39. return;
  40. }
  41. window.history.pushState({ zcodeMobilePage: "chat" }, "");
  42. }
  43. function resolveInitialWebRemoteControlMobilePage(
  44. initialNavigationIntent?: WebRemoteControlMobileNavigationIntent,
  45. ): WebRemoteControlMobilePage {
  46. if (initialNavigationIntent === "chat") {
  47. return "chat";
  48. }
  49. // Bugfix: 手机端在聊天页刷新时,React 内存状态会丢失,但浏览器会保留当前 history.state。
  50. // 这里复用点击进入聊天页时写入的 history state,避免刷新后只恢复 task 选中态却回到任务首页。
  51. if (
  52. typeof window !== "undefined" &&
  53. isWebRemoteControlMobileChatHistoryState(window.history.state)
  54. ) {
  55. return "chat";
  56. }
  57. return "home";
  58. }
  59. export function WebRemoteControlMobileShell({
  60. activeTaskId,
  61. activeWorkspaceIdentity,
  62. activeWorkspacePath,
  63. chatContent,
  64. chatOverlay,
  65. initialNavigationIntent,
  66. initialWorkspaceList,
  67. isSidePaneOpen = false,
  68. onCloseSidePane,
  69. onSelectTask,
  70. onStartDraftInWorkspace,
  71. renderChatHeader,
  72. sidePaneContent,
  73. switcher,
  74. webRemoteControlTerminalTransportState,
  75. }: {
  76. switcher: WebRemoteControlWorkspaceSwitcherApi;
  77. activeWorkspacePath: string;
  78. activeWorkspaceIdentity?: string;
  79. activeTaskId: string | null;
  80. initialNavigationIntent?: WebRemoteControlMobileNavigationIntent;
  81. initialWorkspaceList?: WebRemoteControlWorkspaceListResult;
  82. isSidePaneOpen?: boolean;
  83. onCloseSidePane?: () => void;
  84. onSelectTask: (
  85. targetWorkspacePath: string,
  86. taskId: string,
  87. targetWorkspaceIdentity?: string,
  88. ) => void;
  89. onStartDraftInWorkspace?: (
  90. targetWorkspacePath: string,
  91. targetWorkspaceIdentity?: string,
  92. ) => void;
  93. renderChatHeader: (options: { onBackHome: () => void }) => ReactNode;
  94. chatContent: ReactNode;
  95. chatOverlay?: ReactNode;
  96. sidePaneContent?: ReactNode;
  97. webRemoteControlTerminalTransportState?: WebRemoteControlTerminalTransportState;
  98. }) {
  99. const { intl } = useZCodeIntl();
  100. const [currentPage, setCurrentPage] = useState<WebRemoteControlMobilePage>(() =>
  101. resolveInitialWebRemoteControlMobilePage(initialNavigationIntent),
  102. );
  103. const [taskHomePreferences, setTaskHomePreferences] =
  104. useState<WebRemoteControlMobileTaskHomePreferences>(() =>
  105. readWebRemoteControlMobileTaskHomePreferences(),
  106. );
  107. const [homeRefreshKey, setHomeRefreshKey] = useState(0);
  108. const [switchingWorkspace, setSwitchingWorkspace] = useState(false);
  109. const terminalTransportState = useWebRemoteControlTerminalTransportState(
  110. webRemoteControlTerminalTransportState,
  111. );
  112. const syncedMobileViewStateRef = useRef<string | null>(null);
  113. const shouldInertChatSurface = Boolean(sidePaneContent) && isSidePaneOpen;
  114. const navigateToChat = useCallback(() => {
  115. setCurrentPage("chat");
  116. pushWebRemoteControlMobileChatHistory();
  117. }, []);
  118. const handleTaskHomePreferencesChange = useCallback(
  119. (preferences: WebRemoteControlMobileTaskHomePreferences) => {
  120. // Bugfix: 手机远控任务首页进入 task 后只是卸载组件,shell 内存 state 足够保留排序;
  121. // 但刷新页面会重建整个 React tree,之前的默认值会覆盖用户选择。
  122. // 这里在更新 shell state 的同时写入 localStorage,让刷新后也能恢复同一排序/分组偏好。
  123. persistWebRemoteControlMobileTaskHomePreferences(preferences);
  124. logger.debug("[WebRemoteControlMobileShell] 更新手机端任务首页偏好", preferences);
  125. setTaskHomePreferences(preferences);
  126. },
  127. [],
  128. );
  129. const navigateHome = useCallback(() => {
  130. setHomeRefreshKey((key) => key + 1);
  131. if (
  132. typeof window !== "undefined" &&
  133. isWebRemoteControlMobileChatHistoryState(window.history.state)
  134. ) {
  135. window.history.back();
  136. return;
  137. }
  138. setCurrentPage("home");
  139. }, []);
  140. useEffect(() => {
  141. if (initialNavigationIntent !== "chat") {
  142. return;
  143. }
  144. navigateToChat();
  145. }, [initialNavigationIntent, navigateToChat]);
  146. useEffect(() => {
  147. if (typeof window === "undefined") {
  148. return;
  149. }
  150. const handlePopState = (event: PopStateEvent) => {
  151. const nextPage = isWebRemoteControlMobileChatHistoryState(event.state) ? "chat" : "home";
  152. setCurrentPage(nextPage);
  153. if (nextPage === "home") {
  154. setHomeRefreshKey((key) => key + 1);
  155. }
  156. };
  157. window.addEventListener("popstate", handlePopState);
  158. return () => {
  159. window.removeEventListener("popstate", handlePopState);
  160. };
  161. }, []);
  162. useEffect(() => {
  163. if (!switcher.updateMobileViewState) {
  164. return;
  165. }
  166. const workspaceKey = resolveWebRemoteControlWorkspaceKey({
  167. workspacePath: activeWorkspacePath,
  168. workspaceIdentity: activeWorkspaceIdentity,
  169. });
  170. const dedupeKey = `${workspaceKey}:${activeTaskId ?? ""}`;
  171. if (syncedMobileViewStateRef.current === dedupeKey) {
  172. return;
  173. }
  174. syncedMobileViewStateRef.current = dedupeKey;
  175. // Bugfix: 手机端“新建任务/分叉”会自动切到新 task,但之前只有点任务列表项才会上报 mobileViewState。
  176. // 这样桌面端会继续认为手机还在旧 task,导致新 task 列表刷新滞后。
  177. // 这里在 activeTaskId 变化时立即同步,确保跨端选中态和任务列表收敛一致。
  178. void switcher
  179. .updateMobileViewState(workspaceKey, activeTaskId ?? undefined)
  180. .catch((error) => {
  181. const message = error instanceof Error ? error.message : String(error);
  182. logger.warn("[WebRemoteControlMobileShell] 同步 mobileViewState 失败", {
  183. error: message,
  184. workspaceKey,
  185. taskId: activeTaskId ?? null,
  186. });
  187. });
  188. }, [
  189. activeTaskId,
  190. activeWorkspaceIdentity,
  191. activeWorkspacePath,
  192. switcher,
  193. ]);
  194. // Bugfix: 移动端聊天/侧栏都是 flex 子树,默认 min-width:auto 会按长消息的
  195. // min-content 宽度撑开抽屉;窄屏随后从左侧裁掉正文。沿整条宽度链显式允许收缩,
  196. // 让 subagent 输出、进程面板和正文在抽屉内换行。
  197. return (
  198. <div className="relative flex h-full min-h-0 min-w-0 flex-col bg-background">
  199. {currentPage === "home" ? (
  200. <WebRemoteControlMobileTaskHome
  201. activeTaskId={activeTaskId}
  202. activeWorkspaceIdentity={activeWorkspaceIdentity}
  203. activeWorkspacePath={activeWorkspacePath}
  204. initialResult={initialWorkspaceList}
  205. onCrossWorkspaceSwitchingChange={setSwitchingWorkspace}
  206. onNavigateHome={navigateHome}
  207. onNavigateToChat={navigateToChat}
  208. preferences={taskHomePreferences}
  209. onPreferencesChange={handleTaskHomePreferencesChange}
  210. refreshKey={homeRefreshKey}
  211. onSelectTask={onSelectTask}
  212. onStartDraftInWorkspace={onStartDraftInWorkspace}
  213. switcher={switcher}
  214. />
  215. ) : (
  216. <section
  217. className="flex h-full min-h-0 min-w-0 flex-col bg-background text-foreground"
  218. data-mobile-page="chat"
  219. >
  220. <div className="flex h-11 shrink-0 items-center gap-2 border-b border-border bg-header px-2">
  221. <Button
  222. type="button"
  223. variant="ghost"
  224. size="icon-sm"
  225. aria-label={intl.formatMessage({
  226. id: "webRemoteControl.mobileShell.backHome",
  227. })}
  228. onClick={navigateHome}
  229. >
  230. <ArrowLeft className="size-4" />
  231. </Button>
  232. <span className="min-w-0 flex-1 truncate text-ui-base font-medium">
  233. {intl.formatMessage({ id: "webRemoteControl.mobileShell.chatTitle" })}
  234. </span>
  235. <WebRemoteControlThemeMenu />
  236. </div>
  237. {renderChatHeader({ onBackHome: navigateHome })}
  238. <div className="relative flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
  239. <main
  240. className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden"
  241. aria-hidden={shouldInertChatSurface ? true : undefined}
  242. data-mobile-chat-surface={
  243. shouldInertChatSurface ? "inert" : undefined
  244. }
  245. inert={shouldInertChatSurface ? true : undefined}
  246. >
  247. {/* Bugfix: 手机侧栏打开时底部 composer 会被抽屉覆盖。
  248. 如果聊天区仍留在交互树里,模型选择等控件会被遮挡但仍可被浏览器命中,
  249. 造成“按钮不可点”的误导。这里把被覆盖的聊天表面设为 inert,
  250. 让右侧抽屉成为唯一可交互区域。 */}
  251. {chatContent}
  252. </main>
  253. {sidePaneContent ? (
  254. <div
  255. className={[
  256. "absolute inset-0 z-30 transition-opacity duration-200 ease-out",
  257. isSidePaneOpen ? "opacity-100" : "pointer-events-none opacity-0",
  258. ].join(" ")}
  259. aria-hidden={!isSidePaneOpen}
  260. data-mobile-side-pane-overlay="true"
  261. >
  262. <button
  263. type="button"
  264. className="absolute inset-0 bg-background/60 backdrop-blur-[1px]"
  265. aria-label={intl.formatMessage({ id: "sidePane.collapse" })}
  266. onClick={onCloseSidePane}
  267. />
  268. <div
  269. className={[
  270. "absolute top-0 right-0 h-full w-[min(88vw,28rem)] max-w-full border-l border-border bg-background shadow-2xl transition-transform duration-200 ease-out",
  271. isSidePaneOpen ? "translate-x-0" : "translate-x-full",
  272. ].join(" ")}
  273. >
  274. {/* Bugfix: 手机远控之前把 side pane 作为底部纵向面板渲染,
  275. 会挤压聊天区且不像桌面右侧栏。这里改成右侧覆盖抽屉,
  276. 只覆盖手机聊天区,不改变桌面端分栏布局。 */}
  277. {sidePaneContent}
  278. </div>
  279. </div>
  280. ) : null}
  281. {chatOverlay ? (
  282. <div
  283. className="pointer-events-none absolute inset-0 z-40"
  284. data-mobile-chat-overlay="true"
  285. >
  286. {/* Bugfix: 查找框属于聊天视觉区域,但不能成为 inert 聊天表面的后代。
  287. 独立 overlay 保留抽屉隔离,同时让文件变更查找仍可聚焦、切换和关闭。 */}
  288. <div className="pointer-events-auto">{chatOverlay}</div>
  289. </div>
  290. ) : null}
  291. </div>
  292. </section>
  293. )}
  294. {switchingWorkspace ? (
  295. <div
  296. className="absolute inset-0 z-40 flex items-center justify-center bg-background/72 backdrop-blur-[1px]"
  297. aria-live="polite"
  298. aria-busy="true"
  299. >
  300. <div className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-ui-base text-foreground-subtle shadow-sm">
  301. <LoaderIcon className="size-4 animate-spin" />
  302. {intl.formatMessage({ id: "common.loading" })}
  303. </div>
  304. </div>
  305. ) : null}
  306. {terminalTransportState === "reconnecting" ? (
  307. <div
  308. className="pointer-events-none absolute top-3 left-1/2 z-50 flex -translate-x-1/2 justify-center px-3"
  309. aria-live="polite"
  310. aria-busy="true"
  311. data-web-remote-control-reconnect-notice="true"
  312. >
  313. <div className="flex max-w-[calc(100vw-1.5rem)] items-center gap-2 rounded-lg border border-border bg-toast px-3 py-2 text-ui-base text-foreground shadow-lg">
  314. <LoaderIcon className="size-4 shrink-0 animate-spin text-foreground-subtle" />
  315. <span className="min-w-0 whitespace-nowrap">
  316. {intl.formatMessage({ id: "webRemoteControl.mobileShell.reconnecting" })}
  317. </span>
  318. </div>
  319. </div>
  320. ) : null}
  321. </div>
  322. );
  323. }