conversationShareSelectionStore.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { create } from "zustand";
  2. import type { ConversationShareAccessMode } from "@zcode/shared";
  3. import type { ConversationShareFailureIssue } from "@zcode/services";
  4. export type ConversationShareScope = "all" | "partial";
  5. export type ConversationShareSelectionView = "selection" | "timeline";
  6. export type ConversationShareSelectionStage = "selection" | "configuration";
  7. export const DEFAULT_CONVERSATION_SHARE_ACCESS_MODE: ConversationShareAccessMode =
  8. "public_importable";
  9. export interface ConversationShareAttempt {
  10. key: string;
  11. clientRequestId: string;
  12. disclosureAcceptedAt: number;
  13. }
  14. export interface ConversationShareDisplayError {
  15. issues: readonly ConversationShareFailureIssue[];
  16. issueCount: number;
  17. omittedIssueCount?: number;
  18. requestId?: string;
  19. clientRequestId?: string;
  20. operationId?: string;
  21. status?: number;
  22. code?: number;
  23. /** 没有服务端 issues 时展示的、按错误类型解析出的可行动文案。 */
  24. messageId?: string;
  25. }
  26. /** 发布成功但有结果物被跳过时的非阻断提示。 */
  27. export interface ConversationShareDisplayWarnings {
  28. issues: readonly ConversationShareFailureIssue[];
  29. issueCount: number;
  30. omittedIssueCount?: number;
  31. }
  32. export type ConversationShareProgressPhase = "collecting" | "uploading" | "checking";
  33. export interface ConversationShareSelectionDraft {
  34. scope: ConversationShareScope;
  35. stage: ConversationShareSelectionStage;
  36. view: ConversationShareSelectionView;
  37. availableRowIds: readonly number[];
  38. excludedRowIds: readonly number[];
  39. productTurnIdByRowId: Readonly<Record<number, string>>;
  40. accessMode: ConversationShareAccessMode;
  41. }
  42. export interface ConversationShareDockState {
  43. title?: string;
  44. disclosureAccepted: boolean;
  45. publishing: boolean;
  46. progress: ConversationShareProgressPhase;
  47. completedArtifacts: number;
  48. totalArtifacts: number;
  49. publishedShareUrl: string | null;
  50. error: ConversationShareDisplayError | null;
  51. warnings: ConversationShareDisplayWarnings | null;
  52. attempt: ConversationShareAttempt | null;
  53. }
  54. interface ConversationShareSelectionState {
  55. popoverOpen: boolean;
  56. drafts: Record<string, ConversationShareSelectionDraft>;
  57. dockStates: Record<string, ConversationShareDockState>;
  58. setPopoverOpen: (open: boolean) => void;
  59. setScope: (taskId: string, scope: ConversationShareScope) => void;
  60. setAccessMode: (taskId: string, accessMode: ConversationShareAccessMode) => void;
  61. syncAvailableRowIds: (taskId: string, rowIds: readonly number[]) => void;
  62. syncAvailableTurns: (
  63. taskId: string,
  64. turns: readonly { rowId: number; productTurnId: string }[],
  65. ) => void;
  66. toggleRow: (taskId: string, rowId: number) => void;
  67. /** 按 product turn 身份整轮取消选择(阻断项的「取消选择该轮」入口)。 */
  68. deselectProductTurn: (taskId: string, productTurnId: string) => void;
  69. setAllRowsSelected: (taskId: string, selected: boolean) => void;
  70. goToConfiguration: (taskId: string) => void;
  71. goToSelection: (taskId: string) => void;
  72. showTimeline: (taskId: string) => void;
  73. showSelectionPanel: (taskId: string) => void;
  74. finishSelection: (taskId: string) => void;
  75. updateDockState: (taskId: string, patch: Partial<ConversationShareDockState>) => void;
  76. resetForTests: () => void;
  77. }
  78. const EMPTY_DRAFT: ConversationShareSelectionDraft = Object.freeze({
  79. scope: "all",
  80. stage: "selection",
  81. view: "timeline",
  82. availableRowIds: Object.freeze([]),
  83. excludedRowIds: Object.freeze([]),
  84. productTurnIdByRowId: Object.freeze({}),
  85. accessMode: DEFAULT_CONVERSATION_SHARE_ACCESS_MODE,
  86. });
  87. export const DEFAULT_CONVERSATION_SHARE_DOCK_STATE: ConversationShareDockState = Object.freeze({
  88. disclosureAccepted: false,
  89. publishing: false,
  90. progress: "collecting",
  91. completedArtifacts: 0,
  92. totalArtifacts: 0,
  93. publishedShareUrl: null,
  94. error: null,
  95. warnings: null,
  96. attempt: null,
  97. });
  98. const SESSION_SWITCH_REOPEN_KEY = "__zcodeConversationShareReopenAfterTaskSwitch";
  99. type ConversationShareWindow = Window & Partial<Record<typeof SESSION_SWITCH_REOPEN_KEY, boolean>>;
  100. export function markConversationSharePopoverForSessionSwitch(): void {
  101. if (typeof window === "undefined") return;
  102. (window as ConversationShareWindow)[SESSION_SWITCH_REOPEN_KEY] = true;
  103. }
  104. export function consumeConversationSharePopoverSessionSwitch(): boolean {
  105. if (typeof window === "undefined") return false;
  106. const runtimeWindow = window as ConversationShareWindow;
  107. const shouldReopen = runtimeWindow[SESSION_SWITCH_REOPEN_KEY] === true;
  108. delete runtimeWindow[SESSION_SWITCH_REOPEN_KEY];
  109. return shouldReopen;
  110. }
  111. function normalizeRowIds(rowIds: readonly number[]): number[] {
  112. return [...new Set(rowIds.filter(Number.isSafeInteger))].sort((left, right) => left - right);
  113. }
  114. export function getConversationShareDraft(
  115. state: Pick<ConversationShareSelectionState, "drafts">,
  116. taskId: string,
  117. ): ConversationShareSelectionDraft {
  118. return state.drafts[taskId] ?? EMPTY_DRAFT;
  119. }
  120. export function getConversationShareDockState(
  121. state: Pick<ConversationShareSelectionState, "dockStates">,
  122. taskId: string,
  123. ): ConversationShareDockState {
  124. return state.dockStates[taskId] ?? DEFAULT_CONVERSATION_SHARE_DOCK_STATE;
  125. }
  126. export function getConversationShareSelectedRowIds(
  127. state: Pick<ConversationShareSelectionState, "drafts">,
  128. taskId: string,
  129. ): number[] {
  130. const draft = getConversationShareDraft(state, taskId);
  131. const excluded = new Set(draft.excludedRowIds);
  132. return draft.availableRowIds.filter((rowId) => !excluded.has(rowId));
  133. }
  134. export function getConversationShareSelectedProductTurnIds(
  135. state: Pick<ConversationShareSelectionState, "drafts">,
  136. taskId: string,
  137. ): string[] {
  138. const draft = getConversationShareDraft(state, taskId);
  139. const seen = new Set<string>();
  140. return getConversationShareSelectedRowIds(state, taskId).flatMap((rowId) => {
  141. const productTurnId = draft.productTurnIdByRowId[rowId];
  142. if (!productTurnId || seen.has(productTurnId)) return [];
  143. seen.add(productTurnId);
  144. return [productTurnId];
  145. });
  146. }
  147. export const useConversationShareSelectionStore = create<ConversationShareSelectionState>()(
  148. (set) => ({
  149. popoverOpen: false,
  150. drafts: {},
  151. dockStates: {},
  152. setPopoverOpen: (popoverOpen) => set({ popoverOpen }),
  153. setScope: (taskId, scope) =>
  154. set((state) => {
  155. const currentDraft = state.drafts[taskId];
  156. const dockStates = { ...state.dockStates };
  157. if (scope === "partial") {
  158. if (currentDraft?.scope !== "partial") {
  159. const previousAttempt = state.dockStates[taskId]?.attempt;
  160. dockStates[taskId] = previousAttempt
  161. ? { ...DEFAULT_CONVERSATION_SHARE_DOCK_STATE, attempt: previousAttempt }
  162. : DEFAULT_CONVERSATION_SHARE_DOCK_STATE;
  163. }
  164. } else {
  165. delete dockStates[taskId];
  166. }
  167. return {
  168. // 进入局部选择后左侧面板成为唯一的范围选择入口,避免两个浮层同时争抢焦点。
  169. popoverOpen: scope === "partial" ? false : state.popoverOpen,
  170. drafts: {
  171. ...state.drafts,
  172. [taskId]:
  173. scope === "partial"
  174. ? {
  175. scope,
  176. stage: "selection",
  177. view: "selection",
  178. availableRowIds:
  179. state.drafts[taskId]?.availableRowIds ?? EMPTY_DRAFT.availableRowIds,
  180. // 每次从「全部对话」进入都是新的选择草稿,按产品语义默认全选。
  181. excludedRowIds: [],
  182. productTurnIdByRowId:
  183. state.drafts[taskId]?.productTurnIdByRowId ??
  184. EMPTY_DRAFT.productTurnIdByRowId,
  185. accessMode: state.drafts[taskId]?.accessMode ?? EMPTY_DRAFT.accessMode,
  186. }
  187. : EMPTY_DRAFT,
  188. },
  189. dockStates,
  190. };
  191. }),
  192. setAccessMode: (taskId, accessMode) =>
  193. set((state) => ({
  194. drafts: {
  195. ...state.drafts,
  196. [taskId]: {
  197. ...(state.drafts[taskId] ?? EMPTY_DRAFT),
  198. accessMode,
  199. },
  200. },
  201. })),
  202. syncAvailableRowIds: (taskId, rowIds) =>
  203. set((state) => {
  204. const current = getConversationShareDraft(state, taskId);
  205. if (current.scope !== "partial") return state;
  206. const availableRowIds = normalizeRowIds(rowIds);
  207. const available = new Set(availableRowIds);
  208. const excludedRowIds = current.excludedRowIds.filter((rowId) => available.has(rowId));
  209. if (
  210. availableRowIds.length === current.availableRowIds.length &&
  211. availableRowIds.every((rowId, index) => current.availableRowIds[index] === rowId) &&
  212. excludedRowIds.length === current.excludedRowIds.length
  213. ) {
  214. return state;
  215. }
  216. return {
  217. drafts: {
  218. ...state.drafts,
  219. [taskId]: { ...current, availableRowIds, excludedRowIds },
  220. },
  221. };
  222. }),
  223. syncAvailableTurns: (taskId, turns) =>
  224. set((state) => {
  225. const current = getConversationShareDraft(state, taskId);
  226. if (current.scope !== "partial") return state;
  227. const productTurnIdByRowId = Object.fromEntries(
  228. turns.map((turn) => [turn.rowId, turn.productTurnId]),
  229. );
  230. const availableRowIds = normalizeRowIds(turns.map((turn) => turn.rowId));
  231. const available = new Set(availableRowIds);
  232. return {
  233. drafts: {
  234. ...state.drafts,
  235. [taskId]: {
  236. ...current,
  237. availableRowIds,
  238. excludedRowIds: current.excludedRowIds.filter((rowId) => available.has(rowId)),
  239. productTurnIdByRowId,
  240. },
  241. },
  242. };
  243. }),
  244. toggleRow: (taskId, rowId) =>
  245. set((state) => {
  246. const current = getConversationShareDraft(state, taskId);
  247. if (current.scope !== "partial" || !current.availableRowIds.includes(rowId)) {
  248. return state;
  249. }
  250. const excluded = new Set(current.excludedRowIds);
  251. if (excluded.has(rowId)) excluded.delete(rowId);
  252. else excluded.add(rowId);
  253. return {
  254. drafts: {
  255. ...state.drafts,
  256. [taskId]: {
  257. ...current,
  258. excludedRowIds: [...excluded].sort((left, right) => left - right),
  259. },
  260. },
  261. };
  262. }),
  263. /**
  264. * 按 product turn 身份整轮取消选择。
  265. *
  266. * 不能让 UI 用 service 的 turnOrdinal 去索引自己的 per-query 列表:
  267. * 两套编号在含系统上下文轮或多 steer query 的会话里必然错位;而且 toggleRow 只
  268. * 排除一行,同一轮的其他 query 仍留在选择里,阻断轮根本没被移除。
  269. * 「取消该轮」的语义是整轮,因此按 productTurnId 一次性排除全部行,且幂等。
  270. */
  271. deselectProductTurn: (taskId, productTurnId) =>
  272. set((state) => {
  273. const current = getConversationShareDraft(state, taskId);
  274. if (current.scope !== "partial" || !productTurnId) return state;
  275. const excluded = new Set(current.excludedRowIds);
  276. let changed = false;
  277. for (const rowId of current.availableRowIds) {
  278. if (current.productTurnIdByRowId[rowId] !== productTurnId || excluded.has(rowId)) {
  279. continue;
  280. }
  281. excluded.add(rowId);
  282. changed = true;
  283. }
  284. if (!changed) return state;
  285. return {
  286. drafts: {
  287. ...state.drafts,
  288. [taskId]: {
  289. ...current,
  290. excludedRowIds: [...excluded].sort((left, right) => left - right),
  291. },
  292. },
  293. };
  294. }),
  295. setAllRowsSelected: (taskId, selected) =>
  296. set((state) => {
  297. const current = getConversationShareDraft(state, taskId);
  298. if (current.scope !== "partial") return state;
  299. const excludedRowIds = selected ? [] : [...current.availableRowIds];
  300. if (
  301. excludedRowIds.length === current.excludedRowIds.length &&
  302. excludedRowIds.every((rowId, index) => current.excludedRowIds[index] === rowId)
  303. ) {
  304. return state;
  305. }
  306. return {
  307. drafts: {
  308. ...state.drafts,
  309. [taskId]: { ...current, excludedRowIds },
  310. },
  311. };
  312. }),
  313. goToConfiguration: (taskId) =>
  314. set((state) => {
  315. const current = getConversationShareDraft(state, taskId);
  316. if (
  317. current.scope !== "partial" ||
  318. current.stage === "configuration" ||
  319. getConversationShareSelectedRowIds(state, taskId).length === 0
  320. ) {
  321. return state;
  322. }
  323. return {
  324. drafts: {
  325. ...state.drafts,
  326. [taskId]: { ...current, stage: "configuration" },
  327. },
  328. };
  329. }),
  330. goToSelection: (taskId) =>
  331. set((state) => {
  332. const current = getConversationShareDraft(state, taskId);
  333. if (current.scope !== "partial" || current.stage === "selection") return state;
  334. return {
  335. drafts: {
  336. ...state.drafts,
  337. [taskId]: { ...current, stage: "selection", view: "selection" },
  338. },
  339. };
  340. }),
  341. showTimeline: (taskId) =>
  342. set((state) => {
  343. const current = getConversationShareDraft(state, taskId);
  344. if (current.scope !== "partial") return state;
  345. return {
  346. drafts: {
  347. ...state.drafts,
  348. [taskId]: { ...current, view: "timeline" },
  349. },
  350. };
  351. }),
  352. showSelectionPanel: (taskId) =>
  353. set((state) => {
  354. const current = getConversationShareDraft(state, taskId);
  355. if (current.scope !== "partial" || current.stage !== "selection") return state;
  356. return {
  357. // timeline 被标记为 popover 的 keep-open 区域,导致返回左侧面板时
  358. // 右上角 dropdown 仍滞留。面板切换由 store 收口,同时关闭 dropdown。
  359. popoverOpen: false,
  360. drafts: {
  361. ...state.drafts,
  362. [taskId]: { ...current, view: "selection" },
  363. },
  364. };
  365. }),
  366. finishSelection: (taskId) =>
  367. set((state) => {
  368. const dockStates = { ...state.dockStates };
  369. const previousAttempt = dockStates[taskId]?.attempt;
  370. if (previousAttempt) {
  371. // 幂等重试记录按 session 保留,但关闭后的可见结果、进度和错误必须清空。
  372. dockStates[taskId] = {
  373. ...DEFAULT_CONVERSATION_SHARE_DOCK_STATE,
  374. attempt: previousAttempt,
  375. };
  376. } else {
  377. delete dockStates[taskId];
  378. }
  379. return {
  380. drafts: { ...state.drafts, [taskId]: EMPTY_DRAFT },
  381. // SessionPane 复用实例时,分享成功态不能留在组件本地,
  382. // 切到其它 session 后会继续被渲染;结束分享必须只清理当前 session 的 dock key。
  383. dockStates,
  384. };
  385. }),
  386. updateDockState: (taskId, patch) =>
  387. set((state) => ({
  388. dockStates: {
  389. ...state.dockStates,
  390. [taskId]: {
  391. ...getConversationShareDockState(state, taskId),
  392. ...patch,
  393. },
  394. },
  395. })),
  396. resetForTests: () =>
  397. set({
  398. popoverOpen: false,
  399. drafts: {},
  400. dockStates: {},
  401. }),
  402. }),
  403. );