conversation-session-store-snapshot-script.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import type { TaskStoreSnapshot } from "./conversation-session-store.js";
  2. type BrowserConfigOption = {
  3. category?: string;
  4. currentValue?: unknown;
  5. id?: string;
  6. options?: Array<{ value?: string }>;
  7. type?: string;
  8. };
  9. type BrowserTaskMeta = {
  10. model?: string | null;
  11. provider?: string | null;
  12. target?: {
  13. objective?: string | null;
  14. status?: string | null;
  15. targetID?: string | null;
  16. } | null;
  17. taskId: string;
  18. title?: string | null;
  19. };
  20. type BrowserTaskMessage = {
  21. id?: string;
  22. role?: string;
  23. streaming?: boolean;
  24. syntheticTimeline?: {
  25. goalIteration?: number;
  26. inputId?: string;
  27. operationId?: string;
  28. status?: string;
  29. targetId?: string;
  30. type?: string;
  31. verification?: {
  32. passed?: boolean | null;
  33. } | null;
  34. };
  35. type?: string;
  36. };
  37. type BrowserWorkspaceState = {
  38. activeTaskId?: string | null;
  39. configOptions?: BrowserConfigOption[] | null;
  40. optimisticTaskListByTaskId?: Record<string, BrowserTaskMeta>;
  41. queuedPromptsByTaskId?: Record<string, { content?: string }[]>;
  42. selectedProvider?: string | null;
  43. selectedSupplierKey?: string | null;
  44. taskConfigOptionsByTaskId?: Record<string, BrowserConfigOption[]>;
  45. taskListCache?: BrowserTaskMeta[] | null;
  46. taskMessagesByTaskId?: Record<string, BrowserTaskMessage[]>;
  47. taskRuntimeByTaskId?: Record<
  48. string,
  49. {
  50. activeInputId?: string | null;
  51. error?: string | null;
  52. status?: string | null;
  53. }
  54. >;
  55. taskStopRequestedByTaskId?: Record<string, boolean>;
  56. taskUiByTaskId?: Record<
  57. string,
  58. {
  59. error?: unknown;
  60. permissionRequest?: unknown | null;
  61. pendingPermissionRequests?: unknown[];
  62. }
  63. >;
  64. };
  65. export function readTaskStoreSnapshotInBrowser(
  66. taskIdArg: string,
  67. workspaceKeyArg?: string,
  68. ): {
  69. snapshot: TaskStoreSnapshot;
  70. } {
  71. const selectConfigSummary = (options: BrowserConfigOption[] | null | undefined) =>
  72. (options ?? [])
  73. .filter((option) =>
  74. ["model", "mode", "thought_level"].includes(option.category ?? option.id ?? ""),
  75. )
  76. .map((option) => ({
  77. category: option.category ?? null,
  78. currentValue:
  79. typeof option.currentValue === "string"
  80. ? option.currentValue
  81. : option.currentValue == null
  82. ? null
  83. : String(option.currentValue),
  84. id: option.id ?? null,
  85. optionValues: (option.options ?? []).map((candidate) => candidate.value ?? ""),
  86. type: option.type ?? null,
  87. }));
  88. const readLastSelectedModelStorage = () => {
  89. const result: Record<string, string | null> = {};
  90. try {
  91. for (const [key, value] of Object.entries(window.localStorage)) {
  92. if (key.startsWith("zcode-model-selection-recent-v1:")) {
  93. result[key] = value;
  94. }
  95. }
  96. } catch {
  97. result["<localStorage-error>"] = null;
  98. }
  99. return result;
  100. };
  101. const stringifyUiError = (error: unknown) => {
  102. if (!error) {
  103. return null;
  104. }
  105. if (typeof error === "string") {
  106. return error;
  107. }
  108. if (typeof error === "object") {
  109. const record = error as {
  110. code?: unknown;
  111. detail?: unknown;
  112. message?: unknown;
  113. traceId?: unknown;
  114. };
  115. return JSON.stringify({
  116. code: record.code ?? null,
  117. detail: record.detail ?? null,
  118. message: record.message ?? null,
  119. traceId: record.traceId ?? null,
  120. });
  121. }
  122. return String(error);
  123. };
  124. const bridge = (
  125. window as typeof window & {
  126. __zcodeSessionStoreE2E?: {
  127. getState?: () => {
  128. workspaces?: Record<string, BrowserWorkspaceState>;
  129. };
  130. };
  131. }
  132. ).__zcodeSessionStoreE2E;
  133. const bridgeMissing = typeof bridge?.getState !== "function";
  134. const state = bridge?.getState?.();
  135. const workspaces = state?.workspaces ?? {};
  136. const knownWorkspaceKeys = Object.keys(workspaces);
  137. const workspaceContainsTask = (workspace: BrowserWorkspaceState) => {
  138. const queue = workspace.queuedPromptsByTaskId?.[taskIdArg];
  139. const runtime = workspace.taskRuntimeByTaskId?.[taskIdArg];
  140. const messages = workspace.taskMessagesByTaskId?.[taskIdArg];
  141. const ui = workspace.taskUiByTaskId?.[taskIdArg];
  142. const optimisticMeta = workspace.optimisticTaskListByTaskId?.[taskIdArg];
  143. const cachedMeta = workspace.taskListCache?.some?.((task) => task.taskId === taskIdArg);
  144. const hasStopState = Object.prototype.hasOwnProperty.call(
  145. workspace.taskStopRequestedByTaskId ?? {},
  146. taskIdArg,
  147. );
  148. return Boolean(
  149. workspace.activeTaskId === taskIdArg ||
  150. queue ||
  151. runtime ||
  152. messages ||
  153. ui ||
  154. optimisticMeta ||
  155. cachedMeta ||
  156. hasStopState,
  157. );
  158. };
  159. const workspaceEntry = workspaceKeyArg
  160. ? workspaces[workspaceKeyArg] && workspaceContainsTask(workspaces[workspaceKeyArg])
  161. ? ([workspaceKeyArg, workspaces[workspaceKeyArg]] as const)
  162. : null
  163. : (Object.entries(workspaces).find(([, workspace]) => workspaceContainsTask(workspace)) ??
  164. null);
  165. if (bridgeMissing || !workspaceEntry) {
  166. return {
  167. snapshot: {
  168. activeInputId: null,
  169. activeTaskConfigOptions: [],
  170. activeTaskId: null,
  171. // 修复原因:CI 若误用 production 构建,renderer 不会暴露测试 store bridge。
  172. // 单独标记 bridge 缺失,避免把环境问题误判成 task store hydrate 慢。
  173. error: bridgeMissing ? "session-store-bridge-missing" : "task-not-found-in-store",
  174. hasPendingPermission: false,
  175. knownWorkspaceKeys,
  176. lastSelectedModelStorage: readLastSelectedModelStorage(),
  177. messageCount: 0,
  178. queueCount: 0,
  179. queuedTexts: [],
  180. runtimeStatus: null,
  181. selectedProvider: null,
  182. selectedSupplierKey: null,
  183. stopRequested: false,
  184. streamingAssistantCount: 0,
  185. taskConfigOptions: [],
  186. taskId: taskIdArg,
  187. taskMeta: null,
  188. timelineSummaries: [],
  189. uiError: null,
  190. workspaceConfigOptions: [],
  191. workspaceKey: null,
  192. },
  193. };
  194. }
  195. const [workspaceKey, workspace] = workspaceEntry;
  196. const activeTaskId = workspace.activeTaskId ?? null;
  197. const runtime = workspace.taskRuntimeByTaskId?.[taskIdArg];
  198. const queuedPrompts = workspace.queuedPromptsByTaskId?.[taskIdArg] ?? [];
  199. const messages = workspace.taskMessagesByTaskId?.[taskIdArg] ?? [];
  200. const taskUi = workspace.taskUiByTaskId?.[taskIdArg];
  201. const pendingPermissionCount = taskUi?.pendingPermissionRequests?.length ?? 0;
  202. const taskMeta =
  203. workspace.optimisticTaskListByTaskId?.[taskIdArg] ??
  204. workspace.taskListCache?.find?.((task) => task.taskId === taskIdArg) ??
  205. null;
  206. return {
  207. snapshot: {
  208. activeInputId: runtime?.activeInputId ?? null,
  209. activeTaskConfigOptions: selectConfigSummary(
  210. activeTaskId ? workspace.taskConfigOptionsByTaskId?.[activeTaskId] : null,
  211. ),
  212. activeTaskId,
  213. error: runtime?.error ?? null,
  214. hasPendingPermission: taskUi?.permissionRequest != null || pendingPermissionCount > 0,
  215. knownWorkspaceKeys,
  216. lastSelectedModelStorage: readLastSelectedModelStorage(),
  217. messageCount: messages.length,
  218. queueCount: queuedPrompts.length,
  219. queuedTexts: queuedPrompts.map((prompt) => prompt.content ?? ""),
  220. runtimeStatus: runtime?.status ?? null,
  221. selectedProvider: workspace.selectedProvider ?? null,
  222. selectedSupplierKey: workspace.selectedSupplierKey ?? null,
  223. stopRequested: workspace.taskStopRequestedByTaskId?.[taskIdArg] === true,
  224. streamingAssistantCount: messages.filter(
  225. (message) => message.role === "assistant" && message.streaming === true,
  226. ).length,
  227. taskConfigOptions: selectConfigSummary(workspace.taskConfigOptionsByTaskId?.[taskIdArg]),
  228. taskId: taskIdArg,
  229. taskMeta: taskMeta
  230. ? {
  231. model: taskMeta.model ?? null,
  232. provider: taskMeta.provider ?? null,
  233. targetId: taskMeta.target?.targetID ?? null,
  234. targetObjective: taskMeta.target?.objective ?? null,
  235. targetStatus: taskMeta.target?.status ?? null,
  236. title: taskMeta.title ?? null,
  237. }
  238. : null,
  239. timelineSummaries: messages
  240. .filter((message) => message.syntheticTimeline)
  241. .map((message) => ({
  242. goalIteration:
  243. typeof message.syntheticTimeline?.goalIteration === "number"
  244. ? message.syntheticTimeline.goalIteration
  245. : null,
  246. id: message.id ?? null,
  247. inputId: message.syntheticTimeline?.inputId ?? null,
  248. operationId: message.syntheticTimeline?.operationId ?? null,
  249. status: message.syntheticTimeline?.status ?? null,
  250. targetId: message.syntheticTimeline?.targetId ?? null,
  251. type: message.syntheticTimeline?.type ?? null,
  252. verificationPassed:
  253. typeof message.syntheticTimeline?.verification?.passed === "boolean"
  254. ? message.syntheticTimeline.verification.passed
  255. : null,
  256. })),
  257. uiError: stringifyUiError(taskUi?.error),
  258. workspaceConfigOptions: selectConfigSummary(workspace.configOptions),
  259. workspaceKey,
  260. },
  261. };
  262. }