useTaskListItemContextActions.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import type { ZCodeProvider } from "@zcode/shared";
  2. import { useCallback } from "react";
  3. import { usePlatform } from "@/hooks/usePlatform.js";
  4. import { useTaskNativeSessionLogFile } from "@/hooks/useTaskNativeSessionLogFile.js";
  5. import { useTaskSessionFilePath } from "@/hooks/useTaskSessionFilePath.js";
  6. import { useWorkspaceProviderConfigFile } from "@/hooks/useWorkspaceProviderConfigFile.js";
  7. import { useWorkspaceOpenInEditorTarget } from "@/hooks/useWorkspaceOpenInEditorTarget.js";
  8. import { readLastSelectedEditorId } from "@/lib/editorPreference.js";
  9. import { sortInstalledEditorsForOpenWith } from "@/lib/openWithEditors.js";
  10. import { logger } from "@/logger.js";
  11. interface TaskPathState {
  12. loading: boolean;
  13. path: string | null;
  14. exists: boolean;
  15. }
  16. interface TaskListItemContextActionsResult {
  17. taskSessionFile: TaskPathState;
  18. taskNativeSessionLogFile: TaskPathState;
  19. providerConfigFile: TaskPathState;
  20. fileManagerLabel: string;
  21. handleCopyText: (label: string, value: string | null) => Promise<void>;
  22. handleOpenTaskPathInFileManager: () => Promise<void>;
  23. handleOpenProviderConfig: () => Promise<void>;
  24. }
  25. export function resolveProviderConfigOpenTargetPath(
  26. path: string,
  27. exists: boolean,
  28. ): string {
  29. if (exists) {
  30. return path;
  31. }
  32. // Bugfix: provider 主配置文件首次还没落盘时,更多菜单之前会把“前往配置”完全禁用,
  33. // 用户既看不到承载配置的目录,也没法就地补齐文件。这里改成回退打开父目录,
  34. // 保留“前往配置”的导航语义,并避免把一个不存在的文件路径直接交给编辑器。
  35. const trimmedPath = path.replace(/[\\/]+$/, "");
  36. const lastSeparatorIndex = Math.max(
  37. trimmedPath.lastIndexOf("/"),
  38. trimmedPath.lastIndexOf("\\"),
  39. );
  40. if (lastSeparatorIndex < 0) {
  41. return path;
  42. }
  43. if (lastSeparatorIndex === 0) {
  44. return trimmedPath[0] ?? path;
  45. }
  46. const parentPath = trimmedPath.slice(0, lastSeparatorIndex);
  47. if (/^[A-Za-z]:$/.test(parentPath)) {
  48. return `${parentPath}\\`;
  49. }
  50. return parentPath || path;
  51. }
  52. export function useTaskListItemContextActions({
  53. workspacePath,
  54. remoteSessionId,
  55. workspaceIdentity,
  56. taskId,
  57. provider,
  58. intl,
  59. loadTaskPaths = true,
  60. loadProviderConfig = true,
  61. }: {
  62. workspacePath: string;
  63. remoteSessionId?: string;
  64. workspaceIdentity?: string;
  65. taskId: string;
  66. provider?: ZCodeProvider;
  67. intl: {
  68. formatMessage: (
  69. desc: { id: string },
  70. values?: Record<string, string>,
  71. ) => string;
  72. };
  73. loadTaskPaths?: boolean;
  74. loadProviderConfig?: boolean;
  75. }): TaskListItemContextActionsResult {
  76. const platform = usePlatform();
  77. const workspaceOpenTarget = useWorkspaceOpenInEditorTarget({
  78. workspacePath,
  79. workspaceIdentity,
  80. workspaceRemoteSessionId: remoteSessionId,
  81. });
  82. const taskProvider = provider ?? "glm";
  83. const taskSessionFile = useTaskSessionFilePath(workspacePath, taskId, workspaceIdentity, {
  84. // task session/log 路径只用于右键菜单项;菜单未打开时不要在列表重排中批量触发 RPC。
  85. enabled: loadTaskPaths,
  86. });
  87. const taskNativeSessionLogFile = useTaskNativeSessionLogFile(
  88. workspacePath,
  89. taskId,
  90. provider ?? null,
  91. workspaceIdentity,
  92. { enabled: loadTaskPaths },
  93. );
  94. const providerConfigFile = useWorkspaceProviderConfigFile(
  95. workspacePath,
  96. taskProvider,
  97. remoteSessionId,
  98. workspaceIdentity,
  99. {
  100. // Bugfix: 远程 workspace 里“前往配置”用于打开本机可编辑的 provider 配置入口。
  101. // 之前这里跟随 remote zcodeTaskService 取路径,会返回远端机器上的绝对路径(例如 /root/...),
  102. // 再交给本机平台层打开时就会定位到错误位置或直接失败。
  103. // 这里远程场景强制改走 base service,保证 UI 拿到的是本机可打开的配置路径。
  104. serviceScope: remoteSessionId ? "base" : "workspace",
  105. // Bugfix: 任务列表里每个 item 都会挂载右键菜单动作;如果挂载时就读取 provider 配置路径,
  106. // 远程 workspace 会按任务数量放大 base RPC 和日志。这里改成菜单真正打开时才加载。
  107. enabled: loadProviderConfig,
  108. },
  109. );
  110. const handleCopyText = useCallback(
  111. async (label: string, value: string | null) => {
  112. if (!value) {
  113. return;
  114. }
  115. try {
  116. await navigator.clipboard.writeText(value);
  117. logger.info(`[TaskListItem] ${label} 已复制: ${value}`);
  118. } catch (error) {
  119. logger.warn("[TaskListItem] 复制文本失败", {
  120. label,
  121. value,
  122. error: error instanceof Error ? error.message : String(error),
  123. });
  124. }
  125. },
  126. [],
  127. );
  128. const handleOpenTaskPathInFileManager = useCallback(async () => {
  129. const hasRemoteWorkspaceScope = Boolean(
  130. remoteSessionId ||
  131. workspaceIdentity?.trim() ||
  132. workspaceOpenTarget.isRemoteWorkspace,
  133. );
  134. if (hasRemoteWorkspaceScope) {
  135. if (workspaceOpenTarget.remoteTarget?.kind !== "wsl") {
  136. // 远程项目路径不是宿主机路径。无法精确解析为 WSL 时必须失败关闭,
  137. // 避免 SSH/Docker 的 Linux 路径误落到原生 Windows、macOS 或 Linux 文件管理器。
  138. logger.warn("[TaskListItem] 远程 workspace 不支持本机文件管理器", {
  139. taskId,
  140. path: workspacePath,
  141. remoteKind: workspaceOpenTarget.remoteTarget?.kind ?? "unresolved",
  142. });
  143. return;
  144. }
  145. const result = await platform.openInEditor("explorer", workspacePath, {
  146. pathKind: "directory",
  147. remoteTarget: workspaceOpenTarget.remoteTarget,
  148. workspaceIdentity,
  149. });
  150. if (!result.success) {
  151. logger.warn("[TaskListItem] 打开 WSL workspace 路径失败", {
  152. taskId,
  153. path: workspacePath,
  154. error: result.error ?? "unknown-error",
  155. });
  156. }
  157. return;
  158. }
  159. const isMac = isMacLike();
  160. const isWindows = isWindowsLike();
  161. if (isMac || isWindows) {
  162. const editorId = isMac ? "finder" : "explorer";
  163. const result = await platform.openInEditor(editorId, workspacePath);
  164. if (result.success) {
  165. return;
  166. }
  167. }
  168. const result = await platform.openInFileManager(workspacePath);
  169. if (!result.success) {
  170. // Header / task 菜单里的“Open in Finder”语义应该是打开项目目录。
  171. // 之前这里误绑到了 task session 文件路径,菜单可用性也跟着 task 快照文件走,
  172. // 一旦 session 文件还没解析出来,用户会看到 Finder 入口莫名不可用。
  173. // 这里统一改成始终打开 workspacePath,让行为和“Copy path=项目路径”保持一致。
  174. logger.warn("[TaskListItem] 打开 workspace 路径失败", {
  175. taskId,
  176. path: workspacePath,
  177. error: result.error ?? "unknown-error",
  178. });
  179. }
  180. }, [
  181. platform,
  182. remoteSessionId,
  183. taskId,
  184. workspaceIdentity,
  185. workspaceOpenTarget.isRemoteWorkspace,
  186. workspaceOpenTarget.remoteTarget,
  187. workspacePath,
  188. ]);
  189. const handleOpenProviderConfig = useCallback(async () => {
  190. if (!providerConfigFile.path) {
  191. return;
  192. }
  193. const openTargetPath = resolveProviderConfigOpenTargetPath(
  194. providerConfigFile.path,
  195. providerConfigFile.exists,
  196. );
  197. try {
  198. const preferredEditorId = readLastSelectedEditorId();
  199. const editors = await platform.getInstalledEditors();
  200. const sortedEditors = sortInstalledEditorsForOpenWith(editors);
  201. const preferredEditor =
  202. sortedEditors.find((editor) => editor.id === preferredEditorId) ??
  203. sortedEditors[0] ??
  204. null;
  205. // Bugfix: task 右键菜单位于侧边栏,拿不到 Header 里的 selectedEditor 本地状态。
  206. // 如果这里直接硬编码某个编辑器,Header 和侧边栏会对“Go to config”走出两条不同路径。
  207. // 这里改为读取持久化的 editor 偏好,和 Header editor 按钮共用同一份用户选择。
  208. if (preferredEditor) {
  209. const result = await platform.openInEditor(
  210. preferredEditor.id,
  211. openTargetPath,
  212. );
  213. if (result.success) {
  214. return;
  215. }
  216. }
  217. const result = await platform.openInFileManager(openTargetPath);
  218. if (!result.success) {
  219. logger.warn("[TaskListItem] 打开 provider 配置失败", {
  220. taskId,
  221. provider: taskProvider,
  222. path: providerConfigFile.path,
  223. openTargetPath,
  224. error: result.error ?? "unknown-error",
  225. });
  226. }
  227. } catch (error) {
  228. logger.warn("[TaskListItem] 打开 provider 配置失败", {
  229. taskId,
  230. provider: taskProvider,
  231. path: providerConfigFile.path,
  232. openTargetPath,
  233. error: error instanceof Error ? error.message : String(error),
  234. });
  235. }
  236. }, [
  237. platform,
  238. providerConfigFile.exists,
  239. providerConfigFile.path,
  240. taskId,
  241. taskProvider,
  242. ]);
  243. return {
  244. taskSessionFile,
  245. taskNativeSessionLogFile,
  246. providerConfigFile,
  247. fileManagerLabel: getFileManagerLabel(intl),
  248. handleCopyText,
  249. handleOpenTaskPathInFileManager,
  250. handleOpenProviderConfig,
  251. };
  252. }
  253. function isMacLike(): boolean {
  254. if (typeof navigator === "undefined") {
  255. return false;
  256. }
  257. return /mac/i.test(navigator.userAgent);
  258. }
  259. function isWindowsLike(): boolean {
  260. if (typeof navigator === "undefined") {
  261. return false;
  262. }
  263. return /windows/i.test(navigator.userAgent);
  264. }
  265. function getFileManagerLabel(intl: {
  266. formatMessage: (
  267. desc: { id: string },
  268. values?: Record<string, string>,
  269. ) => string;
  270. }) {
  271. if (isMacLike()) {
  272. return intl.formatMessage({ id: "appHeader.openInFinder" });
  273. }
  274. if (isWindowsLike()) {
  275. return intl.formatMessage({ id: "appHeader.openInFileExplorer" });
  276. }
  277. return intl.formatMessage({ id: "appHeader.openInFileManager" });
  278. }