zcodeSessionStore.test.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. BUILTIN_MODEL_PROVIDER_IDS,
  4. buildCustomSupplierKey,
  5. type ZCodeError,
  6. type ZCodeConfigOption,
  7. type ZCodePermissionRequest,
  8. type ZCodeTaskMeta,
  9. } from "@zcode/shared";
  10. import {
  11. DEFAULT_TASK_UI_STATE,
  12. DEFAULT_TASK_RUNTIME_STATE,
  13. getTaskRuntimeState,
  14. getTaskUnreadIndicator,
  15. getTaskUiState,
  16. getWorkspaceDisplayedTaskState,
  17. useZCodeSessionStore,
  18. } from "../src/store/zcodeSessionStore.js";
  19. import { canGoForward } from "../src/lib/taskNavigationHistory.js";
  20. import { LAST_SELECTED_AGENT_PROVIDER_STORAGE_KEY } from "../src/lib/zcodeProviderPreference.js";
  21. import { encodeCustomModelValue } from "../src/lib/zcodeCustomModelValue.js";
  22. function createStorageMock(initial: Record<string, string> = {}) {
  23. const data = new Map(Object.entries(initial));
  24. return {
  25. getItem(key: string) {
  26. return data.get(key) ?? null;
  27. },
  28. setItem(key: string, value: string) {
  29. data.set(key, value);
  30. },
  31. removeItem(key: string) {
  32. data.delete(key);
  33. },
  34. };
  35. }
  36. function createTaskMeta(overrides: Partial<ZCodeTaskMeta> = {}): ZCodeTaskMeta {
  37. return {
  38. taskId: "task-1",
  39. traceId: "trace-1",
  40. title: "修复任务删除联动",
  41. workspacePath: "/tmp/workspace-delete",
  42. createdAt: 1,
  43. updatedAt: 1,
  44. mode: "default",
  45. provider: "codex",
  46. ...overrides,
  47. };
  48. }
  49. function createPermissionRequest(
  50. overrides: Partial<ZCodePermissionRequest> = {},
  51. ): ZCodePermissionRequest {
  52. return {
  53. type: "permission_request",
  54. taskId: "task-1",
  55. traceId: "trace-1",
  56. requestId: "perm-1",
  57. description: "允许执行命令",
  58. kind: "execute",
  59. options: [
  60. {
  61. optionId: "allow-once",
  62. kind: "allow_once",
  63. name: "允许一次",
  64. },
  65. ],
  66. raw: { toolCallId: "tool-1" },
  67. ...overrides,
  68. };
  69. }
  70. function createZCodeError(overrides: Partial<ZCodeError> = {}): ZCodeError {
  71. return {
  72. code: "SEND_FAILED",
  73. message: "命令执行失败",
  74. traceId: "trace-error-1",
  75. taskId: "task-1",
  76. ...overrides,
  77. };
  78. }
  79. function createModelConfigOption(currentValue: string): ZCodeConfigOption {
  80. return {
  81. id: "model",
  82. name: "Model",
  83. category: "model",
  84. type: "select",
  85. currentValue,
  86. options: [{ value: currentValue, name: currentValue }],
  87. };
  88. }
  89. function createModeConfigOption(currentValue: string): ZCodeConfigOption {
  90. return {
  91. id: "mode",
  92. name: "Mode",
  93. category: "mode",
  94. type: "select",
  95. currentValue,
  96. options: [
  97. { value: "build", name: "Build" },
  98. { value: "plan", name: "Plan" },
  99. { value: "yolo", name: "Yolo" },
  100. ],
  101. };
  102. }
  103. function createThoughtConfigOption(currentValue: string): ZCodeConfigOption {
  104. return {
  105. id: "thought_level",
  106. name: "Thought Level",
  107. category: "thought_level",
  108. type: "select",
  109. currentValue,
  110. options: [
  111. { value: "max", name: "Max" },
  112. { value: "high", name: "High" },
  113. { value: "nothink", name: "No Think" },
  114. ],
  115. };
  116. }
  117. function readModelConfigValue(
  118. options: readonly ZCodeConfigOption[] | null | undefined,
  119. ): string | null {
  120. const modelOption = options?.find(
  121. (option) => option.category === "model" && option.type === "select",
  122. );
  123. return typeof modelOption?.currentValue === "string" ? modelOption.currentValue : null;
  124. }
  125. function readModeConfigOption(options: readonly ZCodeConfigOption[] | null | undefined) {
  126. return options?.find((option) => option.category === "mode" && option.type === "select") ?? null;
  127. }
  128. describe("useZCodeSessionStore provider preference", () => {
  129. beforeEach(() => {
  130. useZCodeSessionStore.setState((state) => ({
  131. ...state,
  132. workspaces: {},
  133. }));
  134. });
  135. afterEach(() => {
  136. vi.restoreAllMocks();
  137. vi.unstubAllGlobals();
  138. });
  139. it("setConfigOptions 会把空 thought_level 归一到第一个合法选项", () => {
  140. const workspacePath = "/tmp/workspace-thought-normalize";
  141. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  142. {
  143. id: "thought_level",
  144. name: "Thought Level",
  145. category: "thought_level",
  146. type: "select",
  147. currentValue: "",
  148. options: [
  149. { value: "low", name: "Low" },
  150. { value: "medium", name: "Medium" },
  151. ],
  152. },
  153. ]);
  154. expect(
  155. useZCodeSessionStore
  156. .getState()
  157. .getWorkspaceState(workspacePath)
  158. .configOptions?.find((option) => option.id === "thought_level")?.currentValue,
  159. ).toBe("low");
  160. });
  161. it.each([
  162. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan, "glm-5.2-pro"],
  163. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan, "GLM-5.2"],
  164. ["default-glm", "glm-0606[1m]"],
  165. ])("setConfigOptions 保留 %s/%s 的 high 思考强度", (providerId, modelId) => {
  166. const workspacePath = `/tmp/workspace-hide-high-${providerId}-${modelId}`;
  167. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  168. createModelConfigOption(`${providerId}/${modelId}`),
  169. {
  170. id: "thought_level",
  171. name: "Thought Level",
  172. category: "thought_level",
  173. type: "select",
  174. currentValue: "high",
  175. options: [
  176. { value: "max", name: "Max" },
  177. { value: "high", name: "High" },
  178. { value: "nothink", name: "No Thinking" },
  179. ],
  180. },
  181. ]);
  182. const thoughtOption = useZCodeSessionStore
  183. .getState()
  184. .getWorkspaceState(workspacePath)
  185. .configOptions?.find((option) => option.id === "thought_level");
  186. expect(thoughtOption?.options?.map((option) => option.value)).toEqual([
  187. "max",
  188. "high",
  189. "nothink",
  190. ]);
  191. expect(thoughtOption?.currentValue).toBe("high");
  192. });
  193. it("setConfigOptions 保留无 provider 的 glm-date 模型 high 思考强度", () => {
  194. const workspacePath = "/tmp/workspace-hide-high-plain-glm-date";
  195. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  196. createModelConfigOption("glm-0606[1m]"),
  197. {
  198. id: "thought_level",
  199. name: "Thought Level",
  200. category: "thought_level",
  201. type: "select",
  202. currentValue: "high",
  203. options: [
  204. { value: "max", name: "Max" },
  205. { value: "high", name: "High" },
  206. { value: "nothink", name: "No Thinking" },
  207. ],
  208. },
  209. ]);
  210. const thoughtOption = useZCodeSessionStore
  211. .getState()
  212. .getWorkspaceState(workspacePath)
  213. .configOptions?.find((option) => option.id === "thought_level");
  214. expect(thoughtOption?.options?.map((option) => option.value)).toEqual([
  215. "max",
  216. "high",
  217. "nothink",
  218. ]);
  219. expect(thoughtOption?.currentValue).toBe("high");
  220. });
  221. it("bindRuntimeProvider 会归一旧 provider,不覆盖 supplier 且不改本地偏好", () => {
  222. const storage = createStorageMock();
  223. vi.stubGlobal("window", { localStorage: storage });
  224. const workspacePath = "/tmp/workspace-runtime-bind";
  225. const customSupplierKey = buildCustomSupplierKey("provider-a");
  226. useZCodeSessionStore.getState().startDraft(workspacePath, "codex");
  227. useZCodeSessionStore.getState().setModelSelectionResolution(workspacePath, {
  228. selectedSupplierKey: customSupplierKey,
  229. isGhostSupplier: false,
  230. supplierMismatchReason: null,
  231. });
  232. useZCodeSessionStore.getState().bindRuntimeProvider(workspacePath, "opencode");
  233. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  234. expect(storage.getItem(LAST_SELECTED_AGENT_PROVIDER_STORAGE_KEY)).toBe("glm");
  235. expect(workspaceState.selectedProvider).toBe("glm");
  236. expect(workspaceState.selectedSupplierKey).toBe(customSupplierKey);
  237. });
  238. it("composer 文本插入请求按 workspaceIdentity 隔离且只能由对应版本清理", () => {
  239. const workspacePath = "/tmp/workspace-composer-prefill";
  240. const workspaceIdentityA = "ssh://user@host-a:/tmp/workspace-composer-prefill";
  241. const workspaceIdentityB = "ssh://user@host-b:/tmp/workspace-composer-prefill";
  242. const store = useZCodeSessionStore.getState();
  243. expect(store.requestComposerTextInsert(workspacePath, "first", workspaceIdentityA)).toBe(1);
  244. expect(
  245. store.requestComposerTextInsert(workspacePath, "second", workspaceIdentityA, {
  246. id: "plugin:demo@mkt",
  247. category: "plugins",
  248. label: "Demo",
  249. value: "demo@mkt",
  250. markdown: "[@Demo](plugin://demo@mkt)",
  251. data: {
  252. pluginId: "demo@mkt",
  253. icon: "https://cdn.example.com/demo.png",
  254. },
  255. }),
  256. ).toBe(2);
  257. store.requestComposerTextInsert(workspacePath, "isolated", workspaceIdentityB);
  258. store.requestComposerTextInsert(
  259. workspacePath,
  260. "[@Demo](plugin://demo@mkt)",
  261. workspaceIdentityA,
  262. {
  263. id: "plugin:demo@mkt",
  264. category: "plugins",
  265. label: "Demo",
  266. value: "demo@mkt",
  267. markdown: "[@Demo](plugin://demo@mkt)",
  268. data: { pluginId: "demo@mkt" },
  269. },
  270. "prepend-if-missing",
  271. );
  272. expect(
  273. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  274. .composerTextInsertRequest,
  275. ).toEqual({
  276. requestId: 3,
  277. text: "[@Demo](plugin://demo@mkt)",
  278. mention: {
  279. id: "plugin:demo@mkt",
  280. category: "plugins",
  281. label: "Demo",
  282. value: "demo@mkt",
  283. markdown: "[@Demo](plugin://demo@mkt)",
  284. data: {
  285. pluginId: "demo@mkt",
  286. },
  287. },
  288. mode: "prepend-if-missing",
  289. });
  290. expect(
  291. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityB)
  292. .composerTextInsertRequest,
  293. ).toEqual({ requestId: 1, text: "isolated" });
  294. useZCodeSessionStore
  295. .getState()
  296. .clearComposerTextInsertRequest(workspacePath, 1, workspaceIdentityA);
  297. expect(
  298. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  299. .composerTextInsertRequest,
  300. ).toEqual(expect.objectContaining({ requestId: 3, mode: "prepend-if-missing" }));
  301. useZCodeSessionStore
  302. .getState()
  303. .clearComposerTextInsertRequest(workspacePath, 2, workspaceIdentityA);
  304. expect(
  305. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  306. .composerTextInsertRequest,
  307. ).toEqual(expect.objectContaining({ requestId: 3, mode: "prepend-if-missing" }));
  308. useZCodeSessionStore
  309. .getState()
  310. .clearComposerTextInsertRequest(workspacePath, 3, workspaceIdentityA);
  311. expect(
  312. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  313. .composerTextInsertRequest,
  314. ).toBeNull();
  315. });
  316. it("时间线到底请求即使目标 task 未切换也会递增,并且只能由对应版本清理", () => {
  317. const workspacePath = "/tmp/workspace-timeline-bottom";
  318. const workspaceIdentity = "ssh://user@host:/tmp/workspace-timeline-bottom";
  319. const store = useZCodeSessionStore.getState();
  320. expect(store.requestTimelineBottom(workspacePath, "task-1", workspaceIdentity)).toBe(1);
  321. expect(store.requestTimelineBottom(workspacePath, "task-1", workspaceIdentity)).toBe(2);
  322. expect(
  323. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  324. .timelineBottomRequest,
  325. ).toEqual({ requestId: 2, taskId: "task-1" });
  326. store.clearTimelineBottomRequest(workspacePath, 1, workspaceIdentity);
  327. expect(
  328. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  329. .timelineBottomRequest,
  330. ).toEqual({ requestId: 2, taskId: "task-1" });
  331. store.clearTimelineBottomRequest(workspacePath, 2, workspaceIdentity);
  332. expect(
  333. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  334. .timelineBottomRequest,
  335. ).toBeNull();
  336. });
  337. it("bindRuntimeProvider 在同路径不同 workspaceIdentity 下不应互相覆盖 supplier", () => {
  338. const workspacePath = "/tmp/workspace-runtime-identity";
  339. const workspaceIdentityA = "ssh://user@host-a:/tmp/workspace-runtime-identity";
  340. const workspaceIdentityB = "ssh://user@host-b:/tmp/workspace-runtime-identity";
  341. const customSupplierKeyA = buildCustomSupplierKey("provider-a");
  342. const customSupplierKeyB = buildCustomSupplierKey("provider-b");
  343. useZCodeSessionStore.getState().startDraft(workspacePath, "claude", workspaceIdentityA);
  344. useZCodeSessionStore.getState().setModelSelectionResolution(
  345. workspacePath,
  346. {
  347. selectedSupplierKey: customSupplierKeyA,
  348. isGhostSupplier: false,
  349. supplierMismatchReason: null,
  350. },
  351. workspaceIdentityA,
  352. );
  353. useZCodeSessionStore
  354. .getState()
  355. .bindRuntimeProvider(workspacePath, "claude", workspaceIdentityA);
  356. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode", workspaceIdentityB);
  357. useZCodeSessionStore.getState().setModelSelectionResolution(
  358. workspacePath,
  359. {
  360. selectedSupplierKey: customSupplierKeyB,
  361. isGhostSupplier: false,
  362. supplierMismatchReason: null,
  363. },
  364. workspaceIdentityB,
  365. );
  366. useZCodeSessionStore
  367. .getState()
  368. .bindRuntimeProvider(workspacePath, "opencode", workspaceIdentityB);
  369. expect(
  370. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  371. .selectedSupplierKey,
  372. ).toBe(customSupplierKeyA);
  373. expect(
  374. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityB)
  375. .selectedSupplierKey,
  376. ).toBe(customSupplierKeyB);
  377. });
  378. it("同一 remote workspace overlay 连续读取时应复用同一个快照引用", () => {
  379. const workspacePath = "/tmp/workspace-identity-overlay-snapshot";
  380. const workspaceIdentity = "ssh://user@host:/tmp/workspace-identity-overlay-snapshot";
  381. // M5②:旧 selectDraftProvider 的"归一后 no-op 不写 identity 桶"路径已随动作删除;
  382. // 这里保留 identity 读取回落 path 桶时快照引用复用的存活语义。
  383. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode");
  384. const firstSnapshot = useZCodeSessionStore
  385. .getState()
  386. .getWorkspaceState(workspacePath, workspaceIdentity);
  387. const secondSnapshot = useZCodeSessionStore
  388. .getState()
  389. .getWorkspaceState(workspacePath, workspaceIdentity);
  390. expect(firstSnapshot.selectedProvider).toBe("glm");
  391. expect(firstSnapshot).toBe(secondSnapshot);
  392. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, "task-1", true);
  393. const thirdSnapshot = useZCodeSessionStore
  394. .getState()
  395. .getWorkspaceState(workspacePath, workspaceIdentity);
  396. expect(thirdSnapshot).not.toBe(firstSnapshot);
  397. expect(thirdSnapshot.selectedProvider).toBe("glm");
  398. expect(thirdSnapshot.taskUnreadByTaskId["task-1"]).toBe(true);
  399. });
  400. it("关闭分组草稿只清除当前 identity 的内存分组,不重建草稿或污染同路径", () => {
  401. const store = useZCodeSessionStore.getState();
  402. const path = "/group-draft";
  403. const identity = "remote:server:other:/group-draft";
  404. store.startDraft(path, undefined, undefined, { projectId: "local", taskGroupId: "local-g" });
  405. store.startDraft(path, undefined, identity, { projectId: "remote", taskGroupId: "remote-g" });
  406. const local = useZCodeSessionStore.getState().getWorkspaceState(path);
  407. const remote = useZCodeSessionStore.getState().getWorkspaceState(path, identity);
  408. store.clearDraftTaskGroup(path, identity);
  409. expect(useZCodeSessionStore.getState().getWorkspaceState(path)).toBe(local);
  410. expect(useZCodeSessionStore.getState().getWorkspaceState(path, identity)).toEqual({
  411. ...remote,
  412. draftTaskGroupId: undefined,
  413. });
  414. });
  415. it("同 cwd 切换草稿项目只重建预热实例,已提交任务不改变归属", () => {
  416. const store = useZCodeSessionStore.getState();
  417. const path = "/project-draft";
  418. store.startDraft(path, undefined, undefined, { projectId: "a" });
  419. const first = useZCodeSessionStore.getState().getWorkspaceState(path);
  420. expect(first.draftProjectId).toBe("a");
  421. store.startDraft(path, undefined, undefined, { projectId: "a" });
  422. expect(
  423. useZCodeSessionStore.getState().getWorkspaceState(path).draftRuntimeInvalidationVersion,
  424. ).toBe(first.draftRuntimeInvalidationVersion);
  425. store.startDraft(path, undefined, undefined, { projectId: "b" });
  426. expect(useZCodeSessionStore.getState().getWorkspaceState(path)).toMatchObject({
  427. draftProjectId: "b",
  428. draftRuntimeInvalidationVersion: first.draftRuntimeInvalidationVersion + 1,
  429. });
  430. store.startDraft(path, undefined, undefined, { projectId: null });
  431. expect(useZCodeSessionStore.getState().getWorkspaceState(path).draftProjectId).toBeNull();
  432. });
  433. it("workspaceIdentity overlay 应优先读取 identity 桶的瞬时状态", () => {
  434. const workspacePath = "/tmp/workspace-remote-transient-state";
  435. const workspaceIdentity =
  436. "remote:ssh:localhost:2222:root:/tmp/workspace-remote-transient-state";
  437. const taskId = "task-remote-transient";
  438. const identityOptions = [createModelConfigOption("glm-identity")];
  439. const pathOptions = [createModelConfigOption("glm-path")];
  440. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, workspaceIdentity);
  441. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, workspaceIdentity);
  442. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath, workspaceIdentity);
  443. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath, workspaceIdentity);
  444. useZCodeSessionStore
  445. .getState()
  446. .setTaskConfigOptions(workspacePath, taskId, identityOptions, workspaceIdentity);
  447. useZCodeSessionStore
  448. .getState()
  449. .setTaskUnreadIndicator(workspacePath, taskId, true, workspaceIdentity);
  450. useZCodeSessionStore.getState().startDraft(workspacePath);
  451. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath);
  452. useZCodeSessionStore.getState().setTaskConfigOptions(workspacePath, taskId, pathOptions);
  453. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  454. const workspaceState = useZCodeSessionStore
  455. .getState()
  456. .getWorkspaceState(workspacePath, workspaceIdentity);
  457. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(
  458. "glm-identity",
  459. );
  460. expect(workspaceState.taskUnreadByTaskId[taskId]).toBe(true);
  461. expect(workspaceState.taskListVersion).toBe(2);
  462. expect(workspaceState.draftFocusVersion).toBe(2);
  463. });
  464. it("startDraft 传入同 provider 时不应把 custom supplier 重置为 native", () => {
  465. const workspacePath = "/tmp/workspace-draft-same-provider";
  466. const customSupplierKey = buildCustomSupplierKey("provider-a");
  467. useZCodeSessionStore.getState().startDraft(workspacePath, "claude");
  468. useZCodeSessionStore.getState().setModelSelectionResolution(workspacePath, {
  469. selectedSupplierKey: customSupplierKey,
  470. isGhostSupplier: false,
  471. supplierMismatchReason: null,
  472. });
  473. useZCodeSessionStore.getState().startDraft(workspacePath, "claude");
  474. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  475. expect(workspaceState.selectedProvider).toBe("glm");
  476. expect(workspaceState.selectedSupplierKey).toBe(customSupplierKey);
  477. });
  478. it("startDraft 会递增草稿聚焦版本,供输入框在新建任务后立即聚焦", () => {
  479. const storage = createStorageMock();
  480. vi.stubGlobal("window", { localStorage: storage });
  481. const workspacePath = "/tmp/workspace-focus";
  482. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  483. 0,
  484. );
  485. useZCodeSessionStore.getState().startDraft(workspacePath);
  486. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  487. 1,
  488. );
  489. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode");
  490. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  491. 2,
  492. );
  493. });
  494. it("startDraft 从 active task 新建且透传同 provider 时会继承输入框完整配置", () => {
  495. const workspacePath = "/tmp/workspace-new-task-inherit-active-config";
  496. const taskId = "task-provider-a";
  497. const taskModel = "provider-a/model-a";
  498. const workspaceModel = "account:bigmodel-individual-coding-plan/GLM-5.2";
  499. useZCodeSessionStore
  500. .getState()
  501. .setConfigOptions(workspacePath, [createModelConfigOption(workspaceModel)]);
  502. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  503. useZCodeSessionStore
  504. .getState()
  505. .setTaskConfigOptions(workspacePath, taskId, [
  506. createModelConfigOption(taskModel),
  507. createModeConfigOption("yolo"),
  508. createThoughtConfigOption("max"),
  509. ]);
  510. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  511. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  512. expect(workspaceState.activeTaskId).toBeNull();
  513. expect(readModelConfigValue(workspaceState.configOptions)).toBe(taskModel);
  514. expect(readModeConfigOption(workspaceState.configOptions)?.currentValue).toBe("yolo");
  515. expect(
  516. workspaceState.configOptions?.find((option) => option.category === "thought_level")
  517. ?.currentValue,
  518. ).toBe("max");
  519. });
  520. it("草稿态重复点击新建任务时不应清空 slashCommands", () => {
  521. const workspacePath = "/tmp/workspace-draft-slash-commands";
  522. const slashCommands = [
  523. { name: "status", description: "查看当前状态" },
  524. { name: "review", description: "发起代码审查" },
  525. ];
  526. useZCodeSessionStore.getState().setSlashCommands(workspacePath, slashCommands);
  527. useZCodeSessionStore.getState().startDraft(workspacePath);
  528. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands).toEqual(
  529. slashCommands,
  530. );
  531. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-from-list");
  532. useZCodeSessionStore.getState().startDraft(workspacePath);
  533. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands).toEqual(
  534. [],
  535. );
  536. });
  537. it("workspaceIdentity 会隔离 workspace 级命令、初始化与模型切换状态", () => {
  538. const workspacePath = "/tmp/workspace-same-path-state";
  539. const identityA = "ssh://host-a/tmp/workspace-same-path-state";
  540. const identityB = "ssh://host-b/tmp/workspace-same-path-state";
  541. const slashCommands = [{ name: "review", description: "发起代码审查" }];
  542. useZCodeSessionStore.getState().setSlashCommands(workspacePath, slashCommands, identityA);
  543. useZCodeSessionStore.getState().setWorkspaceInitState(workspacePath, "ready", null, identityA);
  544. useZCodeSessionStore
  545. .getState()
  546. .startModelSwitch(workspacePath, "switch-a", "settingModel", identityA);
  547. const workspaceStateA = useZCodeSessionStore
  548. .getState()
  549. .getWorkspaceState(workspacePath, identityA);
  550. const workspaceStateB = useZCodeSessionStore
  551. .getState()
  552. .getWorkspaceState(workspacePath, identityB);
  553. expect(workspaceStateA.slashCommands).toEqual(slashCommands);
  554. expect(workspaceStateB.slashCommands).toEqual([]);
  555. expect(workspaceStateA.workspaceInit.status).toBe("ready");
  556. expect(workspaceStateB.workspaceInit.status).toBe("idle");
  557. expect(workspaceStateA.modelSwitchRequestId).toBe("switch-a");
  558. expect(workspaceStateA.modelSwitchPending).toBe(true);
  559. expect(workspaceStateB.modelSwitchRequestId).toBeNull();
  560. expect(workspaceStateB.modelSwitchPending).toBe(false);
  561. });
  562. it("workspaceIdentity 已存在时不再动态合并 path 桶里的 task config", () => {
  563. const workspacePath = "/tmp/workspace-same-path-model-config";
  564. const identityA = "ssh://host-a/tmp/workspace-same-path-model-config";
  565. const identityB = "ssh://host-b/tmp/workspace-same-path-model-config";
  566. useZCodeSessionStore
  567. .getState()
  568. .setTaskConfigOptions(workspacePath, "task-1", [createModelConfigOption("glm-path")]);
  569. useZCodeSessionStore.getState().startDraft(workspacePath, "glm", identityA);
  570. useZCodeSessionStore
  571. .getState()
  572. .setConfigOptions(workspacePath, [createModelConfigOption("glm-identity-b")], identityB);
  573. useZCodeSessionStore
  574. .getState()
  575. .setTaskConfigOptions(
  576. workspacePath,
  577. "task-1",
  578. [createModelConfigOption("glm-identity-a")],
  579. identityA,
  580. );
  581. expect(
  582. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, identityA)
  583. .taskConfigOptionsByTaskId["task-1"]?.[0]?.currentValue,
  584. ).toBe("glm-identity-a");
  585. expect(
  586. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, identityB)
  587. .taskConfigOptionsByTaskId["task-1"],
  588. ).toBeUndefined();
  589. });
  590. it("workspaceIdentity 首次写入只迁移明确属于该 identity 的 path task 状态", () => {
  591. const workspacePath = "/tmp/workspace-same-path-task-cache";
  592. const workspaceIdentity = "ssh://host-a/tmp/workspace-same-path-task-cache";
  593. const otherWorkspaceIdentity = "ssh://host-b/tmp/workspace-same-path-task-cache";
  594. const taskId = "identity-task";
  595. const otherTaskId = "other-task";
  596. useZCodeSessionStore.getState().setTaskListCache(workspacePath, [
  597. createTaskMeta({
  598. taskId,
  599. workspacePath,
  600. workspaceIdentity,
  601. model: "glm-path",
  602. }),
  603. createTaskMeta({
  604. taskId: otherTaskId,
  605. workspacePath,
  606. workspaceIdentity: otherWorkspaceIdentity,
  607. model: "glm-other",
  608. }),
  609. ]);
  610. useZCodeSessionStore
  611. .getState()
  612. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption("glm-path")]);
  613. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  614. useZCodeSessionStore
  615. .getState()
  616. .setTaskError(workspacePath, taskId, createZCodeError({ taskId }));
  617. useZCodeSessionStore
  618. .getState()
  619. .setTaskConfigOptions(workspacePath, otherTaskId, [createModelConfigOption("glm-other")]);
  620. useZCodeSessionStore
  621. .getState()
  622. .setConfigOptions(
  623. workspacePath,
  624. [createModelConfigOption("glm-identity")],
  625. workspaceIdentity,
  626. );
  627. const workspaceState = useZCodeSessionStore
  628. .getState()
  629. .getWorkspaceState(workspacePath, workspaceIdentity);
  630. expect(workspaceState.configOptions?.[0]?.currentValue).toBe("glm-identity");
  631. expect(workspaceState.taskListCache?.map((task) => task.taskId)).toEqual([taskId]);
  632. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe("glm-path");
  633. expect(getTaskRuntimeState(workspaceState, taskId).status).toBe("streaming");
  634. expect(getTaskUiState(workspaceState, taskId).error?.message).toBe("命令执行失败");
  635. expect(workspaceState.taskConfigOptionsByTaskId[otherTaskId]).toBeUndefined();
  636. });
  637. it("modelSwitch 状态只允许最新 requestId 生效与收敛", () => {
  638. const workspacePath = "/tmp/workspace-model-switch";
  639. const requestId1 = "switch-1";
  640. const requestId2 = "switch-2";
  641. useZCodeSessionStore.getState().startModelSwitch(workspacePath, requestId1, "settingModel");
  642. useZCodeSessionStore
  643. .getState()
  644. .updateModelSwitchStage(workspacePath, requestId1, "restartingRuntime");
  645. useZCodeSessionStore.getState().startModelSwitch(workspacePath, requestId2, "syncingSession");
  646. // 旧请求结束不应覆盖新请求状态
  647. useZCodeSessionStore.getState().finishModelSwitch(workspacePath, requestId1);
  648. let workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  649. expect(workspaceState.modelSwitchPending).toBe(true);
  650. expect(workspaceState.modelSwitchRequestId).toBe(requestId2);
  651. expect(workspaceState.modelSwitchStage).toBe("syncingSession");
  652. // 当前请求结束后才回到 idle
  653. useZCodeSessionStore.getState().finishModelSwitch(workspacePath, requestId2);
  654. workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  655. expect(workspaceState.modelSwitchPending).toBe(false);
  656. expect(workspaceState.modelSwitchRequestId).toBeNull();
  657. expect(workspaceState.modelSwitchStage).toBe("idle");
  658. });
  659. it("removeTaskState 删除当前任务时会同步关闭右侧详情态", () => {
  660. const workspacePath = "/tmp/workspace-delete";
  661. const taskId = "task-active";
  662. useZCodeSessionStore
  663. .getState()
  664. .upsertOptimisticTaskListItem(workspacePath, createTaskMeta({ taskId, workspacePath }));
  665. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  666. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  667. useZCodeSessionStore.getState().removeTaskState(workspacePath, taskId);
  668. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  669. expect(workspaceState.activeTaskId).toBeNull();
  670. expect(getWorkspaceDisplayedTaskState(workspaceState).taskStatus).toBe("idle");
  671. expect(getWorkspaceDisplayedTaskState(workspaceState).taskError).toBeNull();
  672. expect(workspaceState.optimisticTaskListByTaskId[taskId]).toBeUndefined();
  673. expect(workspaceState.taskRuntimeByTaskId[taskId]).toBeUndefined();
  674. });
  675. it("权限请求会按 task 维度保存,切换任务后仍可恢复", () => {
  676. const workspacePath = "/tmp/workspace-task-ui";
  677. const firstTaskId = "task-plan";
  678. const secondTaskId = "task-empty";
  679. const permissionRequest = createPermissionRequest({ taskId: firstTaskId });
  680. useZCodeSessionStore
  681. .getState()
  682. .setTaskPermissionRequest(workspacePath, firstTaskId, permissionRequest);
  683. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  684. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, secondTaskId);
  685. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  686. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  687. expect(getTaskUiState(workspaceState, firstTaskId)).toEqual({
  688. ...DEFAULT_TASK_UI_STATE,
  689. permissionRequest,
  690. });
  691. expect(getTaskUiState(workspaceState, secondTaskId)).toEqual(DEFAULT_TASK_UI_STATE);
  692. });
  693. it("问答草稿会按 workspace、task 和 request 隔离,并可在请求收口后清理", () => {
  694. const workspacePath = "/tmp/workspace-elicitation-draft";
  695. const firstTaskId = "task-a";
  696. const secondTaskId = "task-b";
  697. const requestId = "ask-1";
  698. const workspaceIdentity = "ssh://host-a/workspace";
  699. const draft = {
  700. questionIndex: 1,
  701. drafts: {
  702. "0:方案": { selectedValues: ["safe"], customAnswer: "" },
  703. },
  704. };
  705. useZCodeSessionStore
  706. .getState()
  707. .setTaskElicitationFormDraft(workspacePath, firstTaskId, requestId, draft, workspaceIdentity);
  708. let workspaceState = useZCodeSessionStore
  709. .getState()
  710. .getWorkspaceState(workspacePath, workspaceIdentity);
  711. expect(
  712. getTaskUiState(workspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  713. ).toEqual(draft);
  714. expect(
  715. getTaskUiState(workspaceState, secondTaskId).elicitationFormDraftsByRequestId[requestId],
  716. ).toBeUndefined();
  717. const otherWorkspaceState = useZCodeSessionStore
  718. .getState()
  719. .getWorkspaceState(workspacePath, "ssh://host-b/workspace");
  720. expect(
  721. getTaskUiState(otherWorkspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  722. ).toBeUndefined();
  723. useZCodeSessionStore
  724. .getState()
  725. .removeTaskElicitationFormDraft(workspacePath, firstTaskId, requestId, workspaceIdentity);
  726. workspaceState = useZCodeSessionStore
  727. .getState()
  728. .getWorkspaceState(workspacePath, workspaceIdentity);
  729. expect(
  730. getTaskUiState(workspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  731. ).toBeUndefined();
  732. });
  733. it("连续收到多个权限请求时会按顺序排队,响应当前请求后自动切到下一条", () => {
  734. const workspacePath = "/tmp/workspace-task-permission-queue";
  735. const taskId = "task-permission-queue";
  736. const firstPermissionRequest = createPermissionRequest({
  737. taskId,
  738. requestId: "perm-1",
  739. description: "允许读取 about.txt",
  740. });
  741. const secondPermissionRequest = createPermissionRequest({
  742. taskId,
  743. requestId: "perm-2",
  744. description: "允许读取 setting.json",
  745. });
  746. useZCodeSessionStore
  747. .getState()
  748. .setTaskPermissionRequest(workspacePath, taskId, firstPermissionRequest);
  749. useZCodeSessionStore
  750. .getState()
  751. .setTaskPermissionRequest(workspacePath, taskId, secondPermissionRequest);
  752. let workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  753. expect(getTaskUiState(workspaceState, taskId)).toEqual({
  754. ...DEFAULT_TASK_UI_STATE,
  755. permissionRequest: firstPermissionRequest,
  756. pendingPermissionRequests: [secondPermissionRequest],
  757. });
  758. useZCodeSessionStore.getState().removeTaskPermissionRequest(workspacePath, taskId, "perm-1");
  759. workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  760. expect(getTaskUiState(workspaceState, taskId)).toEqual({
  761. ...DEFAULT_TASK_UI_STATE,
  762. permissionRequest: secondPermissionRequest,
  763. });
  764. });
  765. it("重复收到相同权限请求时不会重建 task UI state", () => {
  766. const workspacePath = "/tmp/workspace-task-permission-duplicate";
  767. const taskId = "task-permission-duplicate";
  768. const firstPermissionRequest = createPermissionRequest({ taskId, requestId: "perm-duplicate" });
  769. const duplicatePermissionRequest = createPermissionRequest({
  770. taskId,
  771. requestId: "perm-duplicate",
  772. });
  773. useZCodeSessionStore
  774. .getState()
  775. .setTaskPermissionRequest(workspacePath, taskId, firstPermissionRequest);
  776. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  777. const firstTaskUiState = getTaskUiState(firstWorkspaceState, taskId);
  778. useZCodeSessionStore
  779. .getState()
  780. .setTaskPermissionRequest(workspacePath, taskId, duplicatePermissionRequest);
  781. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  782. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  783. expect(getTaskUiState(secondWorkspaceState, taskId)).toBe(firstTaskUiState);
  784. });
  785. it("重复清理已移除的权限请求时不会重建 task UI state", () => {
  786. const workspacePath = "/tmp/workspace-task-permission-response-duplicate";
  787. const taskId = "task-permission-response-duplicate";
  788. const permissionRequest = createPermissionRequest({ taskId, requestId: "perm-response" });
  789. useZCodeSessionStore
  790. .getState()
  791. .setTaskPermissionRequest(workspacePath, taskId, permissionRequest);
  792. useZCodeSessionStore
  793. .getState()
  794. .removeTaskPermissionRequest(workspacePath, taskId, "perm-response");
  795. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  796. useZCodeSessionStore
  797. .getState()
  798. .removeTaskPermissionRequest(workspacePath, taskId, "perm-response");
  799. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  800. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  801. });
  802. it("task 错误会按 task 维度保存在内存里,切换任务后仍可恢复", () => {
  803. const workspacePath = "/tmp/workspace-task-error";
  804. const firstTaskId = "task-error";
  805. const secondTaskId = "task-other";
  806. const error = createZCodeError({ taskId: firstTaskId });
  807. useZCodeSessionStore.getState().setTaskError(workspacePath, firstTaskId, error);
  808. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  809. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, secondTaskId);
  810. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  811. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  812. expect(getTaskUiState(workspaceState, firstTaskId).error).toEqual(error);
  813. expect(getTaskUiState(workspaceState, secondTaskId).error).toBeNull();
  814. });
  815. it("草稿态错误会保留在 workspace 内存里,并在重新新建草稿时清空", () => {
  816. const workspacePath = "/tmp/workspace-draft-error";
  817. const error = createZCodeError({ taskId: undefined });
  818. useZCodeSessionStore.getState().setDraftError(workspacePath, error);
  819. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftError).toEqual(
  820. error,
  821. );
  822. useZCodeSessionStore.getState().startDraft(workspacePath);
  823. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftError).toBeNull();
  824. });
  825. it("当前 task 被右键标记未读后,再次打开会同时清掉 optimistic 蓝点", () => {
  826. const workspacePath = "/tmp/workspace-task-read";
  827. const taskId = "task-unread";
  828. useZCodeSessionStore
  829. .getState()
  830. .upsertOptimisticTaskListItem(workspacePath, createTaskMeta({ taskId, workspacePath }));
  831. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  832. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, true);
  833. useZCodeSessionStore
  834. .getState()
  835. .upsertOptimisticTaskListItem(
  836. workspacePath,
  837. createTaskMeta({ taskId, workspacePath, unreadAt: 123 }),
  838. );
  839. expect(
  840. getTaskUnreadIndicator(
  841. useZCodeSessionStore.getState().getWorkspaceState(workspacePath),
  842. taskId,
  843. ),
  844. ).toBe(true);
  845. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  846. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  847. expect(getTaskUnreadIndicator(workspaceState, taskId)).toBe(false);
  848. expect(workspaceState.optimisticTaskListByTaskId[taskId]?.unreadAt).toBeUndefined();
  849. });
  850. it("重复清理已读 task 时不会重建 workspace state", () => {
  851. const workspacePath = "/tmp/workspace-task-read-noop";
  852. const taskId = "task-unread-noop";
  853. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, true);
  854. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  855. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  856. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  857. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  858. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  859. });
  860. it("切到已有 task 时会用 task meta 预热 task 配置,且不覆盖 workspace 默认配置", () => {
  861. const workspacePath = "/tmp/workspace-task-model-preload";
  862. const taskId = "task-glm51";
  863. const staleWorkspaceModel = "glm-0531[1m]";
  864. const taskModel = "bigmodel-api/GLM-5.1";
  865. useZCodeSessionStore
  866. .getState()
  867. .setConfigOptions(workspacePath, [createModelConfigOption(staleWorkspaceModel)]);
  868. useZCodeSessionStore.getState().upsertOptimisticTaskListItem(
  869. workspacePath,
  870. createTaskMeta({
  871. taskId,
  872. workspacePath,
  873. provider: "glm",
  874. model: taskModel,
  875. }),
  876. );
  877. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  878. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  879. expect(readModelConfigValue(workspaceState.configOptions)).toBe(staleWorkspaceModel);
  880. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(
  881. encodeCustomModelValue("bigmodel-api", "GLM-5.1"),
  882. );
  883. expect(workspaceState.taskConfigOptionsStatusByTaskId[taskId]).toBe("loading");
  884. });
  885. it("active task 配置更新只写 task 配置桶,不覆盖 workspace 默认配置", () => {
  886. const workspacePath = "/tmp/workspace-task-config-isolation";
  887. const taskId = "task-active-config";
  888. const workspaceModel = "glm-0531[1m]";
  889. const taskModel = "bigmodel-api/GLM-5.1";
  890. useZCodeSessionStore
  891. .getState()
  892. .setConfigOptions(workspacePath, [createModelConfigOption(workspaceModel)]);
  893. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  894. useZCodeSessionStore
  895. .getState()
  896. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(taskModel)]);
  897. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  898. expect(readModelConfigValue(workspaceState.configOptions)).toBe(workspaceModel);
  899. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(taskModel);
  900. expect(workspaceState.taskConfigOptionsStatusByTaskId[taskId]).toBe("ready");
  901. });
  902. it("相同 workspace 配置不会重复通知订阅者", () => {
  903. const workspacePath = "/tmp/workspace-config-options-dedupe";
  904. const modelValue = "account:zai-start-plan/GLM-5.2";
  905. let notificationCount = 0;
  906. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  907. notificationCount += 1;
  908. });
  909. useZCodeSessionStore
  910. .getState()
  911. .setConfigOptions(workspacePath, [createModelConfigOption(modelValue)]);
  912. expect(notificationCount).toBe(1);
  913. useZCodeSessionStore
  914. .getState()
  915. .setConfigOptions(workspacePath, [createModelConfigOption(modelValue)]);
  916. unsubscribe();
  917. expect(notificationCount).toBe(1);
  918. });
  919. it("相同 task 配置不会重复通知订阅者", () => {
  920. const workspacePath = "/tmp/workspace-task-config-options-dedupe";
  921. const taskId = "task-config-dedupe";
  922. const modelValue = "account:zai-start-plan/GLM-5.2";
  923. let notificationCount = 0;
  924. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  925. notificationCount += 1;
  926. });
  927. useZCodeSessionStore
  928. .getState()
  929. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(modelValue)]);
  930. expect(notificationCount).toBe(1);
  931. useZCodeSessionStore
  932. .getState()
  933. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(modelValue)]);
  934. unsubscribe();
  935. expect(notificationCount).toBe(1);
  936. });
  937. it("任务前进后退选择目标时不会覆盖浏览器式历史位置", () => {
  938. const workspacePath = "/tmp/workspace-task-nav";
  939. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-a");
  940. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-b");
  941. const backEntry = useZCodeSessionStore.getState().taskNavGoBack();
  942. expect(backEntry?.taskId).toBe("task-a");
  943. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-a");
  944. expect(canGoForward(useZCodeSessionStore.getState().taskNavHistory)).toBe(true);
  945. expect(useZCodeSessionStore.getState().taskNavGoForward()?.taskId).toBe("task-b");
  946. });
  947. it("removeTaskState 会同时清理 task 级权限请求", () => {
  948. const workspacePath = "/tmp/workspace-remove-task-ui";
  949. const taskId = "task-remove-ui";
  950. useZCodeSessionStore
  951. .getState()
  952. .setTaskPermissionRequest(workspacePath, taskId, createPermissionRequest({ taskId }));
  953. useZCodeSessionStore.getState().removeTaskState(workspacePath, taskId);
  954. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  955. expect(workspaceState.taskUiByTaskId[taskId]).toBeUndefined();
  956. });
  957. it("task usage 会按 task 保存,切换运行态时不丢失", () => {
  958. const workspacePath = "/tmp/workspace-task-usage";
  959. const taskId = "task-usage";
  960. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  961. used: 53000,
  962. size: 200000,
  963. cost: { amount: 0.045, currency: "USD" },
  964. });
  965. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  966. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "completed");
  967. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  968. expect(getTaskRuntimeState(workspaceState, taskId)).toEqual({
  969. ...DEFAULT_TASK_RUNTIME_STATE,
  970. status: "completed",
  971. error: null,
  972. apiRetry: null,
  973. usage: {
  974. used: 53000,
  975. size: 200000,
  976. cost: { amount: 0.045, currency: "USD" },
  977. },
  978. });
  979. });
  980. it("task contextWindow 单独更新,不覆盖已有 usage", () => {
  981. const workspacePath = "/tmp/workspace-task-context-window";
  982. const taskId = "task-context-window";
  983. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  984. used: 11804,
  985. size: 200000,
  986. cost: null,
  987. cache: {
  988. inputTokens: 100,
  989. cacheReadTokens: 40,
  990. cacheWriteTokens: 0,
  991. hitRate: 0.4,
  992. },
  993. breakdown: [{ source: "messages", chars: 1200 }],
  994. });
  995. useZCodeSessionStore.getState().setTaskContextWindow(workspacePath, taskId, 1000000);
  996. const runtime = getTaskRuntimeState(
  997. useZCodeSessionStore.getState().getWorkspaceState(workspacePath),
  998. taskId,
  999. );
  1000. expect(runtime.contextWindow).toBe(1000000);
  1001. expect(runtime.usage).toEqual({
  1002. used: 11804,
  1003. size: 200000,
  1004. cost: null,
  1005. cache: {
  1006. inputTokens: 100,
  1007. cacheReadTokens: 40,
  1008. cacheWriteTokens: 0,
  1009. hitRate: 0.4,
  1010. },
  1011. breakdown: [{ source: "messages", chars: 1200 }],
  1012. });
  1013. });
  1014. it("相同 task usage 不重复通知订阅者", () => {
  1015. const workspacePath = "/tmp/workspace-task-usage-dedupe";
  1016. const taskId = "task-usage-dedupe";
  1017. let notificationCount = 0;
  1018. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  1019. notificationCount += 1;
  1020. });
  1021. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1022. used: 53000,
  1023. size: 200000,
  1024. cost: { amount: 0.045, currency: "USD" },
  1025. });
  1026. expect(notificationCount).toBe(1);
  1027. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1028. used: 53000,
  1029. size: 200000,
  1030. cost: { amount: 0.045, currency: "USD" },
  1031. });
  1032. unsubscribe();
  1033. expect(notificationCount).toBe(1);
  1034. });
  1035. it("configOptionsStatus 写入 workspace identity 时不污染 path 桶", () => {
  1036. const workspacePath = "/tmp/workspace-config-status-identity";
  1037. const workspaceIdentity = "ssh://host-a/tmp/workspace-config-status-identity";
  1038. useZCodeSessionStore.getState().setConfigOptionsStatus(workspacePath, "loading");
  1039. useZCodeSessionStore
  1040. .getState()
  1041. .setConfigOptionsStatus(workspacePath, "error", workspaceIdentity);
  1042. expect(
  1043. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).configOptionsStatus,
  1044. ).toBe("loading");
  1045. expect(
  1046. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  1047. .configOptionsStatus,
  1048. ).toBe("error");
  1049. });
  1050. });