useSettingService.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /**
  2. * useSettingService —— 设置服务 hooks
  3. */
  4. import { useState, useEffect, useCallback } from "react";
  5. import { APP_RUNTIME_PREFERENCES_CHANGED_BROADCAST_CHANNEL, type AppSettings } from "@zcode/shared";
  6. import type { ISettingService } from "@zcode/services";
  7. import { useServices } from "./useServices.js";
  8. import { usePlatform } from "./usePlatform.js";
  9. type SettingsSnapshot = {
  10. settings: AppSettings | null;
  11. loading: boolean;
  12. error: unknown | null;
  13. };
  14. export type { SettingsSnapshot };
  15. interface SettingsStore {
  16. snapshot: SettingsSnapshot;
  17. inflightRefresh: Promise<void> | null;
  18. listeners: Set<(snapshot: SettingsSnapshot) => void>;
  19. }
  20. // SettingsPage 外层与模型配置页内层可能分别绑定 Local/Remote Service;
  21. // 共享一份 snapshot/inflight 会让一次 Environment 的刷新结果覆盖另一份事实源。
  22. // 按 Service 实例隔离 store,保持同一 Environment 内的组件共享,同时阻断跨 Environment 串写。
  23. const stores = new WeakMap<object, SettingsStore>();
  24. const unavailableSettingsStore: SettingsStore = {
  25. snapshot: {
  26. settings: null,
  27. loading: true,
  28. error: null,
  29. },
  30. inflightRefresh: null,
  31. listeners: new Set(),
  32. };
  33. export function getSettingsStore(settingService: ISettingService | undefined): SettingsStore {
  34. if (
  35. !settingService ||
  36. (typeof settingService !== "object" && typeof settingService !== "function")
  37. ) {
  38. return unavailableSettingsStore;
  39. }
  40. const existing = stores.get(settingService);
  41. if (existing) {
  42. return existing;
  43. }
  44. const created: SettingsStore = {
  45. snapshot: {
  46. settings: null,
  47. loading: true,
  48. error: null,
  49. },
  50. inflightRefresh: null,
  51. listeners: new Set(),
  52. };
  53. stores.set(settingService, created);
  54. return created;
  55. }
  56. function emitSettingsSnapshot(store: SettingsStore) {
  57. for (const listener of store.listeners) {
  58. listener(store.snapshot);
  59. }
  60. }
  61. export async function refreshSettingsStore(settingService: ISettingService | undefined) {
  62. const store = getSettingsStore(settingService);
  63. if (!settingService) {
  64. return;
  65. }
  66. if (store.inflightRefresh) {
  67. return store.inflightRefresh;
  68. }
  69. store.snapshot = {
  70. ...store.snapshot,
  71. loading: true,
  72. error: null,
  73. };
  74. emitSettingsSnapshot(store);
  75. store.inflightRefresh = (async () => {
  76. try {
  77. const result = await settingService.get();
  78. store.snapshot = {
  79. settings: result,
  80. loading: false,
  81. error: null,
  82. };
  83. emitSettingsSnapshot(store);
  84. } catch (error) {
  85. store.snapshot = {
  86. // 设置读取失败时保留旧快照,避免一次刷新错误把已可用的设置页降级为空状态。
  87. settings: store.snapshot.settings,
  88. loading: false,
  89. error,
  90. };
  91. emitSettingsSnapshot(store);
  92. }
  93. })().finally(() => {
  94. store.inflightRefresh = null;
  95. });
  96. return store.inflightRefresh;
  97. }
  98. /** 获取和更新应用设置 */
  99. export function useSettings() {
  100. const { botsService, broadcastService, settingService, zcodeAgentService } = useServices();
  101. const platform = usePlatform();
  102. const settingsStore = getSettingsStore(settingService);
  103. const [snapshot, setSnapshot] = useState<SettingsSnapshot>(settingsStore.snapshot);
  104. const refresh = useCallback(async () => {
  105. await refreshSettingsStore(settingService);
  106. }, [settingService]);
  107. useEffect(() => {
  108. const listener = (nextSnapshot: SettingsSnapshot) => {
  109. setSnapshot(nextSnapshot);
  110. };
  111. settingsStore.listeners.add(listener);
  112. setSnapshot(settingsStore.snapshot);
  113. void refresh();
  114. return () => {
  115. settingsStore.listeners.delete(listener);
  116. };
  117. }, [refresh, settingsStore]);
  118. useEffect(() => {
  119. return (
  120. platform.onSettingsChanged?.(() => {
  121. void refresh();
  122. }) ?? (() => {})
  123. );
  124. }, [platform, refresh]);
  125. const update = useCallback(
  126. async (patch: Partial<AppSettings>) => {
  127. await settingService.update(patch);
  128. platform.syncAppSettings?.(patch);
  129. await refresh();
  130. if (
  131. typeof patch.askUserQuestionAutoResolutionEnabled === "boolean" ||
  132. typeof patch.modelIoFullRetentionEnabled === "boolean"
  133. ) {
  134. const preferences = {
  135. askUserQuestionAutoResolutionEnabled:
  136. patch.askUserQuestionAutoResolutionEnabled ??
  137. settingsStore.snapshot.settings?.askUserQuestionAutoResolutionEnabled !== false,
  138. modelIoFullRetentionEnabled:
  139. patch.modelIoFullRetentionEnabled ??
  140. settingsStore.snapshot.settings?.modelIoFullRetentionEnabled === true,
  141. };
  142. const syncResults = await Promise.allSettled([
  143. zcodeAgentService.syncAppRuntimePreferences(preferences),
  144. botsService.syncAppRuntimePreferences(preferences),
  145. ]);
  146. const syncError = syncResults.find(
  147. (result): result is PromiseRejectedResult => result.status === "rejected",
  148. )?.reason;
  149. await broadcastService.send({
  150. channel: APP_RUNTIME_PREFERENCES_CHANGED_BROADCAST_CHANNEL,
  151. payload: preferences,
  152. });
  153. if (syncError) {
  154. throw syncError;
  155. }
  156. }
  157. },
  158. [
  159. botsService,
  160. broadcastService,
  161. settingService,
  162. settingsStore,
  163. zcodeAgentService,
  164. platform,
  165. refresh,
  166. ],
  167. );
  168. return {
  169. settings: snapshot.settings,
  170. loading: snapshot.loading,
  171. error: snapshot.error,
  172. update,
  173. refresh,
  174. };
  175. }
  176. /** 最近项目列表的便捷 hook */
  177. export function useRecentProjects() {
  178. const { settings, loading, update } = useSettings();
  179. return {
  180. recentProjects: settings?.recentProjects ?? [],
  181. loading,
  182. addProject: async (path: string) => {
  183. const current = settings?.recentProjects ?? [];
  184. const updated = [path, ...current.filter((p) => p !== path)].slice(0, 10);
  185. await update({ recentProjects: updated });
  186. },
  187. };
  188. }