useRootPlatformEffects.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /* oxlint-disable eslint(max-lines) -- 平台事件和分享导入共用同一生命周期。 */
  2. import { useEffect, useRef, useState } from "react";
  3. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  4. import type { IPlatformService } from "@zcode/shared";
  5. import { isWorkspaceTab, type TabStoreState, type WindowTabState } from "@/store/tabStore.js";
  6. import { useTabStore } from "@/store/TabStoreProvider.js";
  7. import { logger } from "@/logger.js";
  8. import { seedImportedSessionDraft } from "@/v4/composer/newTaskDraft.js";
  9. import { dismissToast, toast, updateToast } from "@/components/ui/toast.js";
  10. import { matchesPrimaryShortcut } from "@/lib/keyboardShortcuts.js";
  11. import { isShortcutRecordingActive } from "@/shortcuts/bindings.js";
  12. import { isRendererReloadNavigation } from "@/lib/rendererNavigation.js";
  13. import {
  14. buildConnectedRemoteWorkspaceSessionTargets,
  15. buildWebRemoteControlWorkspaceTargets,
  16. shouldPublishCompleteWorkspaceSnapshot,
  17. } from "@/root/rootPlatformWorkspaceSync.js";
  18. import { useOptionalBaseWorkspaceServices } from "@/hooks/useWorkspaceServices.js";
  19. import {
  20. createShareImportIntent,
  21. isShareImportIntentSame,
  22. resolveShareImportFailurePresentation,
  23. type ShareImportIntent,
  24. } from "@/root/shareImportIntent.js";
  25. export function useRootPlatformEffects({
  26. initialWorkspaceAbsPath,
  27. initialWorkspaceIdentity,
  28. initialWorkspacePurpose,
  29. initialTaskId,
  30. canBootstrapInitialWorkspace = true,
  31. addTab,
  32. setIsBootstrappingInitialWorkspace,
  33. platform,
  34. activateTabByPath,
  35. startDraftInWorkspace,
  36. startNewTaskFromActiveWorkspace,
  37. openWorkspace,
  38. openWorkspacePath,
  39. setWorkspaceActionError,
  40. allowOpenWorkspace = true,
  41. isDesktop,
  42. locale,
  43. tabs,
  44. activeWorkspacePath,
  45. activeWorkspaceIdentity,
  46. reconnectingRemoteWorkspaceKeys = [],
  47. remoteWorkspaceErrorByWorkspaceKey = {},
  48. totalUnreadTaskCount,
  49. webRemoteControlFeatureEnabled = false,
  50. webRemoteControlSessionActive = false,
  51. hasCompletedFullTabRestore = true,
  52. intl,
  53. isRestoringOAuthSession,
  54. }: {
  55. initialWorkspaceAbsPath?: string;
  56. initialWorkspaceIdentity?: string;
  57. initialWorkspacePurpose?: import("@zcode/shared").WorkspacePurpose;
  58. initialTaskId?: string;
  59. canBootstrapInitialWorkspace?: boolean;
  60. addTab: (
  61. workspacePath: string,
  62. options?: {
  63. workspaceIdentity?: string;
  64. workspacePurpose?: import("@zcode/shared").WorkspacePurpose;
  65. },
  66. ) => void;
  67. setIsBootstrappingInitialWorkspace: (value: boolean) => void;
  68. platform: IPlatformService;
  69. activateTabByPath: (workspacePath: string, options?: { workspaceIdentity?: string }) => boolean;
  70. startDraftInWorkspace: (workspacePath: string, workspaceIdentity?: string) => void;
  71. startNewTaskFromActiveWorkspace: (source: string) => void;
  72. openWorkspace: () => void;
  73. openWorkspacePath: (workspacePath: string) => void;
  74. setWorkspaceActionError: (message: string | null) => void;
  75. allowOpenWorkspace?: boolean;
  76. isDesktop?: boolean;
  77. locale: ReturnType<typeof import("@/i18n/IntlProvider.js").useZCodeIntl>["locale"];
  78. tabs: WindowTabState[];
  79. activeWorkspacePath?: string | null;
  80. activeWorkspaceIdentity?: string | null;
  81. reconnectingRemoteWorkspaceKeys?: string[];
  82. remoteWorkspaceErrorByWorkspaceKey?: Record<string, string>;
  83. totalUnreadTaskCount: number;
  84. webRemoteControlFeatureEnabled?: boolean;
  85. webRemoteControlSessionActive?: boolean;
  86. hasCompletedFullTabRestore?: boolean;
  87. intl: ReturnType<typeof import("@/i18n/IntlProvider.js").useZCodeIntl>["intl"];
  88. isRestoringOAuthSession: boolean;
  89. }) {
  90. const didBootstrapInitialWorkspaceRef = useRef(false);
  91. const baseServices = useOptionalBaseWorkspaceServices();
  92. const pendingShareImportRef = useRef<ShareImportIntent | null>(null);
  93. const [shareImportRevision, setShareImportRevision] = useState(0);
  94. const activeShareImportRef = useRef<ShareImportIntent | null>(null);
  95. const importOperationRef = useRef<string | null>(null);
  96. const lastImportProgressToastRef = useRef<{ phase: string; at: number } | null>(null);
  97. const importToastIdRef = useRef<number | null>(null);
  98. useEffect(() => {
  99. // 启动时必须先判断 OAuth 本地会话,再恢复历史/初始 workspace。
  100. // 如果这里抢先 addTab,未登录用户会先看到主界面,之后才被登录页覆盖。
  101. if (!canBootstrapInitialWorkspace || didBootstrapInitialWorkspaceRef.current) {
  102. return;
  103. }
  104. didBootstrapInitialWorkspaceRef.current = true;
  105. if (initialWorkspaceAbsPath) {
  106. addTab(
  107. initialWorkspaceAbsPath,
  108. initialWorkspaceIdentity || initialWorkspacePurpose
  109. ? {
  110. ...(initialWorkspaceIdentity ? { workspaceIdentity: initialWorkspaceIdentity } : {}),
  111. ...(initialWorkspacePurpose ? { workspacePurpose: initialWorkspacePurpose } : {}),
  112. }
  113. : undefined,
  114. );
  115. if (initialTaskId) {
  116. useZCodeSessionStore
  117. .getState()
  118. .setActiveTaskId(initialWorkspaceAbsPath, initialTaskId, initialWorkspaceIdentity);
  119. } else if (!isRendererReloadNavigation()) {
  120. // main 注入 initial workspace 只表达工作区入口;没有显式 taskId
  121. // 的 app 冷启动必须进入草稿,不能让 renderer-local last-session/group/pane
  122. // 抢回历史会话;同一 renderer reload 则保留当前 session 续流资格。
  123. startDraftInWorkspace(initialWorkspaceAbsPath, initialWorkspaceIdentity);
  124. }
  125. }
  126. // Dock 最近项目会通过 initialWorkspaceAbsPath 直达工作区。
  127. // 如果这里仍然等首屏先按默认空 tab 渲染一次,窗口会先闪出打开工作区中间页,
  128. // 再异步补上目标 workspace,视觉上像是“打开错页再跳转”。
  129. // 这里把初始工作区注入也纳入启动保护期,等首个 tab 准备好后再渲染正式内容。
  130. setIsBootstrappingInitialWorkspace(false);
  131. }, [
  132. addTab,
  133. canBootstrapInitialWorkspace,
  134. initialTaskId,
  135. initialWorkspaceAbsPath,
  136. initialWorkspaceIdentity,
  137. initialWorkspacePurpose,
  138. setIsBootstrappingInitialWorkspace,
  139. startDraftInWorkspace,
  140. ]);
  141. useEffect(() => {
  142. const disposeFocusTab = platform.onFocusTab((path: string) => {
  143. logger.info("[Root] onFocusTab:", path);
  144. if (activateTabByPath(path)) {
  145. // 系统 workspace focus 是 workspace-only 导航;任务通知另有
  146. // 显式 taskId 路径,不能在这里隐式恢复这个 workspace 上次选中的 session。
  147. startDraftInWorkspace(path);
  148. }
  149. });
  150. const disposeNewTab = platform.onNewTab(() => {
  151. logger.info("[Root] onNewTab");
  152. setWorkspaceActionError(null);
  153. // 新标签过去会打开工作区中间页,导致启动/快捷键都可能进入中间页。
  154. // 现在新标签语义收敛为“打开工作区”动作,由 Root 决定目录选择或默认 workspace 兜底。
  155. openWorkspace();
  156. });
  157. const disposeNewTask = platform.onNewTask(() => {
  158. startNewTaskFromActiveWorkspace("onNewTask");
  159. });
  160. const disposeOpenWorkspace = platform.onOpenWorkspace(() => {
  161. logger.info("[Root] onOpenWorkspace");
  162. openWorkspace();
  163. });
  164. const disposeOpenWorkspacePath = platform.onOpenWorkspacePath
  165. ? platform.onOpenWorkspacePath((path: string) => {
  166. if (!allowOpenWorkspace) {
  167. logger.info("[Root] 当前模式不支持通过 deep link 打开文件夹,已忽略请求");
  168. return;
  169. }
  170. logger.info("[Root] onOpenWorkspacePath:", path);
  171. // 系统服务 deep link 对应输入框上方 Open folder 语义。
  172. // 这里复用 handleSelectProject,而不是把路径作为聊天附件,才能保留 tab 去重、
  173. // 跨窗口激活和 recentProjects 更新这些手动打开文件夹的既有行为。
  174. openWorkspacePath(path);
  175. })
  176. : () => {};
  177. const disposeShareImport = platform.onShareImport
  178. ? platform.onShareImport((payload) => {
  179. const current = pendingShareImportRef.current ?? activeShareImportRef.current;
  180. if (current && isShareImportIntentSame(current, payload)) {
  181. logger.info("[Root] 忽略重复的 share import deep link", {
  182. shareCodeLength: payload.shareCode.length,
  183. });
  184. return;
  185. }
  186. const activeTab = tabs.find(
  187. (tab): tab is Extract<WindowTabState, { kind: "workspace" }> =>
  188. tab.kind === "workspace" &&
  189. tab.workspacePath === activeWorkspacePath &&
  190. (activeWorkspaceIdentity
  191. ? tab.workspaceIdentity === activeWorkspaceIdentity
  192. : !tab.workspaceIdentity),
  193. );
  194. pendingShareImportRef.current = createShareImportIntent(payload.shareCode, undefined, {
  195. ...(activeWorkspacePath ? { targetWorkspacePath: activeWorkspacePath } : {}),
  196. ...(activeWorkspaceIdentity
  197. ? { targetWorkspaceIdentity: activeWorkspaceIdentity }
  198. : {}),
  199. targetWorkspaceKind:
  200. activeTab?.remoteSessionId || activeTab?.remoteTarget ? "remote" : "local",
  201. });
  202. setShareImportRevision((revision) => revision + 1);
  203. logger.info("[Root] 收到 share import deep link", {
  204. shareCodeLength: payload.shareCode.length,
  205. });
  206. })
  207. : () => {};
  208. const disposeNotificationClick = platform.onTaskNotificationClick((taskId: string) => {
  209. logger.info("[Root] onTaskNotificationClick:", taskId);
  210. // 遍历所有 workspace 找到 taskId 所属的 workspace,然后激活对应 tab 并切换任务
  211. const workspaces = useZCodeSessionStore.getState().workspaces;
  212. for (const [workspacePath, workspaceState] of Object.entries(workspaces)) {
  213. const taskMeta = workspaceState.taskListCache?.find((task) => task.taskId === taskId);
  214. const hasTask = workspaceState.activeTaskId === taskId || Boolean(taskMeta);
  215. if (hasTask) {
  216. const targetWorkspacePath = taskMeta?.workspacePath ?? workspacePath;
  217. const targetWorkspaceIdentity = taskMeta?.workspaceIdentity;
  218. // 通知点击会从全局 workspace store 反查 task。
  219. // 远端任务必须用 task meta 自带的 workspaceIdentity 激活和选中,否则会落到 path-only 桶。
  220. activateTabByPath(
  221. targetWorkspacePath,
  222. targetWorkspaceIdentity ? { workspaceIdentity: targetWorkspaceIdentity } : undefined,
  223. );
  224. useZCodeSessionStore
  225. .getState()
  226. .setActiveTaskId(targetWorkspacePath, taskId, targetWorkspaceIdentity);
  227. return;
  228. }
  229. }
  230. logger.warn("[Root] onTaskNotificationClick: task not found in any workspace:", taskId);
  231. });
  232. const disposeUpdateCheckResult = platform.onUpdateCheckResult
  233. ? platform.onUpdateCheckResult((payload) => {
  234. logger.info("[Root] onUpdateCheckResult:", payload.kind);
  235. switch (payload.kind) {
  236. case "up-to-date":
  237. toast(
  238. intl.formatMessage(
  239. { id: "update.toast.upToDate" },
  240. { version: payload.currentVersion },
  241. ),
  242. );
  243. return;
  244. case "downloading":
  245. toast(
  246. intl.formatMessage(
  247. { id: "update.toast.downloading" },
  248. { version: payload.version },
  249. ),
  250. );
  251. return;
  252. case "available":
  253. toast(
  254. intl.formatMessage({ id: "update.toast.available" }, { version: payload.version }),
  255. );
  256. return;
  257. case "already-downloading":
  258. toast(
  259. intl.formatMessage(
  260. { id: "update.toast.alreadyDownloading" },
  261. { progress: payload.progress },
  262. ),
  263. );
  264. return;
  265. case "ready":
  266. toast(intl.formatMessage({ id: "update.toast.ready" }, { version: payload.version }));
  267. return;
  268. case "dev-skipped":
  269. toast(intl.formatMessage({ id: "update.toast.devSkipped" }));
  270. return;
  271. case "error":
  272. toast(intl.formatMessage({ id: "update.toast.error" }, { error: payload.message }));
  273. return;
  274. }
  275. })
  276. : () => {};
  277. return () => {
  278. disposeFocusTab();
  279. disposeNewTab();
  280. disposeNewTask();
  281. disposeOpenWorkspace();
  282. disposeOpenWorkspacePath();
  283. disposeShareImport();
  284. disposeNotificationClick();
  285. disposeUpdateCheckResult();
  286. };
  287. }, [activeWorkspaceIdentity, activeWorkspacePath, platform, tabs]);
  288. useEffect(() => {
  289. const pending = pendingShareImportRef.current;
  290. if (!pending || !baseServices || activeShareImportRef.current || importOperationRef.current) {
  291. return;
  292. }
  293. if (isRestoringOAuthSession) {
  294. return;
  295. }
  296. // 分享页 Deep Link 不应在 Root 层按登录态分叉;未登录与已登录都
  297. // 走同一份 continuation/import 流程。公开可导入分享由接口自身决定是否可用。
  298. pending.status = "importing";
  299. pendingShareImportRef.current = null;
  300. activeShareImportRef.current = pending;
  301. if (importToastIdRef.current !== null) {
  302. dismissToast(importToastIdRef.current);
  303. importToastIdRef.current = null;
  304. }
  305. const operationId = `share-import-${globalThis.crypto?.randomUUID?.() ?? Date.now()}`;
  306. importOperationRef.current = operationId;
  307. lastImportProgressToastRef.current = null;
  308. const progressEvent =
  309. baseServices.conversationShareService.onDynamicImportProgress(operationId);
  310. const disposeProgress = progressEvent((progress) => {
  311. const now = Date.now();
  312. const last = lastImportProgressToastRef.current;
  313. if (
  314. last &&
  315. last.phase === progress.phase &&
  316. now - last.at < 800 &&
  317. progress.phase !== "complete"
  318. ) {
  319. return;
  320. }
  321. // complete 只表示导入事务已经收口;成功结果会在下方统一替换进度提示,避免短暂闪过
  322. // “导入完成”后又紧接着出现“已从分享导入”的两条成功 Toast。
  323. if (progress.phase === "complete") {
  324. return;
  325. }
  326. lastImportProgressToastRef.current = { phase: progress.phase, at: now };
  327. const label =
  328. progress.phase === "downloading"
  329. ? intl.formatMessage(
  330. { id: "conversationShare.import.downloading" },
  331. { completed: progress.completedArtifacts, total: progress.totalArtifacts },
  332. )
  333. : progress.phase === "installing"
  334. ? intl.formatMessage({ id: "conversationShare.import.installing" })
  335. : intl.formatMessage({ id: "conversationShare.import.committing" });
  336. if (importToastIdRef.current === null) {
  337. importToastIdRef.current = toast(label, { durationMs: 0, variant: "info" });
  338. } else {
  339. updateToast(importToastIdRef.current, {
  340. message: label,
  341. durationMs: 0,
  342. variant: "info",
  343. actionLabel: undefined,
  344. onAction: undefined,
  345. dismissible: false,
  346. });
  347. }
  348. });
  349. void baseServices.conversationShareService
  350. .importShare(
  351. {
  352. shareCode: pending.shareCode,
  353. clientRequestId: pending.clientRequestId,
  354. ...(pending.targetWorkspacePath
  355. ? { targetWorkspacePath: pending.targetWorkspacePath }
  356. : {}),
  357. ...(pending.targetWorkspaceIdentity
  358. ? { targetWorkspaceIdentity: pending.targetWorkspaceIdentity }
  359. : {}),
  360. ...(pending.targetWorkspaceKind
  361. ? { targetWorkspaceKind: pending.targetWorkspaceKind }
  362. : {}),
  363. locale,
  364. },
  365. operationId,
  366. )
  367. .then((result) => {
  368. pending.status = "complete";
  369. // 先准备实际落地工作区的独立草稿,再激活;复用导入不覆盖会话选择。
  370. seedImportedSessionDraft(result);
  371. const activated = activateTabByPath(
  372. result.workspacePath,
  373. result.workspaceIdentity ? { workspaceIdentity: result.workspaceIdentity } : undefined,
  374. );
  375. if (!activated) {
  376. addTab(result.workspacePath, {
  377. ...(result.workspaceIdentity ? { workspaceIdentity: result.workspaceIdentity } : {}),
  378. workspacePurpose: "conversation",
  379. });
  380. }
  381. const sessionStore = useZCodeSessionStore.getState();
  382. sessionStore.setActiveTaskId(
  383. result.workspacePath,
  384. result.sessionId,
  385. result.workspaceIdentity,
  386. );
  387. // 导入可能复用当前已打开的 session;仅 setActiveTaskId 不会产生可观察的切换。
  388. // 每次成功都显式发出一次定位请求,目标 pane 准备好分享内容后再消费。
  389. sessionStore.requestTimelineBottom(
  390. result.workspacePath,
  391. result.sessionId,
  392. result.workspaceIdentity,
  393. );
  394. // 回退过的导入会落在与用户当前所看不同的 workspace,必须讲清落在哪、为何回退,
  395. // 否则用户只会看到会话“跑到别处去了”。
  396. const resultMessage = result.fallbackReason
  397. ? intl.formatMessage(
  398. {
  399. id:
  400. result.fallbackReason === "remote_workspace"
  401. ? "conversationShare.import.fallbackRemoteWorkspace"
  402. : "conversationShare.import.fallbackDefaultWorkspace",
  403. },
  404. { title: result.title, workspacePath: result.workspacePath },
  405. )
  406. : intl.formatMessage({ id: "conversationShare.import.source" }, { title: result.title });
  407. const resultToastOptions = {
  408. durationMs: result.fallbackReason ? 7000 : 3000,
  409. variant: result.fallbackReason ? ("info" as const) : ("default" as const),
  410. actionLabel: undefined,
  411. onAction: undefined,
  412. dismissible: false,
  413. };
  414. if (importToastIdRef.current === null) {
  415. importToastIdRef.current = toast(resultMessage, resultToastOptions);
  416. } else {
  417. updateToast(importToastIdRef.current, { message: resultMessage, ...resultToastOptions });
  418. }
  419. })
  420. .catch((error) => {
  421. pending.status = "failed";
  422. const record = error && typeof error === "object" ? (error as Record<string, unknown>) : {};
  423. const kind = typeof record.kind === "string" ? record.kind : "unknown";
  424. const reasonCode = typeof record.reasonCode === "string" ? record.reasonCode : undefined;
  425. const firstIssue = Array.isArray(record.issues) ? record.issues[0] : undefined;
  426. const firstIssueRecord =
  427. firstIssue && typeof firstIssue === "object" && !Array.isArray(firstIssue)
  428. ? (firstIssue as Record<string, unknown>)
  429. : undefined;
  430. const artifactDisplayName =
  431. typeof firstIssueRecord?.artifactDisplayName === "string"
  432. ? firstIssueRecord.artifactDisplayName
  433. : undefined;
  434. logger.warn("[Root] share import failed", {
  435. operationId,
  436. clientRequestId: pending.clientRequestId,
  437. kind,
  438. ...(reasonCode ? { reasonCode } : {}),
  439. ...(typeof record.issueCount === "number" ? { issueCount: record.issueCount } : {}),
  440. });
  441. const failurePresentation = resolveShareImportFailurePresentation(kind);
  442. const retryImport = () => {
  443. pending.status = "received";
  444. pendingShareImportRef.current = pending;
  445. setShareImportRevision((revision) => revision + 1);
  446. };
  447. const detailedMessageId =
  448. artifactDisplayName && kind === "invalid_contract"
  449. ? "conversationShare.import.integrityFailedWithArtifact"
  450. : artifactDisplayName && kind === "network"
  451. ? "conversationShare.import.failedWithArtifact"
  452. : failurePresentation.messageId;
  453. const failureMessage = intl.formatMessage(
  454. { id: detailedMessageId },
  455. artifactDisplayName ? { artifactDisplayName } : undefined,
  456. );
  457. const failureToastOptions = {
  458. durationMs: 7000,
  459. ...(failurePresentation.retryable
  460. ? {
  461. actionLabel: intl.formatMessage({ id: "conversationShare.import.retry" }),
  462. onAction: retryImport,
  463. }
  464. : {}),
  465. dismissible: true,
  466. variant: "default" as const,
  467. };
  468. if (importToastIdRef.current === null) {
  469. importToastIdRef.current = toast(failureMessage, failureToastOptions);
  470. } else {
  471. updateToast(importToastIdRef.current, {
  472. message: failureMessage,
  473. ...failureToastOptions,
  474. });
  475. }
  476. })
  477. .finally(() => {
  478. disposeProgress.dispose();
  479. activeShareImportRef.current = null;
  480. importOperationRef.current = null;
  481. setShareImportRevision((revision) => revision + 1);
  482. });
  483. }, [
  484. activateTabByPath,
  485. addTab,
  486. baseServices,
  487. intl,
  488. isRestoringOAuthSession,
  489. locale,
  490. shareImportRevision,
  491. ]);
  492. useEffect(() => {
  493. if (!isDesktop || !shouldPublishCompleteWorkspaceSnapshot(hasCompletedFullTabRestore)) {
  494. return;
  495. }
  496. const paths = tabs
  497. .filter(isWorkspaceTab)
  498. // 启动期远程 workspace 现在会先以“断开占位 tab”恢复,
  499. // 这些 tab 没有 remoteSessionId,但本质仍是远程会话,不能当成本地路径同步给主进程窗口列表。
  500. // 这里改成按完整远程身份字段过滤,避免把远程路径误同步到本地窗口标签。
  501. .filter((tab) => !tab.remoteSessionId && !tab.workspaceIdentity && !tab.remoteTarget)
  502. .map((tab) => tab.workspacePath);
  503. platform.syncWindowTabs(paths);
  504. }, [hasCompletedFullTabRestore, isDesktop, platform, tabs]);
  505. useEffect(() => {
  506. if (
  507. !isDesktop ||
  508. !shouldPublishCompleteWorkspaceSnapshot(hasCompletedFullTabRestore) ||
  509. !platform.syncWebRemoteControlWorkspaces
  510. ) {
  511. return;
  512. }
  513. const connectedRemoteWorkspaces = buildConnectedRemoteWorkspaceSessionTargets({ tabs });
  514. if (connectedRemoteWorkspaces.length > 0) {
  515. // Bugfix: Bot 远端连接状态查询依赖 main 进程里 remoteSessionId -> workspaceIdentity 的绑定。
  516. // 之前这条绑定复用 Web 远控 workspace 同步,Web 远控未开启时不会执行,导致 UI 已连接但 Bot 误判未连接。
  517. platform.syncWebRemoteControlWorkspaces(connectedRemoteWorkspaces);
  518. }
  519. if (!webRemoteControlFeatureEnabled || !webRemoteControlSessionActive) {
  520. return;
  521. }
  522. const workspaces = buildWebRemoteControlWorkspaceTargets({
  523. tabs,
  524. reconnectingRemoteWorkspaceKeys,
  525. remoteWorkspaceErrorByWorkspaceKey,
  526. });
  527. platform.syncWebRemoteControlWorkspaces(workspaces);
  528. }, [
  529. hasCompletedFullTabRestore,
  530. isDesktop,
  531. platform,
  532. reconnectingRemoteWorkspaceKeys,
  533. remoteWorkspaceErrorByWorkspaceKey,
  534. tabs,
  535. webRemoteControlFeatureEnabled,
  536. webRemoteControlSessionActive,
  537. ]);
  538. useEffect(() => {
  539. if (isDesktop) {
  540. return;
  541. }
  542. function handleWindowKeydown(event: KeyboardEvent) {
  543. // 录制态键盘归录制器独占。本监听先于录制监听注册(同 capture 阶段),
  544. // 不短路的话录制期按 Cmd/Ctrl+N、O 预览会真实触发新建任务/打开工作区。
  545. if (isShortcutRecordingActive()) {
  546. return;
  547. }
  548. const isNewTaskShortcut = matchesPrimaryShortcut(event, "n");
  549. const isOpenWorkspaceShortcut = matchesPrimaryShortcut(event, "o");
  550. if (!isNewTaskShortcut && !isOpenWorkspaceShortcut) {
  551. return;
  552. }
  553. // Web 端没有宿主菜单,补一层 best-effort 键盘监听,按平台主修饰键落到同一套根级动作。
  554. // 耦合说明:这里固定使用默认键位(Ctrl/Cmd+N、+O),与「menu 通道命令在 Web 端不可配置」
  555. // (设置页置灰)配套——若未来放开 Web 端 menu 通道改键,
  556. // 此处必须改为读快捷键生效表,否则用户改键后 Web 行为会分裂。
  557. event.preventDefault();
  558. if (isOpenWorkspaceShortcut) {
  559. openWorkspace();
  560. return;
  561. }
  562. startNewTaskFromActiveWorkspace("web CmdOrCtrl+N");
  563. }
  564. window.addEventListener("keydown", handleWindowKeydown, true);
  565. return () => {
  566. window.removeEventListener("keydown", handleWindowKeydown, true);
  567. };
  568. }, [isDesktop, openWorkspace, startNewTaskFromActiveWorkspace]);
  569. useEffect(() => {
  570. if (!isDesktop) {
  571. return;
  572. }
  573. let disposed = false;
  574. // 原生菜单文案之前在 main 进程里写死,renderer 切换 locale 只会更新 React 标题栏菜单。
  575. // 结果就是桌面端会同时出现两套语言,Help 里的反馈/导出日志也无法跟随当前语言切换。
  576. // 这里把当前 locale 主动同步给 main,让原生菜单和标题栏菜单都从同一份语言状态重建。
  577. platform.setApplicationLocale(locale).catch((error) => {
  578. if (disposed) {
  579. return;
  580. }
  581. logger.error("[Root] 同步应用菜单语言失败", { locale, error });
  582. });
  583. return () => {
  584. disposed = true;
  585. };
  586. }, [isDesktop, locale, platform]);
  587. useEffect(() => {
  588. // Dock badge 一期只统计“后台完成后还没点开”的 task 数。
  589. // 失败态红点和 permission tag 仍留在各自 UI 语义里,避免把平台徽标混成泛化告警数。
  590. platform.syncWindowUnreadCount(totalUnreadTaskCount);
  591. }, [platform, totalUnreadTaskCount]);
  592. const activeTabId = useTabStore((state: TabStoreState) => state.activeTabId);
  593. const activeTabCandidate = useTabStore((state: TabStoreState) =>
  594. state.tabs.find((tab: WindowTabState) => tab.id === state.activeTabId),
  595. );
  596. const activeTab =
  597. activeTabCandidate && isWorkspaceTab(activeTabCandidate) ? activeTabCandidate : undefined;
  598. const lastSyncedSessionIdRef = useRef<string | null | undefined>(undefined);
  599. useEffect(() => {
  600. if (!isDesktop) return;
  601. const workspacePath = activeTab?.workspacePath;
  602. const workspaceIdentity = activeTab?.workspaceIdentity;
  603. const syncActiveSession = (): void => {
  604. const nextSessionId = workspacePath
  605. ? (useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  606. .activeTaskId ?? null)
  607. : null;
  608. if (nextSessionId === lastSyncedSessionIdRef.current) return;
  609. lastSyncedSessionIdRef.current = nextSessionId;
  610. platform.syncActiveTaskSession(nextSessionId);
  611. };
  612. syncActiveSession();
  613. return useZCodeSessionStore.subscribe(syncActiveSession);
  614. }, [activeTab, activeTabId, isDesktop, platform]);
  615. }