useDraftConfigControl.test.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { ZCodeConfigOption } from "@zcode/shared";
  5. import type { SessionConfigState } from "@zcode/shared/zcode-protocol-v4";
  6. import type { IModelSelectionService, ModelSelectionView } from "@zcode/services";
  7. import { resolveEffectiveModelSelection, type ProviderRegistryView } from "@zcode/provider";
  8. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  9. import { useDraftConfigControl as useActualDraftConfigControl } from "@/v4/composer/useDraftConfigControl.js";
  10. import { persistV4ComposerDraft, readV4ComposerDraft } from "@/v4/composer/composerDraftStore.js";
  11. import { captureComposerRecentSubmission } from "@/lib/composerRecent.js";
  12. import { seedImportedSessionDraft } from "@/v4/composer/newTaskDraft.js";
  13. const { prepareWorkspaceMock } = vi.hoisted(() => ({
  14. prepareWorkspaceMock: vi.fn(),
  15. }));
  16. const { toastMock } = vi.hoisted(() => ({
  17. toastMock: vi.fn(),
  18. }));
  19. vi.mock("@/hooks/useWorkspacePrepare.js", () => ({
  20. prepareWorkspaceWithZCodeSessionService: prepareWorkspaceMock,
  21. }));
  22. vi.mock("@/hooks/useZCodeSessionService.js", () => ({
  23. useZCodeSessionService: () => ({ readWorkspacePresentation: vi.fn() }),
  24. }));
  25. vi.mock("@/hooks/useSettingService.js", () => ({
  26. useSettings: () => ({ settings: null }),
  27. }));
  28. vi.mock("@/components/ui/toast.js", () => ({
  29. toast: toastMock,
  30. }));
  31. vi.mock("@/i18n/IntlProvider.js", () => ({
  32. useZCodeIntl: () => ({
  33. intl: { formatMessage: ({ id }: { id: string }) => id },
  34. }),
  35. }));
  36. vi.mock("@/logger.js", () => ({
  37. logger: {
  38. debug: vi.fn(),
  39. info: vi.fn(),
  40. warn: vi.fn(),
  41. },
  42. }));
  43. const WORKSPACE_PRESENTATION: ZCodeConfigOption[] = [
  44. {
  45. id: "mode",
  46. name: "Mode",
  47. category: "mode",
  48. type: "select",
  49. currentValue: "build",
  50. options: [{ value: "build", name: "Build" }],
  51. },
  52. ];
  53. const CUSTOM_COMMANDS = [
  54. {
  55. name: "review",
  56. description: "Review current changes",
  57. source: "custom" as const,
  58. },
  59. ];
  60. const selectionServices = new Map<string, IModelSelectionService>();
  61. // 用真实纯解析算法模拟 Host,只省略 RPC;同内容的 fixture 保持同一 Service owner。
  62. function useDraftConfigControl(
  63. params: Omit<Parameters<typeof useActualDraftConfigControl>[0], "modelSelectionService"> & {
  64. modelSelectionView: ModelSelectionView | null;
  65. },
  66. ) {
  67. const view = params.modelSelectionView;
  68. const key = JSON.stringify(view);
  69. if (view && !selectionServices.has(key))
  70. selectionServices.set(key, {
  71. getView: async (input) => ({
  72. ...view,
  73. ...(input
  74. ? resolveEffectiveModelSelection({
  75. selection: input.selection,
  76. registry: view as unknown as ProviderRegistryView,
  77. classifyProvider: () => "ordinary",
  78. })
  79. : {}),
  80. }),
  81. onDidChange: () => ({ dispose: () => {} }),
  82. });
  83. return useActualDraftConfigControl({
  84. ...params,
  85. modelSelectionService: view ? selectionServices.get(key)! : null,
  86. });
  87. }
  88. function modelSelectionView(
  89. revision: number,
  90. modelIds: readonly string[],
  91. preferredModelId: string,
  92. ): ModelSelectionView {
  93. return {
  94. revision,
  95. preferredSelection: {
  96. providerId: "provider",
  97. modelId: preferredModelId,
  98. },
  99. providers: [
  100. {
  101. providerId: "provider",
  102. config: {},
  103. models: modelIds.map((modelId) => ({
  104. modelId,
  105. config: {
  106. optionSpecs: {
  107. reasoningLevel: { values: ["low", "high"], map: "{}" },
  108. },
  109. },
  110. })),
  111. },
  112. ],
  113. } as ModelSelectionView;
  114. }
  115. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  116. const element = {
  117. addEventListener: () => {},
  118. appendChild: (child: { parentNode?: unknown }) => {
  119. child.parentNode = element;
  120. return child;
  121. },
  122. childNodes: [] as unknown[],
  123. getAttribute: () => null,
  124. insertBefore: (child: { parentNode?: unknown }) => {
  125. child.parentNode = element;
  126. return child;
  127. },
  128. nodeName: tagName.toUpperCase(),
  129. nodeType: 1,
  130. ownerDocument,
  131. parentNode: null as unknown,
  132. removeAttribute: () => {},
  133. removeChild: (child: { parentNode?: unknown }) => {
  134. child.parentNode = null;
  135. return child;
  136. },
  137. removeEventListener: () => {},
  138. setAttribute: () => {},
  139. style: {},
  140. tagName: tagName.toUpperCase(),
  141. };
  142. return element as unknown as Element;
  143. }
  144. function installMinimalDom() {
  145. const storage = new Map<string, string>();
  146. const documentMock = {
  147. addEventListener: () => {},
  148. createElement: (tagName: string) =>
  149. createMinimalElement(documentMock as unknown as Document, tagName),
  150. createTextNode: (nodeValue: string) => ({
  151. nodeType: 3,
  152. nodeValue,
  153. ownerDocument: documentMock,
  154. parentNode: null,
  155. }),
  156. nodeType: 9,
  157. removeEventListener: () => {},
  158. } as unknown as Document;
  159. const windowMock = {
  160. localStorage: {
  161. getItem: (key: string) => storage.get(key) ?? null,
  162. setItem: (key: string, value: string) => storage.set(key, value),
  163. removeItem: (key: string) => storage.delete(key),
  164. },
  165. addEventListener: () => {},
  166. document: documentMock,
  167. HTMLIFrameElement: function HTMLIFrameElement() {},
  168. HTMLElement: function HTMLElement() {},
  169. Node: function Node() {},
  170. removeEventListener: () => {},
  171. };
  172. Object.defineProperty(globalThis, "document", {
  173. configurable: true,
  174. value: documentMock,
  175. });
  176. Object.defineProperty(globalThis, "window", {
  177. configurable: true,
  178. value: windowMock,
  179. });
  180. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  181. configurable: true,
  182. value: true,
  183. });
  184. return createMinimalElement(documentMock);
  185. }
  186. describe("useDraftConfigControl slash command hydration", () => {
  187. it.each(["root", "empty-root", "recent", "default", "unavailable"])(
  188. "SHARE30 首次导入与普通新任务一致:%s,保留 Root 正文且不更新 Recent",
  189. async (source) => {
  190. const root = createRoot(installMinimalDom());
  191. const workspacePath = "/import";
  192. const selection = {
  193. providerId: "provider",
  194. modelId: "model",
  195. options: { reasoningLevel: "high" },
  196. };
  197. const view = {
  198. ...modelSelectionView(1, source === "unavailable" ? [] : ["model"], "model"),
  199. preferredSelection: selection,
  200. };
  201. if (source !== "default" && source !== "unavailable")
  202. captureComposerRecentSubmission(workspacePath, {
  203. modelSelection: selection,
  204. mode: "yolo",
  205. })();
  206. if (source === "root" || source === "empty-root")
  207. persistV4ComposerDraft(workspacePath, undefined, "__draft__", {
  208. text: "KEEP ROOT",
  209. editorStateJson: "ROOT EDITOR",
  210. mode: "plan",
  211. ...(source === "root" ? { modelSelection: selection } : {}),
  212. });
  213. const originalRoot = readV4ComposerDraft(workspacePath, undefined, "__draft__");
  214. const recentBefore = window.localStorage.getItem(
  215. `zcode-model-selection-recent-v1:${workspacePath}`,
  216. );
  217. seedImportedSessionDraft({ workspacePath, sessionId: "imported", reused: false });
  218. let control: ReturnType<typeof useDraftConfigControl>;
  219. function Probe({ sessionId }: { sessionId: string | null }) {
  220. control = useDraftConfigControl({
  221. workspacePath,
  222. sessionId,
  223. sessionConfig: { mode: "build" },
  224. agentStartupAllowed: false,
  225. modelSelectionView: view,
  226. });
  227. return null;
  228. }
  229. await act(async () => root.render(createElement(Probe, { sessionId: "imported" })));
  230. const imported = control!.draftConfig;
  231. expect(control!.composerDraft.text).toBe("");
  232. expect(control!.composerDraft.editorStateJson).toBeUndefined();
  233. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")).toEqual(originalRoot);
  234. await act(async () => root.render(createElement(Probe, { sessionId: null })));
  235. expect(control!.draftConfig).toEqual(imported);
  236. expect(window.localStorage.getItem(`zcode-model-selection-recent-v1:${workspacePath}`)).toBe(
  237. recentBefore,
  238. );
  239. act(() => root.unmount());
  240. },
  241. );
  242. it.each(["none", "mode", "model"])(
  243. "SHARE31 View 延迟不被空 snapshot 抢先锁定;用户先编辑=%s",
  244. async (edited) => {
  245. const root = createRoot(installMinimalDom());
  246. const workspacePath = "/delayed-import";
  247. seedImportedSessionDraft({ workspacePath, sessionId: "imported", reused: false });
  248. let control: ReturnType<typeof useDraftConfigControl>;
  249. const readyView = {
  250. ...modelSelectionView(1, ["model"], "model"),
  251. preferredSelection: {
  252. providerId: "provider",
  253. modelId: "model",
  254. options: { reasoningLevel: "high" },
  255. },
  256. };
  257. function Probe({ ready }: { ready: boolean }) {
  258. control = useDraftConfigControl({
  259. workspacePath,
  260. sessionId: "imported",
  261. sessionConfig: { mode: "build" },
  262. agentStartupAllowed: false,
  263. modelSelectionView: ready ? readyView : null,
  264. });
  265. return null;
  266. }
  267. await act(async () => root.render(createElement(Probe, { ready: false })));
  268. expect(control!.composerDraft.mode).toBeUndefined();
  269. act(() => control!.updateComposerContent({ text: "content stays" }));
  270. if (edited === "mode") act(() => control!.handleDraftSwitchMode("plan"));
  271. if (edited === "model") {
  272. act(() => control!.handleDraftSelectModel("provider", "model"));
  273. act(() => control!.handleDraftSelectThought("low"));
  274. }
  275. await act(async () => root.render(createElement(Probe, { ready: true })));
  276. expect(control!.composerDraft.text).toBe("content stays");
  277. expect(control!.draftConfig.mode).toBe("build");
  278. expect(control!.draftConfig.planEnabled).toBe(edited === "mode");
  279. if (edited === "mode") expect(control!.composerDraft.modelSelection).toBeUndefined();
  280. else expect(control!.draftConfig.modelSelection?.modelId).toBe("model");
  281. if (edited === "model")
  282. expect(control!.draftConfig.modelSelection?.options?.reasoningLevel).toBe("low");
  283. expect(control!.composerDraft.initializeFromNewTask).toBeUndefined();
  284. act(() => root.unmount());
  285. },
  286. );
  287. it("SHARE32 使用导入实际 identity,重复导入/目标已有草稿不覆盖", () => {
  288. installMinimalDom();
  289. const workspacePath = "/same";
  290. persistV4ComposerDraft(workspacePath, "ssh://one/same", "__draft__", {
  291. text: "remote",
  292. mode: "yolo",
  293. });
  294. persistV4ComposerDraft(workspacePath, undefined, "__draft__", { text: "local", mode: "plan" });
  295. seedImportedSessionDraft({ workspacePath, sessionId: "new", reused: false });
  296. expect(readV4ComposerDraft(workspacePath, undefined, "new")).toMatchObject({
  297. text: "",
  298. mode: "build",
  299. planEnabled: true,
  300. });
  301. expect(readV4ComposerDraft(workspacePath, "ssh://one/same", "new")).toBeNull();
  302. seedImportedSessionDraft({
  303. workspacePath,
  304. workspaceIdentity: "ssh://two/same",
  305. sessionId: "new",
  306. reused: false,
  307. });
  308. expect(readV4ComposerDraft(workspacePath, "ssh://two/same", "new")?.mode).toBeUndefined();
  309. persistV4ComposerDraft(workspacePath, undefined, "new", {
  310. text: "already edited",
  311. mode: "edit",
  312. });
  313. seedImportedSessionDraft({ workspacePath, sessionId: "new", reused: false });
  314. expect(readV4ComposerDraft(workspacePath, undefined, "new")).toMatchObject({
  315. text: "already edited",
  316. mode: "edit",
  317. });
  318. seedImportedSessionDraft({ workspacePath, sessionId: "history", reused: true });
  319. expect(readV4ComposerDraft(workspacePath, undefined, "history")).toBeNull();
  320. });
  321. beforeEach(() => {
  322. selectionServices.clear();
  323. prepareWorkspaceMock.mockReset();
  324. toastMock.mockReset();
  325. useZCodeSessionStore.setState((state) => ({
  326. ...state,
  327. workspaces: {},
  328. }));
  329. });
  330. afterEach(() => {
  331. vi.restoreAllMocks();
  332. delete (globalThis as { document?: unknown }).document;
  333. delete (globalThis as { window?: unknown }).window;
  334. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  335. });
  336. it("task → draft 继承模型目录但 slashCommands 为空时重新拉取并写入 identity 桶", async () => {
  337. const workspacePath = "/workspace";
  338. const workspaceIdentity = "ssh://demo/workspace";
  339. useZCodeSessionStore
  340. .getState()
  341. .setConfigOptions(workspacePath, WORKSPACE_PRESENTATION, workspaceIdentity);
  342. prepareWorkspaceMock.mockResolvedValue({
  343. configOptions: WORKSPACE_PRESENTATION,
  344. slashCommands: CUSTOM_COMMANDS,
  345. });
  346. function Probe() {
  347. useDraftConfigControl({
  348. workspacePath,
  349. workspaceIdentity,
  350. provider: "glm",
  351. sessionId: null,
  352. modelSelectionView: null,
  353. });
  354. return null;
  355. }
  356. const root: Root = createRoot(installMinimalDom());
  357. await act(async () => {
  358. root.render(createElement(Probe));
  359. });
  360. await vi.waitFor(() => {
  361. expect(
  362. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  363. .slashCommands,
  364. ).toEqual(CUSTOM_COMMANDS);
  365. });
  366. expect(prepareWorkspaceMock).toHaveBeenCalledWith(
  367. expect.objectContaining({ workspaceIdentity, workspacePath }),
  368. );
  369. act(() => root.unmount());
  370. });
  371. it("打开已有 session 且 workspace slashCommands 为空时独立补水合", async () => {
  372. const workspacePath = "/known-workspace";
  373. useZCodeSessionStore.getState().setConfigOptions(workspacePath, WORKSPACE_PRESENTATION);
  374. prepareWorkspaceMock.mockResolvedValue({
  375. configOptions: WORKSPACE_PRESENTATION,
  376. slashCommands: CUSTOM_COMMANDS,
  377. });
  378. function Probe() {
  379. useDraftConfigControl({
  380. workspacePath,
  381. provider: "glm",
  382. sessionId: "session-known",
  383. modelSelectionView: null,
  384. });
  385. return null;
  386. }
  387. const root: Root = createRoot(installMinimalDom());
  388. await act(async () => {
  389. root.render(createElement(Probe));
  390. });
  391. await vi.waitFor(() => {
  392. expect(
  393. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands,
  394. ).toEqual(CUSTOM_COMMANDS);
  395. });
  396. expect(prepareWorkspaceMock).toHaveBeenCalledWith(expect.objectContaining({ workspacePath }));
  397. act(() => root.unmount());
  398. });
  399. it("打开已有 session 时保留已经水合的 workspace slashCommands", async () => {
  400. const workspacePath = "/hydrated-workspace";
  401. const store = useZCodeSessionStore.getState();
  402. store.setConfigOptions(workspacePath, WORKSPACE_PRESENTATION);
  403. store.setSlashCommands(workspacePath, CUSTOM_COMMANDS);
  404. function Probe() {
  405. useDraftConfigControl({
  406. workspacePath,
  407. provider: "glm",
  408. sessionId: "session-known",
  409. modelSelectionView: null,
  410. });
  411. return null;
  412. }
  413. const root: Root = createRoot(installMinimalDom());
  414. await act(async () => {
  415. root.render(createElement(Probe));
  416. });
  417. expect(useZCodeSessionStore.getState().getWorkspaceState(workspacePath).slashCommands).toEqual(
  418. CUSTOM_COMMANDS,
  419. );
  420. expect(prepareWorkspaceMock).not.toHaveBeenCalled();
  421. act(() => root.unmount());
  422. });
  423. it("从 active task 新建草稿时不再从旧 workspace presentation 继承选择", async () => {
  424. const workspacePath = "/inherited-draft-workspace";
  425. const taskId = "task-custom-model";
  426. const inheritedOptions: ZCodeConfigOption[] = [
  427. {
  428. id: "model",
  429. name: "Model",
  430. category: "model",
  431. type: "select",
  432. currentValue: "custom-provider/gpt-5.6-sol",
  433. options: [{ value: "custom-provider/gpt-5.6-sol", name: "GPT-5.6 Sol" }],
  434. },
  435. {
  436. id: "mode",
  437. name: "Mode",
  438. category: "mode",
  439. type: "select",
  440. currentValue: "yolo",
  441. options: [{ value: "yolo", name: "YOLO" }],
  442. },
  443. {
  444. id: "thought_level",
  445. name: "Thought",
  446. category: "thought_level",
  447. type: "select",
  448. currentValue: "max",
  449. options: [{ value: "max", name: "Max" }],
  450. },
  451. ];
  452. const store = useZCodeSessionStore.getState();
  453. store.setActiveTaskId(workspacePath, taskId);
  454. store.setTaskConfigOptions(workspacePath, taskId, inheritedOptions);
  455. store.startDraft(workspacePath, "glm");
  456. prepareWorkspaceMock.mockResolvedValue({
  457. configOptions: inheritedOptions,
  458. slashCommands: CUSTOM_COMMANDS,
  459. });
  460. let initialConfig: Partial<SessionConfigState> | undefined;
  461. function Probe() {
  462. const control = useDraftConfigControl({
  463. workspacePath,
  464. provider: "glm",
  465. sessionId: null,
  466. modelSelectionView: null,
  467. });
  468. initialConfig = control.resolveInitialDraftConfig();
  469. return null;
  470. }
  471. const root: Root = createRoot(installMinimalDom());
  472. await act(async () => {
  473. root.render(createElement(Probe));
  474. });
  475. // 旧 task presentation 不再是新 Composer 的选择来源;View 未到达时不初始化。
  476. expect(initialConfig).toBeUndefined();
  477. act(() => root.unmount());
  478. });
  479. it("active session 切入草稿时,View 未 Ready 不提前用旧 task 配置初始化", async () => {
  480. const workspacePath = "/inherited-draft-render-transition";
  481. const taskId = "task-custom-model";
  482. const inheritedOptions: ZCodeConfigOption[] = [
  483. {
  484. id: "model",
  485. name: "Model",
  486. category: "model",
  487. type: "select",
  488. currentValue: "custom-provider/gpt-5.6-sol",
  489. options: [{ value: "custom-provider/gpt-5.6-sol", name: "GPT-5.6 Sol" }],
  490. },
  491. {
  492. id: "mode",
  493. name: "Mode",
  494. category: "mode",
  495. type: "select",
  496. currentValue: "yolo",
  497. options: [{ value: "yolo", name: "YOLO" }],
  498. },
  499. {
  500. id: "thought_level",
  501. name: "Thought",
  502. category: "thought_level",
  503. type: "select",
  504. currentValue: "max",
  505. options: [{ value: "max", name: "Max" }],
  506. },
  507. ];
  508. const store = useZCodeSessionStore.getState();
  509. store.setConfigOptions(workspacePath, inheritedOptions);
  510. store.setActiveTaskId(workspacePath, taskId);
  511. store.setTaskConfigOptions(workspacePath, taskId, inheritedOptions);
  512. store.setSlashCommands(workspacePath, CUSTOM_COMMANDS);
  513. prepareWorkspaceMock.mockResolvedValue({
  514. configOptions: inheritedOptions,
  515. slashCommands: CUSTOM_COMMANDS,
  516. });
  517. const configsSeenDuringDraftRender: Array<Partial<SessionConfigState> | undefined> = [];
  518. function Probe({ sessionId }: { sessionId: string | null }) {
  519. const control = useDraftConfigControl({
  520. workspacePath,
  521. provider: "glm",
  522. sessionId,
  523. modelSelectionView: null,
  524. });
  525. if (sessionId === null) {
  526. configsSeenDuringDraftRender.push(control.resolveInitialDraftConfig());
  527. }
  528. return null;
  529. }
  530. const root: Root = createRoot(installMinimalDom());
  531. await act(async () => {
  532. root.render(createElement(Probe, { sessionId: taskId }));
  533. });
  534. act(() => {
  535. useZCodeSessionStore.getState().startDraft(workspacePath, "glm");
  536. root.render(createElement(Probe, { sessionId: null }));
  537. });
  538. expect(configsSeenDuringDraftRender[0]).toBeUndefined();
  539. act(() => root.unmount());
  540. });
  541. it("Registry revision 只影响有效选择,正文和模式编辑保留原意图,配置恢复后重新有效", async () => {
  542. const workspacePath = "/live-selection-invalidated";
  543. const firstView = modelSelectionView(1, ["old", "preferred"], "preferred");
  544. const nextView = modelSelectionView(2, ["preferred"], "preferred");
  545. useZCodeSessionStore.getState().setSlashCommands(workspacePath, CUSTOM_COMMANDS);
  546. useZCodeSessionStore.getState().setConfigOptions(workspacePath, WORKSPACE_PRESENTATION);
  547. let control: ReturnType<typeof useDraftConfigControl> | undefined;
  548. function Probe({ view }: { view: ModelSelectionView }) {
  549. control = useDraftConfigControl({
  550. workspacePath,
  551. provider: "glm",
  552. sessionId: null,
  553. modelSelectionView: view,
  554. });
  555. return null;
  556. }
  557. const root: Root = createRoot(installMinimalDom());
  558. await act(async () => {
  559. root.render(createElement(Probe, { view: firstView }));
  560. });
  561. act(() => control!.handleDraftSelectModel("provider", "old"));
  562. expect(control!.draftConfig.modelSelection).toEqual({
  563. providerId: "provider",
  564. modelId: "old",
  565. options: { reasoningLevel: "high" },
  566. });
  567. await act(async () => {
  568. root.render(createElement(Probe, { view: nextView }));
  569. });
  570. expect(control!.draftConfig.modelSelection).toBeUndefined();
  571. expect(control!.resolveInitialDraftConfig()?.modelSelection).toBeUndefined();
  572. act(() => control!.updateComposerContent({ text: "保留原选择" }));
  573. act(() => control!.handleDraftSwitchMode("plan"));
  574. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")).toMatchObject({
  575. mode: "build",
  576. planEnabled: true,
  577. text: "保留原选择",
  578. modelSelection: { providerId: "provider", modelId: "old" },
  579. });
  580. await act(async () => {
  581. root.render(createElement(Probe, { view: { ...firstView, revision: 3 } }));
  582. });
  583. expect(control!.draftConfig.modelSelection).toEqual({
  584. providerId: "provider",
  585. modelId: "old",
  586. options: { reasoningLevel: "high" },
  587. });
  588. expect(toastMock).not.toHaveBeenCalled();
  589. act(() => root.unmount());
  590. });
  591. it("有效选择只在接纳时写回,迟到接纳不能覆盖新选择或另一个 scope", async () => {
  592. const workspacePath = "/effective-selection-commit";
  593. const root = createRoot(installMinimalDom());
  594. const original = {
  595. providerId: "old-account",
  596. modelId: "model",
  597. options: { reasoningLevel: "high" },
  598. };
  599. const effective = { ...original, providerId: "new-account" };
  600. persistV4ComposerDraft(workspacePath, undefined, "a", {
  601. text: "hello",
  602. mode: "build",
  603. modelSelection: original,
  604. });
  605. const service: IModelSelectionService = {
  606. getView: async (input) => ({
  607. revision: 1,
  608. providers: [],
  609. effectiveSelection:
  610. input?.selection?.providerId === "old-account" ? effective : (input?.selection ?? null),
  611. }),
  612. onDidChange: () => ({ dispose: () => {} }),
  613. };
  614. let control: ReturnType<typeof useActualDraftConfigControl>;
  615. function Probe({ sessionId }: { sessionId: string }) {
  616. control = useActualDraftConfigControl({
  617. workspacePath,
  618. sessionId,
  619. sessionConfig: { mode: "build" },
  620. agentStartupAllowed: false,
  621. modelSelectionService: service,
  622. });
  623. return null;
  624. }
  625. await act(async () => root.render(createElement(Probe, { sessionId: "a" })));
  626. expect(control!.draftConfig.modelSelection).toEqual(effective);
  627. expect(readV4ComposerDraft(workspacePath, undefined, "a")?.modelSelection).toEqual(original);
  628. // 对象属性顺序不属于 Selection 语义,协议/序列化重建可能改变顺序。
  629. const accepted = control!.captureAcceptedModelSelection({
  630. options: effective.options,
  631. modelId: effective.modelId,
  632. providerId: effective.providerId,
  633. });
  634. act(() => control!.updateComposerContent({ text: "新正文" }));
  635. act(() => accepted());
  636. expect(readV4ComposerDraft(workspacePath, undefined, "a")).toMatchObject({
  637. text: "新正文",
  638. modelSelection: effective,
  639. });
  640. const recommended = { ...effective, providerId: "account:bigmodel-start-plan" };
  641. const acceptRecommendation = control!.captureAcceptedModelSelection(recommended, effective);
  642. expect(readV4ComposerDraft(workspacePath, undefined, "a")?.modelSelection).toEqual(effective);
  643. act(() => acceptRecommendation());
  644. expect(readV4ComposerDraft(workspacePath, undefined, "a")?.modelSelection).toEqual(recommended);
  645. const staleAccepted = control!.captureAcceptedModelSelection(recommended);
  646. await act(async () => control!.handleDraftSelectModel("personal", "another"));
  647. act(() => staleAccepted());
  648. expect(readV4ComposerDraft(workspacePath, undefined, "a")?.modelSelection).toEqual({
  649. providerId: "personal",
  650. modelId: "another",
  651. });
  652. const oldScopeAccepted = control!.captureAcceptedModelSelection(
  653. control!.draftConfig.modelSelection!,
  654. );
  655. await act(async () => root.render(createElement(Probe, { sessionId: "b" })));
  656. act(() => oldScopeAccepted());
  657. expect(readV4ComposerDraft(workspacePath, undefined, "b")?.modelSelection).toBeUndefined();
  658. act(() => root.unmount());
  659. });
  660. it("Session 只初始化一次,用户未发送的 mode/model 不被迟到 Snapshot 覆盖", async () => {
  661. const workspacePath = "/session-draft-seed";
  662. const view = modelSelectionView(1, ["old", "new"], "old");
  663. const root = createRoot(installMinimalDom());
  664. let control: ReturnType<typeof useDraftConfigControl>;
  665. function Probe({ config }: { config: Partial<SessionConfigState> | null }) {
  666. control = useDraftConfigControl({
  667. workspacePath,
  668. sessionId: "session",
  669. sessionConfig: config,
  670. agentStartupAllowed: false,
  671. modelSelectionView: view,
  672. });
  673. return null;
  674. }
  675. const config = { mode: "yolo", modelSelection: view.preferredSelection! };
  676. await act(async () => {
  677. root.render(createElement(Probe, { config }));
  678. });
  679. expect(control!.draftConfig).toMatchObject(config);
  680. act(() => {
  681. control!.handleDraftSwitchMode("edit");
  682. control!.handleDraftSelectModel("provider", "new");
  683. });
  684. await act(async () => {
  685. root.render(createElement(Probe, { config: { ...config } }));
  686. });
  687. expect(control!.draftConfig).toMatchObject({
  688. mode: "edit",
  689. modelSelection: { modelId: "new" },
  690. });
  691. expect(readV4ComposerDraft(workspacePath, undefined, "session")).toMatchObject({
  692. text: "",
  693. mode: "edit",
  694. modelSelection: { modelId: "new" },
  695. });
  696. act(() => root.unmount());
  697. });
  698. it("旧文本草稿等 Session 到达后只补新字段;Todo70 未绑定结果不会用 preferred 填满", async () => {
  699. const workspacePath = "/old-text-draft";
  700. const root = createRoot(installMinimalDom());
  701. persistV4ComposerDraft(workspacePath, undefined, "session", { text: "未发送正文" });
  702. let control: ReturnType<typeof useDraftConfigControl>;
  703. function Probe({ config }: { config: Partial<SessionConfigState> | null }) {
  704. control = useDraftConfigControl({
  705. workspacePath,
  706. sessionId: "session",
  707. sessionConfig: config,
  708. agentStartupAllowed: false,
  709. modelSelectionView: modelSelectionView(1, ["old"], "old"),
  710. });
  711. return null;
  712. }
  713. await act(async () => {
  714. root.render(createElement(Probe, { config: null }));
  715. });
  716. expect(readV4ComposerDraft(workspacePath, undefined, "session")?.mode).toBeUndefined();
  717. await act(async () => {
  718. root.render(createElement(Probe, { config: { mode: "build" } }));
  719. });
  720. expect(control!.draftConfig.modelSelection).toBeUndefined();
  721. expect(readV4ComposerDraft(workspacePath, undefined, "session")).toMatchObject({
  722. text: "未发送正文",
  723. mode: "build",
  724. });
  725. await act(async () => {
  726. root.render(
  727. createElement(Probe, {
  728. config: {
  729. mode: "yolo",
  730. modelSelection: modelSelectionView(1, ["old"], "old").preferredSelection!,
  731. },
  732. }),
  733. );
  734. });
  735. expect(control!.draftConfig).toMatchObject({ mode: "build" });
  736. expect(control!.draftConfig.modelSelection).toBeUndefined();
  737. act(() => root.unmount());
  738. });
  739. it("新 Root 继承最近接纳的权限,菜单编辑与旧 Snapshot 不覆盖独立草稿", async () => {
  740. const workspacePath = "/recent-mode";
  741. const root = createRoot(installMinimalDom());
  742. const view = modelSelectionView(1, ["model"], "model");
  743. window.localStorage.setItem(
  744. `zcode-model-selection-recent-v1:${workspacePath}`,
  745. JSON.stringify({ modelSelection: view.preferredSelection, mode: "yolo" }),
  746. );
  747. let control: ReturnType<typeof useDraftConfigControl>;
  748. function Probe({ sessionId }: { sessionId: string | null }) {
  749. control = useDraftConfigControl({
  750. workspacePath,
  751. sessionId,
  752. sessionConfig: { mode: "build", modelSelection: view.preferredSelection },
  753. agentStartupAllowed: false,
  754. modelSelectionView: view,
  755. });
  756. return null;
  757. }
  758. await act(async () => root.render(createElement(Probe, { sessionId: null })));
  759. expect(control!.draftConfig.mode).toBe("yolo");
  760. act(() => control!.handleDraftSwitchMode("plan"));
  761. await act(async () => root.render(createElement(Probe, { sessionId: "session" })));
  762. expect(control!.draftConfig.mode).toBe("build");
  763. act(() => control!.handleDraftSwitchMode("edit"));
  764. await act(async () => root.render(createElement(Probe, { sessionId: null })));
  765. expect(control!.draftConfig).toMatchObject({ mode: "yolo", planEnabled: true });
  766. await act(async () => root.render(createElement(Probe, { sessionId: "session" })));
  767. expect(control!.draftConfig.mode).toBe("edit");
  768. expect(
  769. JSON.parse(window.localStorage.getItem(`zcode-model-selection-recent-v1:${workspacePath}`)!),
  770. ).toMatchObject({ mode: "yolo" });
  771. act(() => root.unmount());
  772. });
  773. it("新草稿先保留 Recent 原意图,再交给当前 View 解析,不能在初始化时丢掉旧账号", async () => {
  774. const workspacePath = "/recent-account-intent";
  775. const root = createRoot(installMinimalDom());
  776. const original = {
  777. providerId: "old-account",
  778. modelId: "same",
  779. options: { reasoningLevel: "high" },
  780. };
  781. const effective = { ...original, providerId: "provider" };
  782. captureComposerRecentSubmission(workspacePath, { modelSelection: original, mode: "build" })();
  783. const service: IModelSelectionService = {
  784. getView: async (input) => ({
  785. ...modelSelectionView(1, ["same"], "same"),
  786. ...(input ? { effectiveSelection: input.selection ? effective : null } : {}),
  787. }),
  788. onDidChange: () => ({ dispose() {} }),
  789. };
  790. let control: ReturnType<typeof useActualDraftConfigControl>;
  791. function Probe() {
  792. control = useActualDraftConfigControl({
  793. workspacePath,
  794. sessionId: null,
  795. agentStartupAllowed: false,
  796. modelSelectionService: service,
  797. });
  798. return null;
  799. }
  800. await act(async () => {
  801. root.render(createElement(Probe));
  802. });
  803. expect(control!.draftConfig.modelSelection).toEqual(effective);
  804. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")?.modelSelection).toEqual(
  805. original,
  806. );
  807. act(() => root.unmount());
  808. });
  809. it("Reasoning 失效只清档位,loading 不清选择,重挂载不补默认", async () => {
  810. const workspacePath = "/persisted-invalid-reasoning";
  811. const container = installMinimalDom();
  812. persistV4ComposerDraft(workspacePath, undefined, "session", {
  813. text: "draft",
  814. mode: "plan",
  815. modelSelection: {
  816. providerId: "provider",
  817. modelId: "old",
  818. options: { reasoningLevel: "deleted" },
  819. },
  820. });
  821. let control: ReturnType<typeof useDraftConfigControl>;
  822. function Probe({ view }: { view: ModelSelectionView | null }) {
  823. control = useDraftConfigControl({
  824. workspacePath,
  825. sessionId: "session",
  826. sessionConfig: { mode: "build" },
  827. agentStartupAllowed: false,
  828. modelSelectionView: view,
  829. });
  830. return null;
  831. }
  832. let root = createRoot(container);
  833. await act(async () => {
  834. root.render(createElement(Probe, { view: null }));
  835. });
  836. expect(control!.draftConfig.modelSelection?.options?.reasoningLevel).toBe("deleted");
  837. const view = modelSelectionView(1, ["old"], "old");
  838. await act(async () => {
  839. root.render(createElement(Probe, { view }));
  840. });
  841. expect(control!.draftConfig.modelSelection).toEqual({ providerId: "provider", modelId: "old" });
  842. act(() => root.unmount());
  843. root = createRoot(container);
  844. await act(async () => {
  845. root.render(createElement(Probe, { view }));
  846. });
  847. expect(control!.draftConfig.modelSelection).toEqual({ providerId: "provider", modelId: "old" });
  848. expect(control!.draftConfig).toMatchObject({ mode: "build", planEnabled: true });
  849. expect(
  850. readV4ComposerDraft(workspacePath, undefined, "session")?.modelSelection?.options
  851. ?.reasoningLevel,
  852. ).toBe("deleted");
  853. expect(toastMock).not.toHaveBeenCalled();
  854. act(() => root.unmount());
  855. });
  856. it("延迟 Session seed 也校验档位,正文保存与选模共享完整草稿且 scope 隔离", async () => {
  857. const workspacePath = "/delayed-session";
  858. const root = createRoot(installMinimalDom());
  859. const view = modelSelectionView(1, ["old", "new"], "new");
  860. let control: ReturnType<typeof useDraftConfigControl>;
  861. function Probe({
  862. sessionId,
  863. config,
  864. }: {
  865. sessionId: string;
  866. config: Partial<SessionConfigState> | null;
  867. }) {
  868. control = useDraftConfigControl({
  869. workspacePath,
  870. workspaceIdentity: "ssh://demo/workspace",
  871. sessionId,
  872. sessionConfig: config,
  873. agentStartupAllowed: false,
  874. modelSelectionView: view,
  875. });
  876. return null;
  877. }
  878. await act(async () => {
  879. root.render(createElement(Probe, { sessionId: "a", config: null }));
  880. });
  881. await act(async () => {
  882. root.render(
  883. createElement(Probe, {
  884. sessionId: "a",
  885. config: {
  886. mode: "yolo",
  887. modelSelection: {
  888. providerId: "provider",
  889. modelId: "old",
  890. options: { reasoningLevel: "deleted" },
  891. },
  892. },
  893. }),
  894. );
  895. });
  896. expect(control!.draftConfig.modelSelection).toEqual({ providerId: "provider", modelId: "old" });
  897. act(() => {
  898. control!.updateComposerContent({ text: "草稿 A" });
  899. control!.handleDraftSelectModel("provider", "new");
  900. });
  901. const staleContentCallback = control!.updateComposerContent;
  902. await act(async () => {
  903. root.render(createElement(Probe, { sessionId: "b", config: { mode: "plan" } }));
  904. });
  905. act(() => staleContentCallback({ text: "迟到 A" }));
  906. expect(control!.composerDraft).toMatchObject({ text: "", mode: "build", planEnabled: true });
  907. await act(async () => {
  908. root.render(createElement(Probe, { sessionId: "a", config: { mode: "build" } }));
  909. });
  910. expect(control!.composerDraft).toMatchObject({
  911. text: "草稿 A",
  912. mode: "yolo",
  913. modelSelection: {
  914. providerId: "provider",
  915. modelId: "new",
  916. },
  917. });
  918. expect(readV4ComposerDraft(workspacePath, undefined, "a")).toBeNull();
  919. act(() => root.unmount());
  920. });
  921. it("新任务创建 Session 时先转移完整 Draft,再删除 Root scope", async () => {
  922. const workspacePath = "/promote-composer-draft";
  923. const root = createRoot(installMinimalDom());
  924. const view = modelSelectionView(1, ["model"], "model");
  925. let control: ReturnType<typeof useDraftConfigControl>;
  926. function Probe() {
  927. control = useDraftConfigControl({
  928. workspacePath,
  929. sessionId: null,
  930. agentStartupAllowed: false,
  931. modelSelectionView: view,
  932. });
  933. return null;
  934. }
  935. await act(async () => root.render(createElement(Probe)));
  936. act(() => {
  937. control!.updateComposerContent({ text: "等待接纳的正文" });
  938. control!.handleDraftSwitchMode("yolo");
  939. control!.handleDraftSelectModel("provider", "model");
  940. control!.promoteComposerDraft("created-session");
  941. });
  942. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")).toBeNull();
  943. expect(readV4ComposerDraft(workspacePath, undefined, "created-session")).toMatchObject({
  944. text: "等待接纳的正文",
  945. mode: "yolo",
  946. modelSelection: {
  947. providerId: "provider",
  948. modelId: "model",
  949. },
  950. });
  951. act(() => root.unmount());
  952. });
  953. it("目标 Session scope 写盘失败时保留 Root Draft", async () => {
  954. const workspacePath = "/promote-write-failure";
  955. const root = createRoot(installMinimalDom());
  956. let control: ReturnType<typeof useDraftConfigControl>;
  957. function Probe() {
  958. control = useDraftConfigControl({
  959. workspacePath,
  960. sessionId: null,
  961. agentStartupAllowed: false,
  962. modelSelectionView: modelSelectionView(1, ["model"], "model"),
  963. });
  964. return null;
  965. }
  966. await act(async () => root.render(createElement(Probe)));
  967. act(() => control!.updateComposerContent({ text: "必须保留" }));
  968. persistV4ComposerDraft(workspacePath, undefined, "__draft__", control!.composerDraft);
  969. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")?.text).toBe("必须保留");
  970. const originalSetItem = window.localStorage.setItem.bind(window.localStorage);
  971. const failedWrites = vi.fn(() => {
  972. throw new Error("quota");
  973. });
  974. window.localStorage.setItem = failedWrites;
  975. act(() => control!.promoteComposerDraft("created-session"));
  976. window.localStorage.setItem = originalSetItem;
  977. expect(failedWrites).toHaveBeenCalledTimes(1);
  978. expect(readV4ComposerDraft(workspacePath, undefined, "__draft__")?.text).toBe("必须保留");
  979. expect(readV4ComposerDraft(workspacePath, undefined, "created-session")).toBeNull();
  980. act(() => root.unmount());
  981. });
  982. it("PA158 授权按 scope 消费一次,保留 Plan/草稿;撤回编辑不重放旧授权", async () => {
  983. const root = createRoot(installMinimalDom());
  984. const workspacePath = "/permission-grant";
  985. persistV4ComposerDraft(workspacePath, undefined, "s", {
  986. text: "draft",
  987. mode: "edit",
  988. planEnabled: true,
  989. });
  990. let control: ReturnType<typeof useDraftConfigControl>;
  991. function Probe({ sessionId }: { sessionId: string }) {
  992. control = useDraftConfigControl({
  993. workspacePath,
  994. sessionId,
  995. sessionConfig:
  996. sessionId === "s"
  997. ? { mode: "yolo", planEnabled: false, permissionGrant: { interactionId: "p" } }
  998. : { mode: "build" },
  999. modelSelectionView: null,
  1000. agentStartupAllowed: false,
  1001. });
  1002. return null;
  1003. }
  1004. await act(async () => root.render(createElement(Probe, { sessionId: "s" })));
  1005. expect(control!.composerDraft).toMatchObject({
  1006. text: "draft",
  1007. mode: "yolo",
  1008. planEnabled: true,
  1009. });
  1010. act(() => control!.handleDraftSwitchMode("build"));
  1011. await act(async () => root.render(createElement(Probe, { sessionId: "s" })));
  1012. expect(control!.composerDraft.mode).toBe("build");
  1013. act(() =>
  1014. control!.replaceComposerDraft({ text: "later queue", mode: "edit", planEnabled: false }),
  1015. );
  1016. expect(control!.composerDraft).toMatchObject({
  1017. text: "later queue",
  1018. mode: "edit",
  1019. planEnabled: false,
  1020. lastPermissionGrantId: "p",
  1021. });
  1022. await act(async () => root.render(createElement(Probe, { sessionId: "other" })));
  1023. expect(control!.composerDraft.mode).toBe("build");
  1024. await act(async () => root.render(createElement(Probe, { sessionId: "s" })));
  1025. expect(control!.composerDraft.mode).toBe("edit");
  1026. act(() => root.unmount());
  1027. });
  1028. });