zcodeSessionStoreTaskSlice.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. import { clearV4ComposerDraft } from "@/v4/composer/composerDraftStore.js";
  2. /* oxlint-disable eslint(max-lines) -- 当前文件承接 task 级状态切片,先保持最小改动修复草稿逻辑,后续再统一拆分 */
  3. import {
  4. normalizeAgentProviderToZCodeAgent,
  5. type ZCodeApiRetryStatus,
  6. type ZCodeConfigOption,
  7. type ZCodePermissionRequest,
  8. type ZCodeElicitationRequest,
  9. type ZCodeProvider,
  10. type ZCodeTaskRuntimeStatus,
  11. type ZCodeTaskMeta,
  12. } from "@zcode/shared";
  13. import type { ZCodeUiError } from "@/lib/zcodeUiError.js";
  14. import { removeTaskFromHistory } from "@/lib/taskNavigationHistory.js";
  15. import { mergeTaskWithOptimisticMeta } from "@/lib/zcodeTaskMetaMerge.js";
  16. import type {
  17. ConfigOptionsStatus,
  18. ElicitationFormDraft,
  19. ZCodeSessionStoreState,
  20. TaskUsageState,
  21. } from "@/store/zcodeSessionStoreTypes.js";
  22. import { getDefaultWorkspaceState } from "@/store/zcodeSessionStoreTypes.js";
  23. import { clearPersistedComposerDraft } from "@/lib/chatComposerDraftStorage.js";
  24. import { areConfigOptionsEquivalent } from "@/lib/configOptionsEquality.js";
  25. import {
  26. getTaskRuntimeState,
  27. getTaskUiState,
  28. getWorkspaceState,
  29. resolveWorkspaceStateKey,
  30. updateWorkspaceState,
  31. } from "@/store/zcodeSessionStoreSelectors.js";
  32. type SetFn = (
  33. partial:
  34. | ZCodeSessionStoreState
  35. | Partial<ZCodeSessionStoreState>
  36. | ((state: ZCodeSessionStoreState) => ZCodeSessionStoreState | Partial<ZCodeSessionStoreState>),
  37. ) => void;
  38. function sortTasksByUpdatedAt(tasks: readonly ZCodeTaskMeta[]): ZCodeTaskMeta[] {
  39. return [...tasks].sort((left, right) => {
  40. if (right.updatedAt !== left.updatedAt) {
  41. return right.updatedAt - left.updatedAt;
  42. }
  43. if (right.createdAt !== left.createdAt) {
  44. return right.createdAt - left.createdAt;
  45. }
  46. return right.taskId.localeCompare(left.taskId);
  47. });
  48. }
  49. function arePermissionOptionsEqual(
  50. left: ZCodePermissionRequest["options"],
  51. right: ZCodePermissionRequest["options"],
  52. ): boolean {
  53. if (left.length !== right.length) {
  54. return false;
  55. }
  56. return left.every((option, index) => {
  57. const otherOption = right[index];
  58. if (!otherOption) {
  59. return false;
  60. }
  61. return (
  62. option.optionId === otherOption.optionId &&
  63. option.kind === otherOption.kind &&
  64. option.name === otherOption.name
  65. );
  66. });
  67. }
  68. function arePermissionRequestsEquivalent(
  69. left: ZCodePermissionRequest,
  70. right: ZCodePermissionRequest,
  71. ): boolean {
  72. if (left === right) {
  73. return true;
  74. }
  75. // 同一 requestId 可能被连续投递成不同对象。raw 只用于展示预览,协议上 requestId 才是权限请求身份;
  76. // 这里按可见字段去重,避免重复请求把权限弹窗和 ChatView 整体重渲染。
  77. return (
  78. left.requestId === right.requestId &&
  79. left.taskId === right.taskId &&
  80. left.traceId === right.traceId &&
  81. left.inputId === right.inputId &&
  82. left.kind === right.kind &&
  83. left.title === right.title &&
  84. left.description === right.description &&
  85. arePermissionOptionsEqual(left.options, right.options)
  86. );
  87. }
  88. function areTaskUsageCostsEqual(
  89. left: TaskUsageState["cost"] | undefined,
  90. right: TaskUsageState["cost"] | undefined,
  91. ): boolean {
  92. const normalizedLeft = left ?? null;
  93. const normalizedRight = right ?? null;
  94. if (normalizedLeft === null || normalizedRight === null) {
  95. return normalizedLeft === normalizedRight;
  96. }
  97. return (
  98. normalizedLeft.amount === normalizedRight.amount &&
  99. normalizedLeft.currency === normalizedRight.currency
  100. );
  101. }
  102. function areTaskUsageCachesEqual(
  103. left: TaskUsageState["cache"] | undefined,
  104. right: TaskUsageState["cache"] | undefined,
  105. ): boolean {
  106. if (left === right) {
  107. return true;
  108. }
  109. if (!left || !right) {
  110. return false;
  111. }
  112. return (
  113. left.inputTokens === right.inputTokens &&
  114. left.cacheReadTokens === right.cacheReadTokens &&
  115. left.cacheWriteTokens === right.cacheWriteTokens &&
  116. left.latestHitRate === right.latestHitRate &&
  117. left.hitRate === right.hitRate &&
  118. left.hitRateRequestCount === right.hitRateRequestCount &&
  119. left.totalInputTokens === right.totalInputTokens &&
  120. left.totalCacheReadTokens === right.totalCacheReadTokens &&
  121. left.totalCacheWriteTokens === right.totalCacheWriteTokens
  122. );
  123. }
  124. function areTaskUsageBreakdownsEqual(
  125. left: TaskUsageState["breakdown"] | undefined,
  126. right: TaskUsageState["breakdown"] | undefined,
  127. ): boolean {
  128. if (left === right) {
  129. return true;
  130. }
  131. if (!left || !right || left.length !== right.length) {
  132. return false;
  133. }
  134. return left.every(
  135. (item, index) => item.source === right[index]?.source && item.chars === right[index]?.chars,
  136. );
  137. }
  138. function areTaskUsageStatesEqual(
  139. left: TaskUsageState | null,
  140. right: TaskUsageState | null,
  141. ): boolean {
  142. if (left === right) {
  143. return true;
  144. }
  145. if (!left || !right) {
  146. return false;
  147. }
  148. return (
  149. left.size === right.size &&
  150. left.used === right.used &&
  151. areTaskUsageCostsEqual(left.cost, right.cost) &&
  152. areTaskUsageCachesEqual(left.cache, right.cache) &&
  153. areTaskUsageBreakdownsEqual(left.breakdown, right.breakdown)
  154. );
  155. }
  156. function normalizeTaskContextWindow(contextWindow: number | null): number | null {
  157. if (contextWindow === null) {
  158. return null;
  159. }
  160. if (!Number.isFinite(contextWindow) || contextWindow <= 0) {
  161. return null;
  162. }
  163. return Math.floor(contextWindow);
  164. }
  165. function updateWorkspaceStateForIdentityScopedTaskState(
  166. state: ZCodeSessionStoreState,
  167. workspacePath: string,
  168. workspaceIdentity: string | undefined,
  169. updater: (
  170. current: ReturnType<typeof getDefaultWorkspaceState>,
  171. ) => ReturnType<typeof getDefaultWorkspaceState>,
  172. ): Pick<ZCodeSessionStoreState, "workspaces"> {
  173. const workspaceKey = resolveWorkspaceStateKey(workspacePath, workspaceIdentity);
  174. if (workspaceKey === workspacePath) {
  175. return updateWorkspaceState(state, workspacePath, updater);
  176. }
  177. const current = state.workspaces[workspaceKey] ?? getDefaultWorkspaceState();
  178. return {
  179. workspaces: {
  180. ...state.workspaces,
  181. [workspaceKey]: updater(current),
  182. },
  183. };
  184. }
  185. export function createTaskSlice(set: SetFn) {
  186. return {
  187. setTaskRuntimeState: (
  188. workspacePath: string,
  189. taskId: string,
  190. status: ZCodeTaskRuntimeStatus,
  191. error?: string | null,
  192. workspaceIdentity?: string,
  193. provider?: ZCodeProvider,
  194. ) => {
  195. set((state) =>
  196. updateWorkspaceState(
  197. state,
  198. workspacePath,
  199. (current) => {
  200. const currentTaskRuntime = getTaskRuntimeState(current, taskId);
  201. const isRunningStatus =
  202. status === "creating" || status === "restoring" || status === "streaming";
  203. const nextTaskRuntime = {
  204. ...currentTaskRuntime,
  205. status,
  206. error: error ?? null,
  207. provider: provider ?? currentTaskRuntime.provider,
  208. // activeInputId 是当前生成轮次的命令路由标识。
  209. // 终态/非运行态如果继续保留旧 inputId,移动端只靠快照补齐时会把已结束任务误判成仍在 loading。
  210. // activeTurnKind 同样是 session 运行态;compact 完成后必须清掉,
  211. // 否则 app 层会继续把同一 task 的发送误判为“压缩中”并吞掉。
  212. activeTurnKind: isRunningStatus ? currentTaskRuntime.activeTurnKind : undefined,
  213. activeInputId: isRunningStatus ? currentTaskRuntime.activeInputId : undefined,
  214. activeInputOwnerClientId: isRunningStatus
  215. ? currentTaskRuntime.activeInputOwnerClientId
  216. : undefined,
  217. };
  218. return {
  219. ...current,
  220. taskRuntimeByTaskId: {
  221. ...current.taskRuntimeByTaskId,
  222. [taskId]: nextTaskRuntime,
  223. },
  224. };
  225. },
  226. workspaceIdentity,
  227. ),
  228. );
  229. },
  230. setTaskUsage: (
  231. workspacePath: string,
  232. taskId: string,
  233. usage: TaskUsageState | null,
  234. workspaceIdentity?: string,
  235. ) => {
  236. set((state) => {
  237. const current = getWorkspaceState(state, workspacePath, workspaceIdentity);
  238. const currentRuntime = getTaskRuntimeState(current, taskId);
  239. if (areTaskUsageStatesEqual(currentRuntime.usage, usage)) {
  240. // usage_update 在流式期间可能以相同数值重复到达。
  241. // 如果继续创建新的 workspace/taskRuntime 对象,React 会被无意义唤醒并造成掉帧。
  242. return state;
  243. }
  244. return updateWorkspaceStateForIdentityScopedTaskState(
  245. state,
  246. workspacePath,
  247. workspaceIdentity,
  248. (current) => ({
  249. ...current,
  250. taskRuntimeByTaskId: {
  251. ...current.taskRuntimeByTaskId,
  252. [taskId]: {
  253. ...getTaskRuntimeState(current, taskId),
  254. usage,
  255. },
  256. },
  257. }),
  258. );
  259. });
  260. },
  261. setTaskContextWindow: (
  262. workspacePath: string,
  263. taskId: string,
  264. contextWindow: number | null,
  265. workspaceIdentity?: string,
  266. ) => {
  267. const normalizedContextWindow = normalizeTaskContextWindow(contextWindow);
  268. set((state) => {
  269. const current = getWorkspaceState(state, workspacePath, workspaceIdentity);
  270. const currentRuntime = getTaskRuntimeState(current, taskId);
  271. if (currentRuntime.contextWindow === normalizedContextWindow) {
  272. return state;
  273. }
  274. return updateWorkspaceStateForIdentityScopedTaskState(
  275. state,
  276. workspacePath,
  277. workspaceIdentity,
  278. (current) => ({
  279. ...current,
  280. taskRuntimeByTaskId: {
  281. ...current.taskRuntimeByTaskId,
  282. [taskId]: {
  283. ...getTaskRuntimeState(current, taskId),
  284. // contextWindow 来自模型状态,usage.used 来自运行时 token 统计。
  285. // 两者流式到达顺序不同,窗口刷新不能重建 usage 对象,否则会把正数 used 覆盖成 0。
  286. contextWindow: normalizedContextWindow,
  287. },
  288. },
  289. }),
  290. );
  291. });
  292. },
  293. setTaskApiRetryStatus: (
  294. workspacePath: string,
  295. taskId: string,
  296. apiRetry: ZCodeApiRetryStatus | null,
  297. workspaceIdentity?: string,
  298. ) => {
  299. set((state) =>
  300. updateWorkspaceState(
  301. state,
  302. workspacePath,
  303. (current) => ({
  304. ...current,
  305. taskRuntimeByTaskId: {
  306. ...current.taskRuntimeByTaskId,
  307. [taskId]: {
  308. ...getTaskRuntimeState(current, taskId),
  309. apiRetry,
  310. },
  311. },
  312. }),
  313. workspaceIdentity,
  314. ),
  315. );
  316. },
  317. setTaskConfigOptions: (
  318. workspacePath: string,
  319. taskId: string,
  320. options: ZCodeConfigOption[],
  321. workspaceIdentity?: string,
  322. status: ConfigOptionsStatus = "ready",
  323. ) => {
  324. const normalizedOptions = [...options];
  325. set((state) => {
  326. const current = getWorkspaceState(state, workspacePath, workspaceIdentity);
  327. const currentOptions = current.taskConfigOptionsByTaskId[taskId] ?? [];
  328. const currentStatus = current.taskConfigOptionsStatusByTaskId[taskId] ?? "ready";
  329. if (
  330. currentStatus === status &&
  331. areConfigOptionsEquivalent(currentOptions, normalizedOptions)
  332. ) {
  333. // 历史 task 恢复旧模型或无 API key 自动清空模型时,多个恢复路径可能反复提交
  334. // 内容相同但引用不同的 configOptions。这里直接跳过等价写入,避免 Zustand 通知触发 React effect 循环。
  335. return state;
  336. }
  337. return updateWorkspaceState(
  338. state,
  339. workspacePath,
  340. (current) => {
  341. return {
  342. ...current,
  343. taskConfigOptionsByTaskId: {
  344. ...current.taskConfigOptionsByTaskId,
  345. [taskId]: normalizedOptions,
  346. },
  347. taskConfigOptionsStatusByTaskId: {
  348. ...current.taskConfigOptionsStatusByTaskId,
  349. [taskId]: status,
  350. },
  351. };
  352. },
  353. workspaceIdentity,
  354. );
  355. });
  356. },
  357. setTaskPermissionRequest: (
  358. workspacePath: string,
  359. taskId: string,
  360. request: ZCodePermissionRequest | null,
  361. workspaceIdentity?: string,
  362. ) => {
  363. set((state) =>
  364. updateWorkspaceState(
  365. state,
  366. workspacePath,
  367. (current) => {
  368. const taskUiState = getTaskUiState(current, taskId);
  369. if (request === null) {
  370. if (
  371. taskUiState.permissionRequest === null &&
  372. taskUiState.pendingPermissionRequests.length === 0
  373. ) {
  374. return current;
  375. }
  376. return {
  377. ...current,
  378. taskUiByTaskId: {
  379. ...current.taskUiByTaskId,
  380. [taskId]: {
  381. ...taskUiState,
  382. permissionRequest: null,
  383. pendingPermissionRequests: [],
  384. },
  385. },
  386. };
  387. }
  388. const currentPermissionRequest = taskUiState.permissionRequest;
  389. const pendingPermissionRequests = taskUiState.pendingPermissionRequests ?? [];
  390. let nextPermissionRequest = currentPermissionRequest;
  391. let nextPendingPermissionRequests = pendingPermissionRequests;
  392. if (currentPermissionRequest?.requestId === request.requestId) {
  393. if (arePermissionRequestsEquivalent(currentPermissionRequest, request)) {
  394. return current;
  395. }
  396. nextPermissionRequest = request;
  397. } else if (currentPermissionRequest === null) {
  398. nextPermissionRequest = request;
  399. nextPendingPermissionRequests = pendingPermissionRequests.filter(
  400. (item) => item.requestId !== request.requestId,
  401. );
  402. } else {
  403. const existingPendingIndex = pendingPermissionRequests.findIndex(
  404. (item) => item.requestId === request.requestId,
  405. );
  406. if (existingPendingIndex >= 0) {
  407. const existingPendingRequest = pendingPermissionRequests[existingPendingIndex];
  408. if (!existingPendingRequest) {
  409. return current;
  410. }
  411. if (arePermissionRequestsEquivalent(existingPendingRequest, request)) {
  412. return current;
  413. }
  414. nextPendingPermissionRequests = pendingPermissionRequests.map((item, index) =>
  415. index === existingPendingIndex ? request : item,
  416. );
  417. } else {
  418. // 同一 task 里可能连续出现多个权限请求。只有一个 permissionRequest 字段时,
  419. // 后到的请求会直接覆盖前一个,导致前面的 pending 权限永远没人响应,任务表面上像是“卡住”。
  420. // 这里把后续请求按 task 入队,保证用户确认当前请求后,下一个还能自动顶上来继续处理。
  421. nextPendingPermissionRequests = [...pendingPermissionRequests, request];
  422. }
  423. }
  424. return {
  425. ...current,
  426. taskUiByTaskId: {
  427. ...current.taskUiByTaskId,
  428. [taskId]: {
  429. ...taskUiState,
  430. permissionRequest: nextPermissionRequest,
  431. pendingPermissionRequests: nextPendingPermissionRequests,
  432. },
  433. },
  434. };
  435. },
  436. workspaceIdentity,
  437. ),
  438. );
  439. },
  440. removeTaskPermissionRequest: (
  441. workspacePath: string,
  442. taskId: string,
  443. requestId: string,
  444. workspaceIdentity?: string,
  445. ) => {
  446. set((state) =>
  447. updateWorkspaceState(
  448. state,
  449. workspacePath,
  450. (current) => {
  451. const taskUiState = getTaskUiState(current, taskId);
  452. const currentPermissionRequest = taskUiState.permissionRequest;
  453. const pendingPermissionRequests = taskUiState.pendingPermissionRequests ?? [];
  454. if (currentPermissionRequest?.requestId === requestId) {
  455. const [nextPermissionRequest, ...restPendingPermissionRequests] =
  456. pendingPermissionRequests;
  457. return {
  458. ...current,
  459. taskUiByTaskId: {
  460. ...current.taskUiByTaskId,
  461. [taskId]: {
  462. ...taskUiState,
  463. permissionRequest: nextPermissionRequest ?? null,
  464. pendingPermissionRequests: restPendingPermissionRequests,
  465. },
  466. },
  467. };
  468. }
  469. const pendingPermissionIndex = pendingPermissionRequests.findIndex(
  470. (item) => item.requestId === requestId,
  471. );
  472. if (pendingPermissionIndex < 0) {
  473. // 权限响应会走本地乐观清理,也会再收到一次 stream 回放的 permission_response。
  474. // 第二次清理如果继续重建 taskUiState,会触发 ChatView 和权限预览树无意义重渲染,导致确认后 CPU 飙高。
  475. return current;
  476. }
  477. return {
  478. ...current,
  479. taskUiByTaskId: {
  480. ...current.taskUiByTaskId,
  481. [taskId]: {
  482. ...taskUiState,
  483. pendingPermissionRequests: pendingPermissionRequests.filter(
  484. (_item, index) => index !== pendingPermissionIndex,
  485. ),
  486. },
  487. },
  488. };
  489. },
  490. workspaceIdentity,
  491. ),
  492. );
  493. },
  494. setTaskElicitationRequest: (
  495. workspacePath: string,
  496. taskId: string,
  497. request: ZCodeElicitationRequest | null,
  498. workspaceIdentity?: string,
  499. ) => {
  500. set((state) =>
  501. updateWorkspaceState(
  502. state,
  503. workspacePath,
  504. (current) => {
  505. const taskUiState = getTaskUiState(current, taskId);
  506. if (request === null) {
  507. return {
  508. ...current,
  509. taskUiByTaskId: {
  510. ...current.taskUiByTaskId,
  511. [taskId]: {
  512. ...taskUiState,
  513. elicitationRequest: null,
  514. pendingElicitationRequests: [],
  515. },
  516. },
  517. };
  518. }
  519. const currentElicitationRequest = taskUiState.elicitationRequest;
  520. const pendingElicitationRequests = taskUiState.pendingElicitationRequests ?? [];
  521. let nextElicitationRequest = currentElicitationRequest;
  522. let nextPendingElicitationRequests = pendingElicitationRequests;
  523. if (currentElicitationRequest?.requestId === request.requestId) {
  524. nextElicitationRequest = request;
  525. } else if (currentElicitationRequest === null) {
  526. nextElicitationRequest = request;
  527. nextPendingElicitationRequests = pendingElicitationRequests.filter(
  528. (item) => item.requestId !== request.requestId,
  529. );
  530. } else {
  531. const existingPendingIndex = pendingElicitationRequests.findIndex(
  532. (item) => item.requestId === request.requestId,
  533. );
  534. if (existingPendingIndex >= 0) {
  535. nextPendingElicitationRequests = pendingElicitationRequests.map((item, index) =>
  536. index === existingPendingIndex ? request : item,
  537. );
  538. } else {
  539. nextPendingElicitationRequests = [...pendingElicitationRequests, request];
  540. }
  541. }
  542. return {
  543. ...current,
  544. taskUiByTaskId: {
  545. ...current.taskUiByTaskId,
  546. [taskId]: {
  547. ...taskUiState,
  548. elicitationRequest: nextElicitationRequest,
  549. pendingElicitationRequests: nextPendingElicitationRequests,
  550. },
  551. },
  552. };
  553. },
  554. workspaceIdentity,
  555. ),
  556. );
  557. },
  558. removeTaskElicitationRequest: (
  559. workspacePath: string,
  560. taskId: string,
  561. requestId: string,
  562. workspaceIdentity?: string,
  563. ) => {
  564. set((state) =>
  565. updateWorkspaceState(
  566. state,
  567. workspacePath,
  568. (current) => {
  569. const taskUiState = getTaskUiState(current, taskId);
  570. const currentElicitationRequest = taskUiState.elicitationRequest;
  571. const pendingElicitationRequests = taskUiState.pendingElicitationRequests ?? [];
  572. if (currentElicitationRequest?.requestId === requestId) {
  573. const [nextElicitationRequest, ...restPendingElicitationRequests] =
  574. pendingElicitationRequests;
  575. return {
  576. ...current,
  577. taskUiByTaskId: {
  578. ...current.taskUiByTaskId,
  579. [taskId]: {
  580. ...taskUiState,
  581. elicitationRequest: nextElicitationRequest ?? null,
  582. pendingElicitationRequests: restPendingElicitationRequests,
  583. },
  584. },
  585. };
  586. }
  587. return {
  588. ...current,
  589. taskUiByTaskId: {
  590. ...current.taskUiByTaskId,
  591. [taskId]: {
  592. ...taskUiState,
  593. pendingElicitationRequests: pendingElicitationRequests.filter(
  594. (item) => item.requestId !== requestId,
  595. ),
  596. },
  597. },
  598. };
  599. },
  600. workspaceIdentity,
  601. ),
  602. );
  603. },
  604. setTaskElicitationFormDraft: (
  605. workspacePath: string,
  606. taskId: string,
  607. requestId: string,
  608. draft: ElicitationFormDraft,
  609. workspaceIdentity?: string,
  610. ) => {
  611. set((state) =>
  612. updateWorkspaceState(
  613. state,
  614. workspacePath,
  615. (current) => {
  616. const taskUiState = getTaskUiState(current, taskId);
  617. return {
  618. ...current,
  619. taskUiByTaskId: {
  620. ...current.taskUiByTaskId,
  621. [taskId]: {
  622. ...taskUiState,
  623. // 问答进度原本只存在弹窗 useState,切换 task 后组件卸载,
  624. // 再挂载只能从原始 request 初始化。按 task/request 提升到 renderer store,
  625. // 既能恢复本地草稿,也不会把分题状态误写入 runtime/replayable snapshot。
  626. elicitationFormDraftsByRequestId: {
  627. ...taskUiState.elicitationFormDraftsByRequestId,
  628. [requestId]: draft,
  629. },
  630. },
  631. },
  632. };
  633. },
  634. workspaceIdentity,
  635. ),
  636. );
  637. },
  638. removeTaskElicitationFormDraft: (
  639. workspacePath: string,
  640. taskId: string,
  641. requestId: string,
  642. workspaceIdentity?: string,
  643. ) => {
  644. set((state) =>
  645. updateWorkspaceState(
  646. state,
  647. workspacePath,
  648. (current) => {
  649. const taskUiState = getTaskUiState(current, taskId);
  650. if (!(requestId in taskUiState.elicitationFormDraftsByRequestId)) {
  651. return current;
  652. }
  653. const nextDrafts = { ...taskUiState.elicitationFormDraftsByRequestId };
  654. delete nextDrafts[requestId];
  655. return {
  656. ...current,
  657. taskUiByTaskId: {
  658. ...current.taskUiByTaskId,
  659. [taskId]: {
  660. ...taskUiState,
  661. elicitationFormDraftsByRequestId: nextDrafts,
  662. },
  663. },
  664. };
  665. },
  666. workspaceIdentity,
  667. ),
  668. );
  669. },
  670. setTaskError: (
  671. workspacePath: string,
  672. taskId: string,
  673. error: ZCodeUiError | null,
  674. workspaceIdentity?: string,
  675. ) => {
  676. set((state) =>
  677. updateWorkspaceState(
  678. state,
  679. workspacePath,
  680. (current) => ({
  681. ...current,
  682. taskUiByTaskId: {
  683. ...current.taskUiByTaskId,
  684. [taskId]: {
  685. ...getTaskUiState(current, taskId),
  686. // 完整错误对象之前只放在 ChatView/useZCodeChat 的本地 state。
  687. // 一旦切换页面或任务,组件卸载后 traceId/code 就会一起丢失,只剩 taskRuntime.error 的纯文本。
  688. // 这里改成按 task 写进 store,让错误提示能跟 plan/permission 一样跨页面恢复。
  689. error,
  690. },
  691. },
  692. }),
  693. workspaceIdentity,
  694. ),
  695. );
  696. },
  697. initializeBackgroundTaskRuntime: (
  698. workspacePath: string,
  699. params: {
  700. task: ZCodeTaskMeta;
  701. provider: ZCodeProvider;
  702. activeInputId: string;
  703. workspaceIdentity?: string;
  704. },
  705. ) => {
  706. set((state) =>
  707. updateWorkspaceState(
  708. state,
  709. workspacePath,
  710. (current) => {
  711. const existingTask = current.optimisticTaskListByTaskId[params.task.taskId];
  712. const nextTask = existingTask
  713. ? mergeTaskWithOptimisticMeta(params.task, existingTask)
  714. : params.task;
  715. const currentTaskRuntime = getTaskRuntimeState(current, params.task.taskId);
  716. const cachedTasks = current.taskListCache ?? [];
  717. const nextTaskListCache =
  718. current.taskListCache === null
  719. ? current.taskListCache
  720. : sortTasksByUpdatedAt([
  721. nextTask,
  722. ...cachedTasks.filter((cachedTask) => cachedTask.taskId !== params.task.taskId),
  723. ]);
  724. return {
  725. ...current,
  726. selectedProvider: normalizeAgentProviderToZCodeAgent(params.provider),
  727. // 性能优化:后台首发不需要先经历 optimistic -> cache -> runtime 多轮 set。
  728. // 合到一次写入可以削掉并发压测创建任务时的 renderer 订阅风暴。
  729. optimisticTaskListByTaskId: {
  730. ...current.optimisticTaskListByTaskId,
  731. [params.task.taskId]: nextTask,
  732. },
  733. taskListCache: nextTaskListCache,
  734. taskRuntimeByTaskId: {
  735. ...current.taskRuntimeByTaskId,
  736. [params.task.taskId]: {
  737. ...currentTaskRuntime,
  738. status: "streaming",
  739. error: null,
  740. provider: params.provider,
  741. activeInputId: params.activeInputId,
  742. },
  743. },
  744. };
  745. },
  746. params.workspaceIdentity ?? params.task.workspaceIdentity,
  747. ),
  748. );
  749. },
  750. upsertOptimisticTaskListItem: (
  751. workspacePath: string,
  752. task: ZCodeTaskMeta,
  753. workspaceIdentity?: string,
  754. ) => {
  755. set((state) =>
  756. updateWorkspaceState(
  757. state,
  758. workspacePath,
  759. (current) => {
  760. const existingTask = current.optimisticTaskListByTaskId[task.taskId];
  761. const nextTask = existingTask ? mergeTaskWithOptimisticMeta(task, existingTask) : task;
  762. return {
  763. ...current,
  764. optimisticTaskListByTaskId: {
  765. ...current.optimisticTaskListByTaskId,
  766. // desktop-continuous 的 readSession 快照可能旧于首发 optimistic Date.now()。
  767. // 这里按 updatedAt 单调合并,避免旧快照把新 task 压回列表下面。
  768. [task.taskId]: nextTask,
  769. },
  770. };
  771. },
  772. workspaceIdentity ?? task.workspaceIdentity,
  773. ),
  774. );
  775. },
  776. removeOptimisticTaskListItem: (
  777. workspacePath: string,
  778. taskId: string,
  779. workspaceIdentity?: string,
  780. ) => {
  781. set((state) =>
  782. updateWorkspaceState(
  783. state,
  784. workspacePath,
  785. (current) => {
  786. const { [taskId]: _removedTaskMeta, ...restOptimisticTaskListByTaskId } =
  787. current.optimisticTaskListByTaskId;
  788. return {
  789. ...current,
  790. optimisticTaskListByTaskId: restOptimisticTaskListByTaskId,
  791. };
  792. },
  793. workspaceIdentity,
  794. ),
  795. );
  796. },
  797. removeTaskState: (workspacePath: string, taskId: string, workspaceIdentity?: string) => {
  798. // task 删除会清内存 task state,但 composer 草稿还有桌面端 localStorage 桶。
  799. // 如果不在统一删除 action 里同步清理,重启后已删除 task 的草稿会继续残留。
  800. clearPersistedComposerDraft(workspacePath, taskId, workspaceIdentity);
  801. clearV4ComposerDraft(workspacePath, workspaceIdentity, taskId);
  802. set((state) => {
  803. const workspaceUpdate = updateWorkspaceState(
  804. state,
  805. workspacePath,
  806. (current) => {
  807. const { [taskId]: _removedTaskRuntime, ...restTaskRuntimeByTaskId } =
  808. current.taskRuntimeByTaskId;
  809. const { [taskId]: _removedTaskUi, ...restTaskUiByTaskId } = current.taskUiByTaskId;
  810. const { [taskId]: _removedTaskConfigOptions, ...restTaskConfigOptionsByTaskId } =
  811. current.taskConfigOptionsByTaskId;
  812. const {
  813. [taskId]: _removedTaskConfigOptionsStatus,
  814. ...restTaskConfigOptionsStatusByTaskId
  815. } = current.taskConfigOptionsStatusByTaskId;
  816. const { [taskId]: _removedTaskUnread, ...restTaskUnreadByTaskId } =
  817. current.taskUnreadByTaskId;
  818. const { [taskId]: _removedTaskMeta, ...restOptimisticTaskListByTaskId } =
  819. current.optimisticTaskListByTaskId;
  820. const shouldCloseDeletedTask = current.activeTaskId === taskId;
  821. // 删除左侧当前正在查看的任务时,之前只更新了任务列表数据,
  822. // workspace 里的 activeTaskId 仍指向已删除 task,右侧主区就会继续按旧 taskId 渲染详情。
  823. // 这里在删除成功后统一回收选中态和运行态,让主区域立即退出这条已删除任务。
  824. return {
  825. ...current,
  826. activeTaskId: shouldCloseDeletedTask ? null : current.activeTaskId,
  827. draftRuntime: shouldCloseDeletedTask
  828. ? { status: "idle", error: null }
  829. : current.draftRuntime,
  830. taskRuntimeByTaskId: restTaskRuntimeByTaskId,
  831. taskUiByTaskId: restTaskUiByTaskId,
  832. taskConfigOptionsByTaskId: restTaskConfigOptionsByTaskId,
  833. taskConfigOptionsStatusByTaskId: restTaskConfigOptionsStatusByTaskId,
  834. taskUnreadByTaskId: restTaskUnreadByTaskId,
  835. optimisticTaskListByTaskId: restOptimisticTaskListByTaskId,
  836. };
  837. },
  838. workspaceIdentity,
  839. );
  840. return {
  841. ...workspaceUpdate,
  842. taskNavHistory: removeTaskFromHistory(state.taskNavHistory, taskId),
  843. };
  844. });
  845. },
  846. };
  847. }