main.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /* eslint-disable max-lines -- Web 入口集中编排启动、路由与 workspace shell wiring,与 Root.tsx 同样先保持入口收口,避免跨层状态拆散。 */
  2. import { createRoot } from "react-dom/client";
  3. import {
  4. AppErrorBoundary,
  5. Root,
  6. ZCodeIntlProvider,
  7. generateMobileDeviceFingerprint,
  8. playTaskNotificationSound,
  9. setStreamClientId,
  10. type Theme,
  11. } from "@zcode/ui";
  12. import "@zcode/ui/styles.css";
  13. import { connectViaWebSocket } from "@zcode/client";
  14. import { WebCallbackPage } from "./auth/WebCallbackPage.js";
  15. import { createWebAuthService } from "./auth/webAuthService.js";
  16. import { WEB_ZAI_OAUTH_CONFIG, resolveWebAuthDevReturnTo } from "./auth/webZaiOAuthConfig.js";
  17. import { parseOAuthState, resolveSafeAppReturnTo } from "./auth/oauthStateCodec.js";
  18. import { resolveWebCommunityUrl, resolveWebHelpConfig } from "./communityUrl.js";
  19. import {
  20. ConversationShareLandingLoader,
  21. ConversationShareLandingStatus,
  22. } from "./share/ConversationShareLandingPage.js";
  23. import {
  24. ConversationSharePreviewClient,
  25. resolveConversationShareRouteLocale,
  26. } from "./share/conversationSharePreviewClient.js";
  27. import {
  28. isConversationSharePath,
  29. resolveConversationShareCodeFromPath,
  30. } from "./share/conversationShareRoute.js";
  31. import type { IPlatformService, RemoteTarget, ServerRemoteInfo } from "@zcode/shared";
  32. import { WEB_DEFAULT_THEME, resolveWebInitialTheme } from "./webThemeSeed.js";
  33. function resolveWebThemePreference(defaultTheme: Theme = WEB_DEFAULT_THEME): Theme {
  34. const saved = localStorage.getItem("zcode-theme");
  35. return resolveWebInitialTheme({ storedTheme: saved, defaultTheme });
  36. }
  37. // 初始化主题:默认 Zai dark,后续由 useTheme hook 接管
  38. // system 模式下需要查询系统偏好;非 system 模式直接用存储值
  39. {
  40. // 分享页没有本地主题配置时使用浅色,已有配置仍然沿用;其他 Web 页面继续默认深色。
  41. const saved = resolveWebThemePreference(
  42. isConversationSharePath(window.location.pathname) ? "zai-light" : undefined,
  43. );
  44. const resolved =
  45. saved === "system"
  46. ? window.matchMedia("(prefers-color-scheme: dark)").matches
  47. ? "dark"
  48. : "light"
  49. : saved === "dark" || saved === "zai-dark"
  50. ? "dark"
  51. : "light";
  52. const appliedTheme =
  53. saved === "system"
  54. ? resolved === "dark"
  55. ? "zai-dark"
  56. : "zai-light"
  57. : saved === "dark"
  58. ? "zai-dark"
  59. : saved === "light"
  60. ? "zai-light"
  61. : saved;
  62. document.documentElement.classList.toggle("dark", resolved === "dark");
  63. document.documentElement.classList.toggle("theme-zai-light", appliedTheme === "zai-light");
  64. document.documentElement.classList.toggle("theme-zai-dark", appliedTheme === "zai-dark");
  65. }
  66. async function resolveFeedbackUrl(): Promise<string | undefined> {
  67. return (await resolveWebHelpConfig()).feedback_url;
  68. }
  69. const root = createRoot(document.getElementById("root")!);
  70. const webAuthService = createWebAuthService();
  71. // 初始化 Web 端流式 clientId,确保所有 hook 在首次渲染前就使用稳定 ID
  72. {
  73. setStreamClientId(generateMobileDeviceFingerprint());
  74. }
  75. interface WebBootstrapResult {
  76. wsUrl: string;
  77. initialWorkspaceAbsPath?: string;
  78. initialWorkspaceIdentity?: string;
  79. initialTaskId?: string;
  80. restoreSession?: boolean;
  81. allowOpenWorkspace?: boolean;
  82. }
  83. function isWebOAuthCallback(params: URLSearchParams): boolean {
  84. return (
  85. ["/cn/share/callback", "/share/callback"].includes(window.location.pathname) &&
  86. params.has("state") &&
  87. (params.has("code") || params.has("error"))
  88. );
  89. }
  90. function renderWebAuthCallbackPage(): void {
  91. document.title = "ZCode - Sign In";
  92. const callbackState = parseOAuthState(
  93. new URLSearchParams(window.location.search).get("state") ?? "",
  94. );
  95. const safeRetryTarget = resolveSafeAppReturnTo(callbackState?.app_return_to);
  96. root.render(
  97. <WebCallbackPage
  98. authService={webAuthService}
  99. onSuccess={({ appReturnTo }) => {
  100. window.location.replace(appReturnTo ?? "/");
  101. }}
  102. onRetry={() => {
  103. window.location.replace(safeRetryTarget ?? "/");
  104. }}
  105. />,
  106. );
  107. }
  108. async function renderConversationSharePage(): Promise<void> {
  109. // 页面语言跟随路径前缀:/cn/share 中文,裸 /share 英文。
  110. const routeLocale = resolveConversationShareRouteLocale(window.location.pathname);
  111. // index.html 固定 lang="en";不同步会让中文分享页对无障碍与浏览器翻译都报错语言。
  112. document.documentElement.lang = routeLocale;
  113. // 分享页必须设置 title:否则浏览器标签只显示 index.html 的通用标题。
  114. // 会话标题要等 preview 加载完,先给一个语言正确的兜底。
  115. document.title = routeLocale === "zh-CN" ? "ZCode 会话分享" : "ZCode Conversation Share";
  116. const shareCode = resolveConversationShareCodeFromPath(window.location.pathname);
  117. if (!shareCode) {
  118. root.render(
  119. <ConversationShareLandingStatus
  120. state={{ kind: "error", error: "invalid_contract" }}
  121. locale={routeLocale}
  122. />,
  123. );
  124. return;
  125. }
  126. const endpointOrigin =
  127. import.meta.env.VITE_ZCODE_BASE_URL?.trim().replace(/\/+$/u, "") || window.location.origin;
  128. const mockMode =
  129. import.meta.env.DEV && import.meta.env.VITE_CONVERSATION_SHARE_PREVIEW_MOCK === "true";
  130. // Share 加载失败不能只有通用 network 文案:需要区分 mock、endpoint 配置或跨域 fetch。
  131. // 这里只记录运行时路由与 endpoint,不记录完整 pathname,避免把 share code 写入日志。
  132. console.info("[conversation-share-web]", "preview_runtime_initialized", {
  133. browserOrigin: window.location.origin,
  134. routeKind: "canonical",
  135. endpointOrigin,
  136. transport: mockMode ? "mock" : "fetch",
  137. });
  138. const client = mockMode
  139. ? new (
  140. await import("./share/mockConversationSharePreviewClient.js")
  141. ).MockConversationSharePreviewClient()
  142. : new ConversationSharePreviewClient({ baseUrl: `${endpointOrigin}/api/v1` });
  143. const getMockToken = () =>
  144. mockMode && window.sessionStorage.getItem("zcode:share:mock-auth") === "owner"
  145. ? "mock-owner-token"
  146. : null;
  147. const onLogout = () => {
  148. if (mockMode) {
  149. window.sessionStorage.removeItem("zcode:share:mock-auth");
  150. window.location.reload();
  151. return;
  152. }
  153. void webAuthService.logout();
  154. };
  155. root.render(
  156. <ConversationShareLandingLoader
  157. shareCode={shareCode}
  158. client={client}
  159. getAccessToken={() => getMockToken() ?? webAuthService.getZCodeJwtToken()}
  160. onLogin={(provider) => {
  161. if (mockMode) {
  162. window.sessionStorage.setItem("zcode:share:mock-auth", "owner");
  163. window.location.reload();
  164. return;
  165. }
  166. webAuthService.startLogin({
  167. provider,
  168. appReturnTo: window.location.href,
  169. redirectUri: WEB_ZAI_OAUTH_CONFIG.shareRedirectUri,
  170. devReturnTo: resolveWebAuthDevReturnTo(WEB_ZAI_OAUTH_CONFIG),
  171. });
  172. }}
  173. onLogout={onLogout}
  174. locale={routeLocale}
  175. theme={resolveWebThemePreference("zai-light")}
  176. />,
  177. );
  178. }
  179. function createWebPlatform(): IPlatformService {
  180. return {
  181. canSelectFilePath: false,
  182. // Web 端无法打开系统目录选择框
  183. selectDirectory: () => Promise.resolve(null),
  184. // Web 端无法打开系统文件选择框
  185. selectFile: () => Promise.resolve(null),
  186. selectFiles: () => Promise.resolve([]),
  187. getPathForFile: () => null,
  188. createTempTextAttachment: () =>
  189. Promise.reject(new Error("Temporary text attachments require a desktop host")),
  190. onRemoteConnectionLog: () => () => {},
  191. onRemoteSessionClosed: () => () => {},
  192. // Web 端无多窗口管理
  193. activateOrSetWorkspace: () => Promise.resolve({ activated: false }),
  194. // TODO(web-remote-workspace): 普通 Web 模式先只保证 server 本地工作区可用。
  195. // 远程 WebSocket 只暴露部分 service,与 Root/RemoteServiceAccess 需要的完整
  196. // accessor 不匹配,直接打开 ?remote=<id> 会在项目向导或首屏卡住。
  197. connectRemote(options: RemoteTarget) {
  198. return Promise.resolve({
  199. success: false,
  200. error: `Remote connect is not supported in Web mode yet: ${options.kind}`,
  201. });
  202. },
  203. cancelPendingRemoteConnection: (_requestId?: string) => Promise.resolve(),
  204. disposeRemoteSession: () => Promise.resolve(),
  205. isDockerAvailable: () => Promise.resolve(false),
  206. listWSLDistros: () => Promise.resolve([]),
  207. listDockerContainers: () => Promise.resolve([]),
  208. listSSHConfigAliases: () => Promise.resolve([]),
  209. loadMcpFromUserDirectory: () => Promise.resolve({ servers: [] }),
  210. saveMcpToUserDirectory: () =>
  211. Promise.resolve({
  212. success: false,
  213. error: "MCP native directory management requires a desktop attachment",
  214. }),
  215. migrateLegacyCommonMcp: () =>
  216. Promise.resolve({
  217. servers: {},
  218. totalCount: 0,
  219. importedCount: 0,
  220. skippedCount: 0,
  221. }),
  222. openExternal: (url) => {
  223. window.open(url, "_blank", "noopener,noreferrer");
  224. },
  225. openFeedback: async () => {
  226. const feedbackUrl = await resolveFeedbackUrl();
  227. if (!feedbackUrl) {
  228. return;
  229. }
  230. window.open(feedbackUrl, "_blank", "noopener,noreferrer");
  231. },
  232. openCommunity: async () => {
  233. const locale = document.documentElement.lang === "en-US" ? "en-US" : "zh-CN";
  234. const communityUrl = await resolveWebCommunityUrl(locale);
  235. if (!communityUrl) {
  236. return;
  237. }
  238. window.open(communityUrl, "_blank", "noopener,noreferrer");
  239. },
  240. canOpenCommunity: async (locale) => {
  241. const communityUrl = await resolveWebCommunityUrl(locale);
  242. return typeof communityUrl === "string" && communityUrl.length > 0;
  243. },
  244. openInFileManager: () =>
  245. Promise.resolve({ success: false, error: "Not supported in web mode" }),
  246. openExternalFile: () => Promise.resolve({ success: false, error: "Not supported in web mode" }),
  247. registerOAuthState: (_payload) => {},
  248. onOAuthCallback: () => () => {},
  249. onPaymentCallback: () => () => {},
  250. onShareImport: () => () => {},
  251. notifyRendererReady: () => {},
  252. reportTelemetryEvent: async () => {},
  253. reportArmsCustomEvent: () => Promise.resolve(),
  254. showTaskNotification: (payload) => {
  255. if (document.hasFocus()) {
  256. return;
  257. }
  258. if (
  259. typeof window.Notification === "undefined" ||
  260. window.Notification.permission !== "granted"
  261. ) {
  262. return;
  263. }
  264. try {
  265. new window.Notification(payload.title, {
  266. body: payload.body,
  267. silent: true,
  268. });
  269. void playTaskNotificationSound();
  270. } catch {
  271. // 浏览器通知不可用时静默忽略,避免打断主流程
  272. }
  273. },
  274. // Web 端不需要跨窗口 tab 管理
  275. syncWindowTabs: () => {},
  276. // Web 端没有宿主层 Dock / 任务栏徽标,保持空实现以兼容统一平台接口
  277. syncWindowUnreadCount: () => {},
  278. syncActiveTaskSession: () => {},
  279. onFocusTab: () => () => {},
  280. onNewTab: () => () => {},
  281. onCloseActiveContextRequest: () => () => {},
  282. onOpenBrowserUrl: () => () => {},
  283. onNewTask: () => () => {},
  284. onOpenWorkspace: () => () => {},
  285. onWindowFullscreenChanged: () => () => {},
  286. onTaskNotificationClick: () => () => {},
  287. exportLogs: () => Promise.resolve({ success: false, error: "Not supported in web mode" }),
  288. captureWindowScreenshot: () => Promise.resolve(null),
  289. importChromeBrowserData: (_options) =>
  290. Promise.resolve({
  291. success: false,
  292. cookies: { imported: 0, skipped: 0, failed: 0 },
  293. localStorage: {
  294. originsImported: 0,
  295. entriesImported: 0,
  296. originsSkipped: 0,
  297. originsFailed: 0,
  298. },
  299. error: "chrome_import_not_supported" as const,
  300. }),
  301. clearEmbeddedBrowserData: () =>
  302. Promise.resolve({ success: false, error: "Not supported in web mode" }),
  303. // IPlatformService 新增更新提示能力后,Web fallback 没有同步补齐空实现,
  304. // 根级 typecheck 会直接失败,连与桌面端无关的改动都没法完成校验。
  305. // Web 端当前没有桌面更新器,先显式 no-op,保持接口完整且不改变现有行为。
  306. onUpdateReady: () => () => {},
  307. onUpdateCheckResult: () => () => {},
  308. onUpdateStateChanged: () => () => {},
  309. getUpdateState: () => Promise.resolve({ kind: "idle", enabled: true }),
  310. downloadUpdate: () => Promise.resolve(),
  311. cancelUpdateDownload: () => Promise.resolve(),
  312. getDesktopSessionActivity: () => Promise.resolve({ runningAgentSessionCount: 0 }),
  313. getDesktopZoomLevel: () => Promise.resolve({ zoomLevel: 0 }),
  314. onDesktopZoomLevelChanged: () => () => {},
  315. onPostUpdateReleaseNotes: () => () => {},
  316. acknowledgePostUpdateReleaseNotes: () => Promise.resolve(),
  317. skipUpdateVersion: () => Promise.resolve(),
  318. quitAndInstallUpdate: () => Promise.resolve(),
  319. getInstalledEditors: () => Promise.resolve([]),
  320. openInEditor: () => Promise.resolve({ success: false, error: "Not supported in web mode" }),
  321. executeDesktopCommand: () => Promise.resolve(),
  322. setApplicationLocale: (_locale) => Promise.resolve(),
  323. setTitleBarTheme: () => Promise.resolve(),
  324. getDeviceId: () => {
  325. const nav = globalThis.navigator as Navigator & { platform?: string };
  326. const platform = nav?.platform ?? "";
  327. const screenWidth = globalThis.screen?.width;
  328. const screenHeight = globalThis.screen?.height;
  329. const colorDepth = globalThis.screen?.colorDepth;
  330. const parts = [
  331. platform,
  332. screenWidth !== undefined ? String(screenWidth) : "",
  333. screenHeight !== undefined ? String(screenHeight) : "",
  334. colorDepth !== undefined ? String(colorDepth) : "",
  335. ];
  336. return parts.filter(Boolean).join("|");
  337. },
  338. };
  339. }
  340. function resolveDefaultWsOrigin(): string {
  341. return `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.host}`;
  342. }
  343. async function resolveWebBootstrap(): Promise<WebBootstrapResult> {
  344. const params = new URLSearchParams(window.location.search);
  345. const remoteId = params.get("remote");
  346. const wsUrl = remoteId
  347. ? `${resolveDefaultWsOrigin()}/ws/remote/${remoteId}`
  348. : `${resolveDefaultWsOrigin()}/ws`;
  349. if (remoteId) {
  350. return { wsUrl };
  351. }
  352. try {
  353. const response = await fetch("/api/server-info", {
  354. cache: "no-store",
  355. });
  356. if (!response.ok) {
  357. return { wsUrl };
  358. }
  359. const serverInfo = (await response.json()) as Partial<ServerRemoteInfo>;
  360. const workspace = Array.isArray(serverInfo.workspaces) ? serverInfo.workspaces[0] : undefined;
  361. return {
  362. wsUrl,
  363. ...(workspace?.path ? { initialWorkspaceAbsPath: workspace.path } : {}),
  364. ...(workspace?.workspaceIdentity
  365. ? { initialWorkspaceIdentity: workspace.workspaceIdentity }
  366. : {}),
  367. };
  368. } catch {
  369. return { wsUrl };
  370. }
  371. }
  372. function WebBootstrapErrorScreen({ message }: { message: string }) {
  373. return (
  374. <div className="h-dvh min-h-dvh w-screen bg-background text-foreground">
  375. <div className="mx-auto flex h-full w-full max-w-lg items-center px-4">
  376. <section className="w-full rounded-xl border border-card-border bg-card p-5">
  377. <div className="flex items-center gap-3">
  378. <span className="size-2 rounded-full bg-destructive" />
  379. <h1 className="text-ui-xs font-medium">
  380. {/^zh\b/i.test(navigator.language) ? "Web 启动失败" : "Web bootstrap failed"}
  381. </h1>
  382. </div>
  383. <p className="mt-2 break-all text-ui-xs/relaxed text-foreground-subtle">{message}</p>
  384. <button
  385. type="button"
  386. className="mt-4 rounded-lg border border-border bg-surface px-3 py-2 text-ui-xs text-foreground-subtle hover:bg-surface-hover"
  387. onClick={() => {
  388. window.location.reload();
  389. }}
  390. >
  391. {/^zh\b/i.test(navigator.language) ? "重试" : "Retry"}
  392. </button>
  393. </section>
  394. </div>
  395. </div>
  396. );
  397. }
  398. function renderWebBootstrapError(error: unknown): void {
  399. document.title = "ZCode - Web";
  400. root.render(
  401. <WebBootstrapErrorScreen message={error instanceof Error ? error.message : String(error)} />,
  402. );
  403. }
  404. async function bootstrapWebApp() {
  405. const params = new URLSearchParams(window.location.search);
  406. if (isWebOAuthCallback(params)) {
  407. renderWebAuthCallbackPage();
  408. return;
  409. }
  410. if (isConversationSharePath(window.location.pathname)) {
  411. await renderConversationSharePage();
  412. return;
  413. }
  414. let bootstrap: WebBootstrapResult;
  415. try {
  416. bootstrap = await resolveWebBootstrap();
  417. } catch (error) {
  418. renderWebBootstrapError(error);
  419. return;
  420. }
  421. try {
  422. const services = await connectViaWebSocket(bootstrap.wsUrl, {
  423. onClose: () => {},
  424. });
  425. const platform = createWebPlatform();
  426. document.title = "ZCode - Web + Server";
  427. root.render(
  428. <AppErrorBoundary>
  429. <ZCodeIntlProvider
  430. settingService={services.settingService}
  431. broadcastService={services.broadcastService}
  432. >
  433. <Root
  434. services={services}
  435. platform={platform}
  436. initialWorkspaceAbsPath={bootstrap.initialWorkspaceAbsPath}
  437. initialWorkspaceIdentity={bootstrap.initialWorkspaceIdentity}
  438. initialTaskId={bootstrap.initialTaskId}
  439. restoreSession={bootstrap.restoreSession}
  440. allowOpenWorkspace={bootstrap.allowOpenWorkspace}
  441. preferDirectoryBrowser
  442. supportsEmbeddedBrowser={false}
  443. allowRemoteWorkspace={false}
  444. />
  445. </ZCodeIntlProvider>
  446. </AppErrorBoundary>,
  447. );
  448. } catch (error) {
  449. renderWebBootstrapError(error);
  450. }
  451. }
  452. void bootstrapWebApp();