zcodeSessionStore.test.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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 createComposerDraft(
  80. overrides: Pick<ComposerDraftState, "text"> & Partial<ComposerDraftState>,
  81. ): ComposerDraftState {
  82. return {
  83. attachments: [],
  84. codeCommentAttachments: [],
  85. webElementContexts: [],
  86. ...overrides,
  87. };
  88. }
  89. function createModelConfigOption(currentValue: string): ZCodeConfigOption {
  90. return {
  91. id: "model",
  92. name: "Model",
  93. category: "model",
  94. type: "select",
  95. currentValue,
  96. options: [{ value: currentValue, name: currentValue }],
  97. };
  98. }
  99. function createModeConfigOption(currentValue: string): ZCodeConfigOption {
  100. return {
  101. id: "mode",
  102. name: "Mode",
  103. category: "mode",
  104. type: "select",
  105. currentValue,
  106. options: [
  107. { value: "build", name: "Build" },
  108. { value: "plan", name: "Plan" },
  109. { value: "yolo", name: "Yolo" },
  110. ],
  111. };
  112. }
  113. function createThoughtConfigOption(currentValue: string): ZCodeConfigOption {
  114. return {
  115. id: "thought_level",
  116. name: "Thought Level",
  117. category: "thought_level",
  118. type: "select",
  119. currentValue,
  120. options: [
  121. { value: "max", name: "Max" },
  122. { value: "high", name: "High" },
  123. { value: "nothink", name: "No Think" },
  124. ],
  125. };
  126. }
  127. function readModelConfigValue(
  128. options: readonly ZCodeConfigOption[] | null | undefined,
  129. ): string | null {
  130. const modelOption = options?.find(
  131. (option) => option.category === "model" && option.type === "select",
  132. );
  133. return typeof modelOption?.currentValue === "string" ? modelOption.currentValue : null;
  134. }
  135. function readModeConfigOption(options: readonly ZCodeConfigOption[] | null | undefined) {
  136. return options?.find((option) => option.category === "mode" && option.type === "select") ?? null;
  137. }
  138. describe("useZCodeSessionStore provider preference", () => {
  139. beforeEach(() => {
  140. useZCodeSessionStore.setState((state) => ({
  141. ...state,
  142. workspaces: {},
  143. }));
  144. });
  145. afterEach(() => {
  146. vi.restoreAllMocks();
  147. vi.unstubAllGlobals();
  148. });
  149. it("新 workspace 会把旧 provider 偏好归一为 glm", () => {
  150. const storage = createStorageMock({
  151. [LAST_SELECTED_AGENT_PROVIDER_STORAGE_KEY]: "codex",
  152. });
  153. vi.stubGlobal("window", { localStorage: storage });
  154. const workspaceState = useZCodeSessionStore
  155. .getState()
  156. .getWorkspaceState("/tmp/workspace-codex");
  157. expect(workspaceState.selectedProvider).toBe("glm");
  158. });
  159. it("setConfigOptions 会把空 thought_level 归一到第一个合法选项", () => {
  160. const workspacePath = "/tmp/workspace-thought-normalize";
  161. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  162. {
  163. id: "thought_level",
  164. name: "Thought Level",
  165. category: "thought_level",
  166. type: "select",
  167. currentValue: "",
  168. options: [
  169. { value: "low", name: "Low" },
  170. { value: "medium", name: "Medium" },
  171. ],
  172. },
  173. ]);
  174. expect(
  175. useZCodeSessionStore
  176. .getState()
  177. .getWorkspaceState(workspacePath)
  178. .configOptions?.find((option) => option.id === "thought_level")?.currentValue,
  179. ).toBe("low");
  180. });
  181. it.each([
  182. [BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan, "glm-5.2-pro"],
  183. [BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan, "GLM-5.2"],
  184. ["default-glm", "glm-0606[1m]"],
  185. ])("setConfigOptions 保留 %s/%s 的 high 思考强度", (providerId, modelId) => {
  186. const workspacePath = `/tmp/workspace-hide-high-${providerId}-${modelId}`;
  187. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  188. createModelConfigOption(`${providerId}/${modelId}`),
  189. {
  190. id: "thought_level",
  191. name: "Thought Level",
  192. category: "thought_level",
  193. type: "select",
  194. currentValue: "high",
  195. options: [
  196. { value: "max", name: "Max" },
  197. { value: "high", name: "High" },
  198. { value: "nothink", name: "No Thinking" },
  199. ],
  200. },
  201. ]);
  202. const thoughtOption = useZCodeSessionStore
  203. .getState()
  204. .getWorkspaceState(workspacePath)
  205. .configOptions?.find((option) => option.id === "thought_level");
  206. expect(thoughtOption?.options?.map((option) => option.value)).toEqual([
  207. "max",
  208. "high",
  209. "nothink",
  210. ]);
  211. expect(thoughtOption?.currentValue).toBe("high");
  212. });
  213. it("setConfigOptions 保留无 provider 的 glm-date 模型 high 思考强度", () => {
  214. const workspacePath = "/tmp/workspace-hide-high-plain-glm-date";
  215. useZCodeSessionStore.getState().setConfigOptions(workspacePath, [
  216. createModelConfigOption("glm-0606[1m]"),
  217. {
  218. id: "thought_level",
  219. name: "Thought Level",
  220. category: "thought_level",
  221. type: "select",
  222. currentValue: "high",
  223. options: [
  224. { value: "max", name: "Max" },
  225. { value: "high", name: "High" },
  226. { value: "nothink", name: "No Thinking" },
  227. ],
  228. },
  229. ]);
  230. const thoughtOption = useZCodeSessionStore
  231. .getState()
  232. .getWorkspaceState(workspacePath)
  233. .configOptions?.find((option) => option.id === "thought_level");
  234. expect(thoughtOption?.options?.map((option) => option.value)).toEqual([
  235. "max",
  236. "high",
  237. "nothink",
  238. ]);
  239. expect(thoughtOption?.currentValue).toBe("high");
  240. });
  241. it("bindRuntimeProvider 会归一旧 provider,不覆盖 supplier 且不改本地偏好", () => {
  242. const storage = createStorageMock();
  243. vi.stubGlobal("window", { localStorage: storage });
  244. const workspacePath = "/tmp/workspace-runtime-bind";
  245. const customSupplierKey = buildCustomSupplierKey("provider-a");
  246. useZCodeSessionStore.getState().startDraft(workspacePath, "codex");
  247. useZCodeSessionStore.getState().setModelSelectionResolution(workspacePath, {
  248. selectedSupplierKey: customSupplierKey,
  249. isGhostSupplier: false,
  250. supplierMismatchReason: null,
  251. });
  252. useZCodeSessionStore.getState().bindRuntimeProvider(workspacePath, "opencode");
  253. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  254. expect(storage.getItem(LAST_SELECTED_AGENT_PROVIDER_STORAGE_KEY)).toBe("glm");
  255. expect(workspaceState.selectedProvider).toBe("glm");
  256. expect(workspaceState.selectedSupplierKey).toBe(customSupplierKey);
  257. });
  258. it("同路径不同 workspaceIdentity 输入旧 provider 时都应归一为 glm", () => {
  259. const workspacePath = "/tmp/workspace-identity-isolation";
  260. const workspaceIdentityA = "ssh://user@host-a:/tmp/workspace-identity-isolation";
  261. const workspaceIdentityB = "ssh://user@host-b:/tmp/workspace-identity-isolation";
  262. useZCodeSessionStore.getState().startDraft(workspacePath, "claude", workspaceIdentityA);
  263. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode", workspaceIdentityB);
  264. expect(
  265. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  266. .selectedProvider,
  267. ).toBe("glm");
  268. expect(
  269. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityB)
  270. .selectedProvider,
  271. ).toBe("glm");
  272. });
  273. it("composer 文本插入请求按 workspaceIdentity 隔离且只能由对应版本清理", () => {
  274. const workspacePath = "/tmp/workspace-composer-prefill";
  275. const workspaceIdentityA = "ssh://user@host-a:/tmp/workspace-composer-prefill";
  276. const workspaceIdentityB = "ssh://user@host-b:/tmp/workspace-composer-prefill";
  277. const store = useZCodeSessionStore.getState();
  278. expect(store.requestComposerTextInsert(workspacePath, "first", workspaceIdentityA)).toBe(1);
  279. expect(
  280. store.requestComposerTextInsert(workspacePath, "second", workspaceIdentityA, {
  281. id: "plugin:demo@mkt",
  282. category: "plugins",
  283. label: "Demo",
  284. value: "demo@mkt",
  285. markdown: "[@Demo](plugin://demo@mkt)",
  286. data: {
  287. pluginId: "demo@mkt",
  288. icon: "https://cdn.example.com/demo.png",
  289. },
  290. }),
  291. ).toBe(2);
  292. store.requestComposerTextInsert(workspacePath, "isolated", workspaceIdentityB);
  293. store.requestComposerTextInsert(
  294. workspacePath,
  295. "[@Demo](plugin://demo@mkt)",
  296. workspaceIdentityA,
  297. {
  298. id: "plugin:demo@mkt",
  299. category: "plugins",
  300. label: "Demo",
  301. value: "demo@mkt",
  302. markdown: "[@Demo](plugin://demo@mkt)",
  303. data: { pluginId: "demo@mkt" },
  304. },
  305. "prepend-if-missing",
  306. );
  307. expect(
  308. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  309. .composerTextInsertRequest,
  310. ).toEqual({
  311. requestId: 3,
  312. text: "[@Demo](plugin://demo@mkt)",
  313. mention: {
  314. id: "plugin:demo@mkt",
  315. category: "plugins",
  316. label: "Demo",
  317. value: "demo@mkt",
  318. markdown: "[@Demo](plugin://demo@mkt)",
  319. data: {
  320. pluginId: "demo@mkt",
  321. },
  322. },
  323. mode: "prepend-if-missing",
  324. });
  325. expect(
  326. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityB)
  327. .composerTextInsertRequest,
  328. ).toEqual({ requestId: 1, text: "isolated" });
  329. useZCodeSessionStore
  330. .getState()
  331. .clearComposerTextInsertRequest(workspacePath, 1, workspaceIdentityA);
  332. expect(
  333. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  334. .composerTextInsertRequest,
  335. ).toEqual(expect.objectContaining({ requestId: 3, mode: "prepend-if-missing" }));
  336. useZCodeSessionStore
  337. .getState()
  338. .clearComposerTextInsertRequest(workspacePath, 2, workspaceIdentityA);
  339. expect(
  340. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  341. .composerTextInsertRequest,
  342. ).toEqual(expect.objectContaining({ requestId: 3, mode: "prepend-if-missing" }));
  343. useZCodeSessionStore
  344. .getState()
  345. .clearComposerTextInsertRequest(workspacePath, 3, workspaceIdentityA);
  346. expect(
  347. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  348. .composerTextInsertRequest,
  349. ).toBeNull();
  350. });
  351. it("时间线到底请求即使目标 task 未切换也会递增,并且只能由对应版本清理", () => {
  352. const workspacePath = "/tmp/workspace-timeline-bottom";
  353. const workspaceIdentity = "ssh://user@host:/tmp/workspace-timeline-bottom";
  354. const store = useZCodeSessionStore.getState();
  355. expect(store.requestTimelineBottom(workspacePath, "task-1", workspaceIdentity)).toBe(1);
  356. expect(store.requestTimelineBottom(workspacePath, "task-1", workspaceIdentity)).toBe(2);
  357. expect(
  358. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  359. .timelineBottomRequest,
  360. ).toEqual({ requestId: 2, taskId: "task-1" });
  361. store.clearTimelineBottomRequest(workspacePath, 1, workspaceIdentity);
  362. expect(
  363. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  364. .timelineBottomRequest,
  365. ).toEqual({ requestId: 2, taskId: "task-1" });
  366. store.clearTimelineBottomRequest(workspacePath, 2, workspaceIdentity);
  367. expect(
  368. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  369. .timelineBottomRequest,
  370. ).toBeNull();
  371. });
  372. it("bindRuntimeProvider 在同路径不同 workspaceIdentity 下不应互相覆盖 supplier", () => {
  373. const workspacePath = "/tmp/workspace-runtime-identity";
  374. const workspaceIdentityA = "ssh://user@host-a:/tmp/workspace-runtime-identity";
  375. const workspaceIdentityB = "ssh://user@host-b:/tmp/workspace-runtime-identity";
  376. const customSupplierKeyA = buildCustomSupplierKey("provider-a");
  377. const customSupplierKeyB = buildCustomSupplierKey("provider-b");
  378. useZCodeSessionStore.getState().startDraft(workspacePath, "claude", workspaceIdentityA);
  379. useZCodeSessionStore.getState().setModelSelectionResolution(
  380. workspacePath,
  381. {
  382. selectedSupplierKey: customSupplierKeyA,
  383. isGhostSupplier: false,
  384. supplierMismatchReason: null,
  385. },
  386. workspaceIdentityA,
  387. );
  388. useZCodeSessionStore
  389. .getState()
  390. .bindRuntimeProvider(workspacePath, "claude", workspaceIdentityA);
  391. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode", workspaceIdentityB);
  392. useZCodeSessionStore.getState().setModelSelectionResolution(
  393. workspacePath,
  394. {
  395. selectedSupplierKey: customSupplierKeyB,
  396. isGhostSupplier: false,
  397. supplierMismatchReason: null,
  398. },
  399. workspaceIdentityB,
  400. );
  401. useZCodeSessionStore
  402. .getState()
  403. .bindRuntimeProvider(workspacePath, "opencode", workspaceIdentityB);
  404. expect(
  405. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityA)
  406. .selectedSupplierKey,
  407. ).toBe(customSupplierKeyA);
  408. expect(
  409. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentityB)
  410. .selectedSupplierKey,
  411. ).toBe(customSupplierKeyB);
  412. });
  413. it("同一 remote workspace overlay 连续读取时应复用同一个快照引用", () => {
  414. const workspacePath = "/tmp/workspace-identity-overlay-snapshot";
  415. const workspaceIdentity = "ssh://user@host:/tmp/workspace-identity-overlay-snapshot";
  416. // M5②:旧 selectDraftProvider 的"归一后 no-op 不写 identity 桶"路径已随动作删除;
  417. // 这里保留 identity 读取回落 path 桶时快照引用复用的存活语义。
  418. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode");
  419. const firstSnapshot = useZCodeSessionStore
  420. .getState()
  421. .getWorkspaceState(workspacePath, workspaceIdentity);
  422. const secondSnapshot = useZCodeSessionStore
  423. .getState()
  424. .getWorkspaceState(workspacePath, workspaceIdentity);
  425. expect(firstSnapshot.selectedProvider).toBe("glm");
  426. expect(firstSnapshot).toBe(secondSnapshot);
  427. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, "task-1", true);
  428. const thirdSnapshot = useZCodeSessionStore
  429. .getState()
  430. .getWorkspaceState(workspacePath, workspaceIdentity);
  431. expect(thirdSnapshot).not.toBe(firstSnapshot);
  432. expect(thirdSnapshot.selectedProvider).toBe("glm");
  433. expect(thirdSnapshot.taskUnreadByTaskId["task-1"]).toBe(true);
  434. });
  435. it("workspaceIdentity overlay 应优先使用 identity 桶的 draftSessionId", () => {
  436. const workspacePath = "/tmp/workspace-remote-draft-session";
  437. const workspaceIdentity = "remote:ssh:localhost:2222:root:/tmp/workspace-remote-draft-session";
  438. useZCodeSessionStore.getState().setDraftSessionId(workspacePath, "sess-path-stale");
  439. useZCodeSessionStore
  440. .getState()
  441. .setDraftSessionId(workspacePath, "sess-identity-current", workspaceIdentity);
  442. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftSessionId).toBe(
  443. "sess-path-stale",
  444. );
  445. expect(
  446. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  447. .draftSessionId,
  448. ).toBe("sess-identity-current");
  449. });
  450. it("workspaceIdentity overlay 应优先读取 identity 桶的瞬时状态", () => {
  451. const workspacePath = "/tmp/workspace-remote-transient-state";
  452. const workspaceIdentity =
  453. "remote:ssh:localhost:2222:root:/tmp/workspace-remote-transient-state";
  454. const taskId = "task-remote-transient";
  455. const identityOptions = [createModelConfigOption("glm-identity")];
  456. const pathOptions = [createModelConfigOption("glm-path")];
  457. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, workspaceIdentity);
  458. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, workspaceIdentity);
  459. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath, workspaceIdentity);
  460. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath, workspaceIdentity);
  461. useZCodeSessionStore
  462. .getState()
  463. .setTaskConfigOptions(workspacePath, taskId, identityOptions, workspaceIdentity);
  464. useZCodeSessionStore
  465. .getState()
  466. .setTaskUnreadIndicator(workspacePath, taskId, true, workspaceIdentity);
  467. useZCodeSessionStore.getState().startDraft(workspacePath);
  468. useZCodeSessionStore.getState().bumpTaskListVersion(workspacePath);
  469. useZCodeSessionStore.getState().setTaskConfigOptions(workspacePath, taskId, pathOptions);
  470. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  471. const workspaceState = useZCodeSessionStore
  472. .getState()
  473. .getWorkspaceState(workspacePath, workspaceIdentity);
  474. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(
  475. "glm-identity",
  476. );
  477. expect(workspaceState.taskUnreadByTaskId[taskId]).toBe(true);
  478. expect(workspaceState.taskListVersion).toBe(2);
  479. expect(workspaceState.draftFocusVersion).toBe(2);
  480. });
  481. it("startDraft 选择旧 provider 时也会立即归一最近一次选择", () => {
  482. const storage = createStorageMock();
  483. vi.stubGlobal("window", { localStorage: storage });
  484. useZCodeSessionStore.getState().startDraft("/tmp/workspace-draft", "codex");
  485. expect(storage.getItem(LAST_SELECTED_AGENT_PROVIDER_STORAGE_KEY)).toBe("glm");
  486. expect(
  487. useZCodeSessionStore.getState().getWorkspaceState("/tmp/workspace-draft").selectedProvider,
  488. ).toBe("glm");
  489. });
  490. it("startDraft 传入同 provider 时不应把 custom supplier 重置为 native", () => {
  491. const workspacePath = "/tmp/workspace-draft-same-provider";
  492. const customSupplierKey = buildCustomSupplierKey("provider-a");
  493. useZCodeSessionStore.getState().startDraft(workspacePath, "claude");
  494. useZCodeSessionStore.getState().setModelSelectionResolution(workspacePath, {
  495. selectedSupplierKey: customSupplierKey,
  496. isGhostSupplier: false,
  497. supplierMismatchReason: null,
  498. });
  499. useZCodeSessionStore.getState().startDraft(workspacePath, "claude");
  500. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  501. expect(workspaceState.selectedProvider).toBe("glm");
  502. expect(workspaceState.selectedSupplierKey).toBe(customSupplierKey);
  503. });
  504. it("startDraft 会递增草稿聚焦版本,供输入框在新建任务后立即聚焦", () => {
  505. const storage = createStorageMock();
  506. vi.stubGlobal("window", { localStorage: storage });
  507. const workspacePath = "/tmp/workspace-focus";
  508. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  509. 0,
  510. );
  511. useZCodeSessionStore.getState().startDraft(workspacePath);
  512. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  513. 1,
  514. );
  515. useZCodeSessionStore.getState().startDraft(workspacePath, "opencode");
  516. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftFocusVersion).toBe(
  517. 2,
  518. );
  519. });
  520. it("startDraft 从 active task 新建且透传同 provider 时会继承输入框完整配置", () => {
  521. const workspacePath = "/tmp/workspace-new-task-inherit-active-config";
  522. const taskId = "task-provider-a";
  523. const taskModel = "provider-a/model-a";
  524. const workspaceModel = "account:bigmodel-individual-coding-plan/GLM-5.2";
  525. useZCodeSessionStore
  526. .getState()
  527. .setConfigOptions(workspacePath, [createModelConfigOption(workspaceModel)]);
  528. useZCodeSessionStore.getState().setDraftSessionId(workspacePath, "draft-glm");
  529. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  530. useZCodeSessionStore
  531. .getState()
  532. .setTaskConfigOptions(workspacePath, taskId, [
  533. createModelConfigOption(taskModel),
  534. createModeConfigOption("yolo"),
  535. createThoughtConfigOption("max"),
  536. ]);
  537. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  538. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  539. expect(workspaceState.activeTaskId).toBeNull();
  540. expect(workspaceState.draftSessionId).toBeNull();
  541. expect(readModelConfigValue(workspaceState.configOptions)).toBe(taskModel);
  542. expect(readModeConfigOption(workspaceState.configOptions)?.currentValue).toBe("yolo");
  543. expect(
  544. workspaceState.configOptions?.find((option) => option.category === "thought_level")
  545. ?.currentValue,
  546. ).toBe("max");
  547. });
  548. it("startDraft 在 task 级缓存缺失时仍继承当前输入框配置", () => {
  549. const workspacePath = "/tmp/workspace-new-task-inherit-current-config";
  550. const taskId = "task-projection-only";
  551. const taskModel = "output-token-preflight-e2e/otb-preflight-64k";
  552. useZCodeSessionStore
  553. .getState()
  554. .setConfigOptions(workspacePath, [
  555. createModelConfigOption(taskModel),
  556. createModeConfigOption("yolo"),
  557. createThoughtConfigOption("max"),
  558. ]);
  559. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  560. // 模拟 protocol-v4 投影已经更新当前工具条,但尚未写入 legacy task 级缓存。
  561. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  562. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  563. });
  564. it("startDraft 在 task 级缓存为空时仍继承当前输入框配置", () => {
  565. const workspacePath = "/tmp/workspace-new-task-inherit-empty-task-config";
  566. const taskId = "task-projection-with-empty-cache";
  567. const taskModel = "custom-provider/custom-vision-model";
  568. useZCodeSessionStore
  569. .getState()
  570. .setConfigOptions(workspacePath, [
  571. createModelConfigOption(taskModel),
  572. createModeConfigOption("yolo"),
  573. createThoughtConfigOption("max"),
  574. ]);
  575. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  576. useZCodeSessionStore.setState((state) => ({
  577. ...state,
  578. workspaces: {
  579. ...state.workspaces,
  580. [workspacePath]: {
  581. ...state.getWorkspaceState(workspacePath),
  582. taskConfigOptionsByTaskId: { [taskId]: [] },
  583. },
  584. },
  585. }));
  586. // 模拟首轮 session 先以空目录建立,随后 protocol-v4 只更新当前工具条投影。
  587. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  588. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  589. });
  590. it("草稿目录水合不应清掉从 active task 继承的预热配置", () => {
  591. const workspacePath = "/tmp/workspace-new-task-hydration-race";
  592. const taskId = "task-custom-model";
  593. const taskModel = "custom-provider/gpt-5.6-sol";
  594. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  595. useZCodeSessionStore
  596. .getState()
  597. .setTaskConfigOptions(workspacePath, taskId, [
  598. createModelConfigOption(taskModel),
  599. createModeConfigOption("yolo"),
  600. createThoughtConfigOption("max"),
  601. ]);
  602. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  603. // 模拟新草稿 mount 后异步完成的 workspace catalog 水合。
  604. useZCodeSessionStore
  605. .getState()
  606. .setConfigOptions(workspacePath, [createModelConfigOption("glm/GLM-5.2")]);
  607. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  608. });
  609. it("grouped 草稿在不同 New task 入口之间切换时会更新创建位置", () => {
  610. const workspacePath = "/tmp/workspace-grouped-draft-placement";
  611. const nowSpy = vi.spyOn(Date, "now").mockReturnValue(1000);
  612. useZCodeSessionStore
  613. .getState()
  614. .startDraft(workspacePath, undefined, undefined, { groupedDraftPlacement: { type: "top" } });
  615. const topDraft = useZCodeSessionStore
  616. .getState()
  617. .getWorkspaceState(workspacePath).groupedDraftTask;
  618. useZCodeSessionStore
  619. .getState()
  620. .startDraft(workspacePath, undefined, undefined, { groupedDraftPlacement: { type: "top" } });
  621. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).groupedDraftTask).toBe(
  622. topDraft,
  623. );
  624. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  625. groupedDraftPlacement: { type: "group", groupId: "group-a" },
  626. });
  627. const groupDraft = useZCodeSessionStore
  628. .getState()
  629. .getWorkspaceState(workspacePath).groupedDraftTask;
  630. expect(groupDraft?.placement).toEqual({ type: "group", groupId: "group-a" });
  631. expect(groupDraft?.createdAt).toBe(1000);
  632. expect(nowSpy).toHaveBeenCalledTimes(1);
  633. nowSpy.mockRestore();
  634. });
  635. it("grouped 草稿提升位置落库后可以按 task 消费", () => {
  636. const workspacePath = "/tmp/workspace-grouped-draft-consume";
  637. const nowSpy = vi.spyOn(Date, "now").mockReturnValue(2000);
  638. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  639. groupedDraftPlacement: { type: "group", groupId: "group-a" },
  640. });
  641. const groupedDraftTask = useZCodeSessionStore
  642. .getState()
  643. .getWorkspaceState(workspacePath).groupedDraftTask;
  644. expect(groupedDraftTask).not.toBeNull();
  645. useZCodeSessionStore
  646. .getState()
  647. .promoteGroupedDraftTask(workspacePath, "task-promoted", groupedDraftTask!);
  648. expect(
  649. useZCodeSessionStore.getState().getWorkspaceState(workspacePath)
  650. .promotedGroupedDraftTaskByTaskId["task-promoted"]?.placement,
  651. ).toEqual({ type: "group", groupId: "group-a" });
  652. expect(
  653. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).optimisticTaskListByTaskId[
  654. "task-promoted"
  655. ],
  656. ).toMatchObject({
  657. taskId: "task-promoted",
  658. title: "",
  659. workspacePath,
  660. createdAt: groupedDraftTask?.createdAt,
  661. updatedAt: 0,
  662. mode: "default",
  663. });
  664. useZCodeSessionStore.getState().clearPromotedGroupedDraftTask(workspacePath, "task-promoted");
  665. expect(
  666. useZCodeSessionStore.getState().getWorkspaceState(workspacePath)
  667. .promotedGroupedDraftTaskByTaskId["task-promoted"],
  668. ).toBeUndefined();
  669. nowSpy.mockRestore();
  670. });
  671. it("旧创建请求完成时使用原草稿位置且不清除后创建的草稿", () => {
  672. const workspacePath = "/tmp/workspace-grouped-draft-interleaved-create";
  673. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  674. groupedDraftPlacement: { type: "group", groupId: "group-a" },
  675. });
  676. const originalDraft = useZCodeSessionStore
  677. .getState()
  678. .getWorkspaceState(workspacePath).groupedDraftTask;
  679. expect(originalDraft).not.toBeNull();
  680. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "existing-task");
  681. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  682. groupedDraftPlacement: { type: "group", groupId: "group-b" },
  683. });
  684. const newerDraft = useZCodeSessionStore
  685. .getState()
  686. .getWorkspaceState(workspacePath).groupedDraftTask;
  687. expect(newerDraft?.draftId).not.toBe(originalDraft?.draftId);
  688. useZCodeSessionStore
  689. .getState()
  690. .promoteGroupedDraftTask(workspacePath, "created-task-a", originalDraft!);
  691. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  692. expect(workspaceState.groupedDraftTask).toBe(newerDraft);
  693. expect(workspaceState.promotedGroupedDraftTaskByTaskId["created-task-a"]?.placement).toEqual({
  694. type: "group",
  695. groupId: "group-a",
  696. });
  697. });
  698. it("grouped 草稿提升不覆盖先于 ACK 到达的 task 元数据", () => {
  699. const workspacePath = "/tmp/workspace-grouped-draft-meta-race";
  700. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  701. groupedDraftPlacement: { type: "top" },
  702. });
  703. const groupedDraftTask = useZCodeSessionStore
  704. .getState()
  705. .getWorkspaceState(workspacePath).groupedDraftTask;
  706. const task = createTaskMeta({
  707. taskId: "task-meta-first",
  708. title: "权威标题已到达",
  709. workspacePath,
  710. createdAt: 10,
  711. updatedAt: 20,
  712. });
  713. useZCodeSessionStore.getState().upsertOptimisticTaskListItem(workspacePath, task);
  714. useZCodeSessionStore
  715. .getState()
  716. .promoteGroupedDraftTask(workspacePath, task.taskId, groupedDraftTask!);
  717. expect(
  718. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).optimisticTaskListByTaskId[
  719. task.taskId
  720. ],
  721. ).toBe(task);
  722. });
  723. it("grouped 草稿存在时选择已有任务只清除草稿,不生成提升标记", () => {
  724. const workspacePath = "/tmp/workspace-grouped-draft-existing-task-navigation";
  725. useZCodeSessionStore.getState().startDraft(workspacePath, undefined, undefined, {
  726. groupedDraftPlacement: { type: "group", groupId: "group-a" },
  727. });
  728. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "existing-root-task");
  729. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  730. expect(workspaceState.groupedDraftTask).toBeNull();
  731. expect(workspaceState.promotedGroupedDraftTaskByTaskId["existing-root-task"]).toBeUndefined();
  732. });
  733. it("切换 workspace 时可以迁移 grouped 草稿位置", () => {
  734. const sourceWorkspacePath = "/tmp/workspace-grouped-draft-source";
  735. const targetWorkspacePath = "/tmp/workspace-grouped-draft-target";
  736. const placement = { type: "group" as const, groupId: "group-a" };
  737. useZCodeSessionStore.getState().startDraft(sourceWorkspacePath, undefined, undefined, {
  738. groupedDraftPlacement: placement,
  739. });
  740. const sourceDraft = useZCodeSessionStore
  741. .getState()
  742. .getWorkspaceState(sourceWorkspacePath).groupedDraftTask;
  743. expect(sourceDraft).not.toBeNull();
  744. useZCodeSessionStore.getState().startDraft(targetWorkspacePath, undefined, undefined, {
  745. groupedDraftPlacement: sourceDraft!.placement,
  746. });
  747. // 修复原因:grouped 左侧 New task 行是创建位置,不是 workspace 本身。
  748. // 切 workspace 只迁移草稿目标,不能让左侧临时行凭空消失。
  749. useZCodeSessionStore.getState().clearGroupedDraftTask(sourceWorkspacePath);
  750. expect(
  751. useZCodeSessionStore.getState().getWorkspaceState(sourceWorkspacePath).groupedDraftTask,
  752. ).toBeNull();
  753. expect(
  754. useZCodeSessionStore.getState().getWorkspaceState(targetWorkspacePath).groupedDraftTask,
  755. ).toMatchObject({
  756. workspacePath: targetWorkspacePath,
  757. placement,
  758. });
  759. });
  760. it("草稿态重复点击新建任务时不应清空 slashCommands", () => {
  761. const workspacePath = "/tmp/workspace-draft-slash-commands";
  762. const slashCommands = [
  763. { name: "status", description: "查看当前状态" },
  764. { name: "review", description: "发起代码审查" },
  765. ];
  766. useZCodeSessionStore.getState().setSlashCommands(workspacePath, slashCommands);
  767. useZCodeSessionStore.getState().startDraft(workspacePath);
  768. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands).toEqual(
  769. slashCommands,
  770. );
  771. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-from-list");
  772. useZCodeSessionStore.getState().startDraft(workspacePath);
  773. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands).toEqual(
  774. [],
  775. );
  776. });
  777. it("workspaceIdentity 会隔离 workspace 级命令、初始化与模型切换状态", () => {
  778. const workspacePath = "/tmp/workspace-same-path-state";
  779. const identityA = "ssh://host-a/tmp/workspace-same-path-state";
  780. const identityB = "ssh://host-b/tmp/workspace-same-path-state";
  781. const slashCommands = [{ name: "review", description: "发起代码审查" }];
  782. useZCodeSessionStore.getState().setSlashCommands(workspacePath, slashCommands, identityA);
  783. useZCodeSessionStore.getState().setWorkspaceInitState(workspacePath, "ready", null, identityA);
  784. useZCodeSessionStore
  785. .getState()
  786. .startModelSwitch(workspacePath, "switch-a", "settingModel", identityA);
  787. const workspaceStateA = useZCodeSessionStore
  788. .getState()
  789. .getWorkspaceState(workspacePath, identityA);
  790. const workspaceStateB = useZCodeSessionStore
  791. .getState()
  792. .getWorkspaceState(workspacePath, identityB);
  793. expect(workspaceStateA.slashCommands).toEqual(slashCommands);
  794. expect(workspaceStateB.slashCommands).toEqual([]);
  795. expect(workspaceStateA.workspaceInit.status).toBe("ready");
  796. expect(workspaceStateB.workspaceInit.status).toBe("idle");
  797. expect(workspaceStateA.modelSwitchRequestId).toBe("switch-a");
  798. expect(workspaceStateA.modelSwitchPending).toBe(true);
  799. expect(workspaceStateB.modelSwitchRequestId).toBeNull();
  800. expect(workspaceStateB.modelSwitchPending).toBe(false);
  801. });
  802. it("workspaceIdentity 已存在时不再动态合并 path 桶里的 task config", () => {
  803. const workspacePath = "/tmp/workspace-same-path-model-config";
  804. const identityA = "ssh://host-a/tmp/workspace-same-path-model-config";
  805. const identityB = "ssh://host-b/tmp/workspace-same-path-model-config";
  806. useZCodeSessionStore
  807. .getState()
  808. .setTaskConfigOptions(workspacePath, "task-1", [createModelConfigOption("glm-path")]);
  809. useZCodeSessionStore.getState().startDraft(workspacePath, "glm", identityA);
  810. useZCodeSessionStore
  811. .getState()
  812. .setConfigOptions(workspacePath, [createModelConfigOption("glm-identity-b")], identityB);
  813. useZCodeSessionStore
  814. .getState()
  815. .setTaskConfigOptions(
  816. workspacePath,
  817. "task-1",
  818. [createModelConfigOption("glm-identity-a")],
  819. identityA,
  820. );
  821. expect(
  822. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, identityA)
  823. .taskConfigOptionsByTaskId["task-1"]?.[0]?.currentValue,
  824. ).toBe("glm-identity-a");
  825. expect(
  826. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, identityB)
  827. .taskConfigOptionsByTaskId["task-1"],
  828. ).toBeUndefined();
  829. });
  830. it("workspaceIdentity 首次写入只迁移明确属于该 identity 的 path task 状态", () => {
  831. const workspacePath = "/tmp/workspace-same-path-task-cache";
  832. const workspaceIdentity = "ssh://host-a/tmp/workspace-same-path-task-cache";
  833. const otherWorkspaceIdentity = "ssh://host-b/tmp/workspace-same-path-task-cache";
  834. const taskId = "identity-task";
  835. const otherTaskId = "other-task";
  836. useZCodeSessionStore.getState().setTaskListCache(workspacePath, [
  837. createTaskMeta({
  838. taskId,
  839. workspacePath,
  840. workspaceIdentity,
  841. model: "glm-path",
  842. }),
  843. createTaskMeta({
  844. taskId: otherTaskId,
  845. workspacePath,
  846. workspaceIdentity: otherWorkspaceIdentity,
  847. model: "glm-other",
  848. }),
  849. ]);
  850. useZCodeSessionStore
  851. .getState()
  852. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption("glm-path")]);
  853. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  854. useZCodeSessionStore
  855. .getState()
  856. .setTaskError(workspacePath, taskId, createZCodeError({ taskId }));
  857. useZCodeSessionStore
  858. .getState()
  859. .setTaskConfigOptions(workspacePath, otherTaskId, [createModelConfigOption("glm-other")]);
  860. useZCodeSessionStore
  861. .getState()
  862. .setConfigOptions(
  863. workspacePath,
  864. [createModelConfigOption("glm-identity")],
  865. workspaceIdentity,
  866. );
  867. const workspaceState = useZCodeSessionStore
  868. .getState()
  869. .getWorkspaceState(workspacePath, workspaceIdentity);
  870. expect(workspaceState.configOptions?.[0]?.currentValue).toBe("glm-identity");
  871. expect(workspaceState.taskListCache?.map((task) => task.taskId)).toEqual([taskId]);
  872. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe("glm-path");
  873. expect(getTaskRuntimeState(workspaceState, taskId).status).toBe("streaming");
  874. expect(getTaskUiState(workspaceState, taskId).error?.message).toBe("命令执行失败");
  875. expect(workspaceState.taskConfigOptionsByTaskId[otherTaskId]).toBeUndefined();
  876. });
  877. it("modelSwitch 状态只允许最新 requestId 生效与收敛", () => {
  878. const workspacePath = "/tmp/workspace-model-switch";
  879. const requestId1 = "switch-1";
  880. const requestId2 = "switch-2";
  881. useZCodeSessionStore.getState().startModelSwitch(workspacePath, requestId1, "settingModel");
  882. useZCodeSessionStore
  883. .getState()
  884. .updateModelSwitchStage(workspacePath, requestId1, "restartingRuntime");
  885. useZCodeSessionStore.getState().startModelSwitch(workspacePath, requestId2, "syncingSession");
  886. // 旧请求结束不应覆盖新请求状态
  887. useZCodeSessionStore.getState().finishModelSwitch(workspacePath, requestId1);
  888. let workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  889. expect(workspaceState.modelSwitchPending).toBe(true);
  890. expect(workspaceState.modelSwitchRequestId).toBe(requestId2);
  891. expect(workspaceState.modelSwitchStage).toBe("syncingSession");
  892. // 当前请求结束后才回到 idle
  893. useZCodeSessionStore.getState().finishModelSwitch(workspacePath, requestId2);
  894. workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  895. expect(workspaceState.modelSwitchPending).toBe(false);
  896. expect(workspaceState.modelSwitchRequestId).toBeNull();
  897. expect(workspaceState.modelSwitchStage).toBe("idle");
  898. });
  899. it("removeTaskState 删除当前任务时会同步关闭右侧详情态", () => {
  900. const workspacePath = "/tmp/workspace-delete";
  901. const taskId = "task-active";
  902. useZCodeSessionStore
  903. .getState()
  904. .upsertOptimisticTaskListItem(workspacePath, createTaskMeta({ taskId, workspacePath }));
  905. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  906. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  907. useZCodeSessionStore.getState().removeTaskState(workspacePath, taskId);
  908. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  909. expect(workspaceState.activeTaskId).toBeNull();
  910. expect(getWorkspaceDisplayedTaskState(workspaceState).taskStatus).toBe("idle");
  911. expect(getWorkspaceDisplayedTaskState(workspaceState).taskError).toBeNull();
  912. expect(workspaceState.optimisticTaskListByTaskId[taskId]).toBeUndefined();
  913. expect(workspaceState.taskRuntimeByTaskId[taskId]).toBeUndefined();
  914. });
  915. it("权限请求会按 task 维度保存,切换任务后仍可恢复", () => {
  916. const workspacePath = "/tmp/workspace-task-ui";
  917. const firstTaskId = "task-plan";
  918. const secondTaskId = "task-empty";
  919. const permissionRequest = createPermissionRequest({ taskId: firstTaskId });
  920. useZCodeSessionStore
  921. .getState()
  922. .setTaskPermissionRequest(workspacePath, firstTaskId, permissionRequest);
  923. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  924. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, secondTaskId);
  925. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  926. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  927. expect(getTaskUiState(workspaceState, firstTaskId)).toEqual({
  928. ...DEFAULT_TASK_UI_STATE,
  929. permissionRequest,
  930. });
  931. expect(getTaskUiState(workspaceState, secondTaskId)).toEqual(DEFAULT_TASK_UI_STATE);
  932. });
  933. it("问答草稿会按 workspace、task 和 request 隔离,并可在请求收口后清理", () => {
  934. const workspacePath = "/tmp/workspace-elicitation-draft";
  935. const firstTaskId = "task-a";
  936. const secondTaskId = "task-b";
  937. const requestId = "ask-1";
  938. const workspaceIdentity = "ssh://host-a/workspace";
  939. const draft = {
  940. questionIndex: 1,
  941. drafts: {
  942. "0:方案": { selectedValues: ["safe"], customAnswer: "" },
  943. },
  944. };
  945. useZCodeSessionStore
  946. .getState()
  947. .setTaskElicitationFormDraft(workspacePath, firstTaskId, requestId, draft, workspaceIdentity);
  948. let workspaceState = useZCodeSessionStore
  949. .getState()
  950. .getWorkspaceState(workspacePath, workspaceIdentity);
  951. expect(
  952. getTaskUiState(workspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  953. ).toEqual(draft);
  954. expect(
  955. getTaskUiState(workspaceState, secondTaskId).elicitationFormDraftsByRequestId[requestId],
  956. ).toBeUndefined();
  957. const otherWorkspaceState = useZCodeSessionStore
  958. .getState()
  959. .getWorkspaceState(workspacePath, "ssh://host-b/workspace");
  960. expect(
  961. getTaskUiState(otherWorkspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  962. ).toBeUndefined();
  963. useZCodeSessionStore
  964. .getState()
  965. .removeTaskElicitationFormDraft(workspacePath, firstTaskId, requestId, workspaceIdentity);
  966. workspaceState = useZCodeSessionStore
  967. .getState()
  968. .getWorkspaceState(workspacePath, workspaceIdentity);
  969. expect(
  970. getTaskUiState(workspaceState, firstTaskId).elicitationFormDraftsByRequestId[requestId],
  971. ).toBeUndefined();
  972. });
  973. it("连续收到多个权限请求时会按顺序排队,响应当前请求后自动切到下一条", () => {
  974. const workspacePath = "/tmp/workspace-task-permission-queue";
  975. const taskId = "task-permission-queue";
  976. const firstPermissionRequest = createPermissionRequest({
  977. taskId,
  978. requestId: "perm-1",
  979. description: "允许读取 about.txt",
  980. });
  981. const secondPermissionRequest = createPermissionRequest({
  982. taskId,
  983. requestId: "perm-2",
  984. description: "允许读取 setting.json",
  985. });
  986. useZCodeSessionStore
  987. .getState()
  988. .setTaskPermissionRequest(workspacePath, taskId, firstPermissionRequest);
  989. useZCodeSessionStore
  990. .getState()
  991. .setTaskPermissionRequest(workspacePath, taskId, secondPermissionRequest);
  992. let workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  993. expect(getTaskUiState(workspaceState, taskId)).toEqual({
  994. ...DEFAULT_TASK_UI_STATE,
  995. permissionRequest: firstPermissionRequest,
  996. pendingPermissionRequests: [secondPermissionRequest],
  997. });
  998. useZCodeSessionStore.getState().removeTaskPermissionRequest(workspacePath, taskId, "perm-1");
  999. workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1000. expect(getTaskUiState(workspaceState, taskId)).toEqual({
  1001. ...DEFAULT_TASK_UI_STATE,
  1002. permissionRequest: secondPermissionRequest,
  1003. });
  1004. });
  1005. it("重复收到相同权限请求时不会重建 task UI state", () => {
  1006. const workspacePath = "/tmp/workspace-task-permission-duplicate";
  1007. const taskId = "task-permission-duplicate";
  1008. const firstPermissionRequest = createPermissionRequest({ taskId, requestId: "perm-duplicate" });
  1009. const duplicatePermissionRequest = createPermissionRequest({
  1010. taskId,
  1011. requestId: "perm-duplicate",
  1012. });
  1013. useZCodeSessionStore
  1014. .getState()
  1015. .setTaskPermissionRequest(workspacePath, taskId, firstPermissionRequest);
  1016. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1017. const firstTaskUiState = getTaskUiState(firstWorkspaceState, taskId);
  1018. useZCodeSessionStore
  1019. .getState()
  1020. .setTaskPermissionRequest(workspacePath, taskId, duplicatePermissionRequest);
  1021. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1022. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  1023. expect(getTaskUiState(secondWorkspaceState, taskId)).toBe(firstTaskUiState);
  1024. });
  1025. it("重复清理已移除的权限请求时不会重建 task UI state", () => {
  1026. const workspacePath = "/tmp/workspace-task-permission-response-duplicate";
  1027. const taskId = "task-permission-response-duplicate";
  1028. const permissionRequest = createPermissionRequest({ taskId, requestId: "perm-response" });
  1029. useZCodeSessionStore
  1030. .getState()
  1031. .setTaskPermissionRequest(workspacePath, taskId, permissionRequest);
  1032. useZCodeSessionStore
  1033. .getState()
  1034. .removeTaskPermissionRequest(workspacePath, taskId, "perm-response");
  1035. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1036. useZCodeSessionStore
  1037. .getState()
  1038. .removeTaskPermissionRequest(workspacePath, taskId, "perm-response");
  1039. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1040. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  1041. });
  1042. it("task 错误会按 task 维度保存在内存里,切换任务后仍可恢复", () => {
  1043. const workspacePath = "/tmp/workspace-task-error";
  1044. const firstTaskId = "task-error";
  1045. const secondTaskId = "task-other";
  1046. const error = createZCodeError({ taskId: firstTaskId });
  1047. useZCodeSessionStore.getState().setTaskError(workspacePath, firstTaskId, error);
  1048. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  1049. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, secondTaskId);
  1050. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, firstTaskId);
  1051. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1052. expect(getTaskUiState(workspaceState, firstTaskId).error).toEqual(error);
  1053. expect(getTaskUiState(workspaceState, secondTaskId).error).toBeNull();
  1054. });
  1055. it("草稿态错误会保留在 workspace 内存里,并在重新新建草稿时清空", () => {
  1056. const workspacePath = "/tmp/workspace-draft-error";
  1057. const error = createZCodeError({ taskId: undefined });
  1058. useZCodeSessionStore.getState().setDraftError(workspacePath, error);
  1059. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftError).toEqual(
  1060. error,
  1061. );
  1062. useZCodeSessionStore.getState().startDraft(workspacePath);
  1063. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).draftError).toBeNull();
  1064. });
  1065. it("当前 task 被右键标记未读后,再次打开会同时清掉 optimistic 蓝点", () => {
  1066. const workspacePath = "/tmp/workspace-task-read";
  1067. const taskId = "task-unread";
  1068. useZCodeSessionStore
  1069. .getState()
  1070. .upsertOptimisticTaskListItem(workspacePath, createTaskMeta({ taskId, workspacePath }));
  1071. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  1072. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, true);
  1073. useZCodeSessionStore
  1074. .getState()
  1075. .upsertOptimisticTaskListItem(
  1076. workspacePath,
  1077. createTaskMeta({ taskId, workspacePath, unreadAt: 123 }),
  1078. );
  1079. expect(
  1080. getTaskUnreadIndicator(
  1081. useZCodeSessionStore.getState().getWorkspaceState(workspacePath),
  1082. taskId,
  1083. ),
  1084. ).toBe(true);
  1085. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  1086. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1087. expect(getTaskUnreadIndicator(workspaceState, taskId)).toBe(false);
  1088. expect(workspaceState.optimisticTaskListByTaskId[taskId]?.unreadAt).toBeUndefined();
  1089. });
  1090. it("重复清理已读 task 时不会重建 workspace state", () => {
  1091. const workspacePath = "/tmp/workspace-task-read-noop";
  1092. const taskId = "task-unread-noop";
  1093. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, true);
  1094. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  1095. const firstWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1096. useZCodeSessionStore.getState().setTaskUnreadIndicator(workspacePath, taskId, false);
  1097. const secondWorkspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1098. expect(secondWorkspaceState).toBe(firstWorkspaceState);
  1099. });
  1100. it("切到已有 task 时会用 task meta 预热 task 配置,且不覆盖 workspace 默认配置", () => {
  1101. const workspacePath = "/tmp/workspace-task-model-preload";
  1102. const taskId = "task-glm51";
  1103. const staleWorkspaceModel = "glm-0531[1m]";
  1104. const taskModel = "bigmodel-api/GLM-5.1";
  1105. useZCodeSessionStore
  1106. .getState()
  1107. .setConfigOptions(workspacePath, [createModelConfigOption(staleWorkspaceModel)]);
  1108. useZCodeSessionStore.getState().upsertOptimisticTaskListItem(
  1109. workspacePath,
  1110. createTaskMeta({
  1111. taskId,
  1112. workspacePath,
  1113. provider: "glm",
  1114. model: taskModel,
  1115. }),
  1116. );
  1117. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  1118. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1119. expect(readModelConfigValue(workspaceState.configOptions)).toBe(staleWorkspaceModel);
  1120. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(
  1121. encodeCustomModelValue("bigmodel-api", "GLM-5.1"),
  1122. );
  1123. expect(workspaceState.taskConfigOptionsStatusByTaskId[taskId]).toBe("loading");
  1124. });
  1125. it("active task 配置更新只写 task 配置桶,不覆盖 workspace 默认配置", () => {
  1126. const workspacePath = "/tmp/workspace-task-config-isolation";
  1127. const taskId = "task-active-config";
  1128. const workspaceModel = "glm-0531[1m]";
  1129. const taskModel = "bigmodel-api/GLM-5.1";
  1130. useZCodeSessionStore
  1131. .getState()
  1132. .setConfigOptions(workspacePath, [createModelConfigOption(workspaceModel)]);
  1133. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, taskId);
  1134. useZCodeSessionStore
  1135. .getState()
  1136. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(taskModel)]);
  1137. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1138. expect(readModelConfigValue(workspaceState.configOptions)).toBe(workspaceModel);
  1139. expect(readModelConfigValue(workspaceState.taskConfigOptionsByTaskId[taskId])).toBe(taskModel);
  1140. expect(workspaceState.taskConfigOptionsStatusByTaskId[taskId]).toBe("ready");
  1141. });
  1142. it("相同 workspace 配置不会重复通知订阅者", () => {
  1143. const workspacePath = "/tmp/workspace-config-options-dedupe";
  1144. const modelValue = "account:zai-start-plan/GLM-5.2";
  1145. let notificationCount = 0;
  1146. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  1147. notificationCount += 1;
  1148. });
  1149. useZCodeSessionStore
  1150. .getState()
  1151. .setConfigOptions(workspacePath, [createModelConfigOption(modelValue)]);
  1152. expect(notificationCount).toBe(1);
  1153. useZCodeSessionStore
  1154. .getState()
  1155. .setConfigOptions(workspacePath, [createModelConfigOption(modelValue)]);
  1156. unsubscribe();
  1157. expect(notificationCount).toBe(1);
  1158. });
  1159. it("相同 task 配置不会重复通知订阅者", () => {
  1160. const workspacePath = "/tmp/workspace-task-config-options-dedupe";
  1161. const taskId = "task-config-dedupe";
  1162. const modelValue = "account:zai-start-plan/GLM-5.2";
  1163. let notificationCount = 0;
  1164. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  1165. notificationCount += 1;
  1166. });
  1167. useZCodeSessionStore
  1168. .getState()
  1169. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(modelValue)]);
  1170. expect(notificationCount).toBe(1);
  1171. useZCodeSessionStore
  1172. .getState()
  1173. .setTaskConfigOptions(workspacePath, taskId, [createModelConfigOption(modelValue)]);
  1174. unsubscribe();
  1175. expect(notificationCount).toBe(1);
  1176. });
  1177. it("任务前进后退选择目标时不会覆盖浏览器式历史位置", () => {
  1178. const workspacePath = "/tmp/workspace-task-nav";
  1179. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-a");
  1180. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-b");
  1181. const backEntry = useZCodeSessionStore.getState().taskNavGoBack();
  1182. expect(backEntry?.taskId).toBe("task-a");
  1183. useZCodeSessionStore.getState().setActiveTaskId(workspacePath, "task-a");
  1184. expect(canGoForward(useZCodeSessionStore.getState().taskNavHistory)).toBe(true);
  1185. expect(useZCodeSessionStore.getState().taskNavGoForward()?.taskId).toBe("task-b");
  1186. });
  1187. it("removeTaskState 会同时清理 task 级权限请求", () => {
  1188. const workspacePath = "/tmp/workspace-remove-task-ui";
  1189. const taskId = "task-remove-ui";
  1190. useZCodeSessionStore
  1191. .getState()
  1192. .setTaskPermissionRequest(workspacePath, taskId, createPermissionRequest({ taskId }));
  1193. useZCodeSessionStore.getState().removeTaskState(workspacePath, taskId);
  1194. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1195. expect(workspaceState.taskUiByTaskId[taskId]).toBeUndefined();
  1196. });
  1197. it("task usage 会按 task 保存,切换运行态时不丢失", () => {
  1198. const workspacePath = "/tmp/workspace-task-usage";
  1199. const taskId = "task-usage";
  1200. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1201. used: 53000,
  1202. size: 200000,
  1203. cost: { amount: 0.045, currency: "USD" },
  1204. });
  1205. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "streaming");
  1206. useZCodeSessionStore.getState().setTaskRuntimeState(workspacePath, taskId, "completed");
  1207. const workspaceState = useZCodeSessionStore.getState().getWorkspaceState(workspacePath);
  1208. expect(getTaskRuntimeState(workspaceState, taskId)).toEqual({
  1209. ...DEFAULT_TASK_RUNTIME_STATE,
  1210. status: "completed",
  1211. error: null,
  1212. apiRetry: null,
  1213. usage: {
  1214. used: 53000,
  1215. size: 200000,
  1216. cost: { amount: 0.045, currency: "USD" },
  1217. },
  1218. });
  1219. });
  1220. it("task contextWindow 单独更新,不覆盖已有 usage", () => {
  1221. const workspacePath = "/tmp/workspace-task-context-window";
  1222. const taskId = "task-context-window";
  1223. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1224. used: 11804,
  1225. size: 200000,
  1226. cost: null,
  1227. cache: {
  1228. inputTokens: 100,
  1229. cacheReadTokens: 40,
  1230. cacheWriteTokens: 0,
  1231. hitRate: 0.4,
  1232. },
  1233. breakdown: [{ source: "messages", chars: 1200 }],
  1234. });
  1235. useZCodeSessionStore.getState().setTaskContextWindow(workspacePath, taskId, 1000000);
  1236. const runtime = getTaskRuntimeState(
  1237. useZCodeSessionStore.getState().getWorkspaceState(workspacePath),
  1238. taskId,
  1239. );
  1240. expect(runtime.contextWindow).toBe(1000000);
  1241. expect(runtime.usage).toEqual({
  1242. used: 11804,
  1243. size: 200000,
  1244. cost: null,
  1245. cache: {
  1246. inputTokens: 100,
  1247. cacheReadTokens: 40,
  1248. cacheWriteTokens: 0,
  1249. hitRate: 0.4,
  1250. },
  1251. breakdown: [{ source: "messages", chars: 1200 }],
  1252. });
  1253. });
  1254. it("相同 task usage 不重复通知订阅者", () => {
  1255. const workspacePath = "/tmp/workspace-task-usage-dedupe";
  1256. const taskId = "task-usage-dedupe";
  1257. let notificationCount = 0;
  1258. const unsubscribe = useZCodeSessionStore.subscribe(() => {
  1259. notificationCount += 1;
  1260. });
  1261. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1262. used: 53000,
  1263. size: 200000,
  1264. cost: { amount: 0.045, currency: "USD" },
  1265. });
  1266. expect(notificationCount).toBe(1);
  1267. useZCodeSessionStore.getState().setTaskUsage(workspacePath, taskId, {
  1268. used: 53000,
  1269. size: 200000,
  1270. cost: { amount: 0.045, currency: "USD" },
  1271. });
  1272. unsubscribe();
  1273. expect(notificationCount).toBe(1);
  1274. });
  1275. it("configOptionsStatus 写入 workspace identity 时不污染 path 桶", () => {
  1276. const workspacePath = "/tmp/workspace-config-status-identity";
  1277. const workspaceIdentity = "ssh://host-a/tmp/workspace-config-status-identity";
  1278. useZCodeSessionStore.getState().setConfigOptionsStatus(workspacePath, "loading");
  1279. useZCodeSessionStore
  1280. .getState()
  1281. .setConfigOptionsStatus(workspacePath, "error", workspaceIdentity);
  1282. expect(
  1283. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).configOptionsStatus,
  1284. ).toBe("loading");
  1285. expect(
  1286. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  1287. .configOptionsStatus,
  1288. ).toBe("error");
  1289. });
  1290. });