edit-query-presentation.fixture.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. import { useState, useSyncExternalStore } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import type {
  4. CommandAck,
  5. ConversationDelta,
  6. ConversationRow,
  7. ConversationSnapshot,
  8. ConversationTopicFrame,
  9. } from "@zcode/shared/zcode-protocol-v4";
  10. import type { IServiceAccessor, IBroadcastService } from "@zcode/services";
  11. import type { IPlatformService } from "@zcode/shared";
  12. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  13. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  14. import { ConversationTimeline } from "@/v4/ConversationTimeline.js";
  15. import { ConversationProjectionStore } from "@/v4/conversationProjectionStore.js";
  16. import type { ConversationTransport } from "@/v4/transport.js";
  17. import { TooltipProvider } from "@/components/ui/tooltip.js";
  18. import { TabStoreProvider } from "@/store/TabStoreProvider.js";
  19. import { ServiceProvider } from "@/hooks/useServices.js";
  20. import { PlatformProvider } from "@/hooks/usePlatform.js";
  21. import { StoreContext } from "@/store/StoreProvider.js";
  22. import { createZCodeStore } from "@/store/index.js";
  23. import { composerEditSessionKey, useComposerEditStore } from "@/composer-edit-mode/index.js";
  24. import "@/styles.css";
  25. const query = new URLSearchParams(location.search);
  26. const theme = query.get("theme") === "dark" ? "dark" : "light";
  27. const mobile = query.get("mobile") === "true";
  28. const count = Number(query.get("count") || 8);
  29. const broadcast = {
  30. send: async () => {},
  31. onMessage: () => ({ dispose() {} }),
  32. } as unknown as IBroadcastService;
  33. const services = {
  34. clientConfigService: {},
  35. subagentsService: { list: async () => ({ agents: [], capability: null }) },
  36. zcodeAgentService: {},
  37. settingService: { get: async () => ({}) },
  38. broadcastService: broadcast,
  39. } as unknown as IServiceAccessor;
  40. const platform = { platform: "darwin" } as unknown as IPlatformService;
  41. const settings = createZCodeStore(broadcast);
  42. settings.getState().setTheme(theme);
  43. document.documentElement.className = `${theme} theme-zai-${theme}`;
  44. const rows: ConversationRow[] = Array.from({ length: count }, (_, index) => {
  45. const base = {
  46. turnId: `turn-${index}`,
  47. createdAt: 1700000000000 + index,
  48. createdAtSeq: index + 1,
  49. };
  50. return [
  51. {
  52. ...base,
  53. rowId: index * 10 + 1,
  54. kind: "turnHeader",
  55. origin: "userInput",
  56. state: "completedSuccess",
  57. startedAt: base.createdAt,
  58. endedAt: base.createdAt + 1000,
  59. },
  60. {
  61. ...base,
  62. rowId: index * 10 + 2,
  63. kind: "userInput",
  64. origin: "realUser",
  65. entityId: `user-${index}`,
  66. text: `E2E_EDIT_PRESENTATION_${index} 请分析编辑重发的布局。`,
  67. actions: { canEdit: index === count - 1 },
  68. },
  69. {
  70. ...base,
  71. rowId: index * 10 + 3,
  72. kind: "assistantText",
  73. entityId: `assistant-${index}`,
  74. state: "complete",
  75. text: Array.from(
  76. { length: 9 },
  77. (_, paragraph) => `第 ${paragraph + 1} 段:合成回答用于检查列表高度和滚动位置。`,
  78. ).join("\n\n"),
  79. },
  80. ] as ConversationRow[];
  81. }).flat();
  82. function makeSnapshot(sessionId: string, initialRows = rows): ConversationSnapshot {
  83. return {
  84. protocolVersion: 1,
  85. sessionId,
  86. logEpoch: "epoch-a",
  87. seq: 0,
  88. revision: 0,
  89. control: {
  90. phase: "completedSuccess",
  91. sessionEnded: true,
  92. canStop: false,
  93. stopState: "idle",
  94. stopTargetKind: "unknown",
  95. activeWorks: [],
  96. lastError: null,
  97. apiRetry: null,
  98. },
  99. availability: {},
  100. inputRouting: {},
  101. meta: { title: "Fixture", titleSource: "default" },
  102. config: {
  103. provider: "",
  104. model: "",
  105. thought: "",
  106. thoughtLevels: [],
  107. followupMode: "queue",
  108. mode: "build",
  109. },
  110. modelTransition: null,
  111. usage: {
  112. contextWindow: null,
  113. cumulative: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
  114. },
  115. queue: { items: [], autoDrain: true },
  116. pendingInteractions: [],
  117. pendingCommands: [],
  118. backgroundWorks: [],
  119. subagents: { revision: 0, childSessionIds: [], running: [], endedTotal: 0 },
  120. goal: null,
  121. plan: null,
  122. workspaceHookAdmission: null,
  123. rows: {
  124. window: initialRows,
  125. totalCount: initialRows.length,
  126. firstRowId: initialRows[0]?.rowId ?? null,
  127. },
  128. } as ConversationSnapshot;
  129. }
  130. function makeStore(sessionId: string, initialRows = rows) {
  131. const snapshot = makeSnapshot(sessionId, initialRows);
  132. let store: ConversationProjectionStore;
  133. const topic = `conversation:${sessionId}`;
  134. const subscriptionId = `sub-${sessionId}`;
  135. const transport = {
  136. onAssemblyFault: () => () => {},
  137. onRuntimeRestart: () => () => {},
  138. subscribe: async () => ({
  139. ack: { subscriptionId, mode: "snapshot", logEpoch: snapshot.logEpoch },
  140. }),
  141. activate: () =>
  142. store.handleFrame(
  143. {
  144. topic,
  145. subscriptionId,
  146. logEpoch: snapshot.logEpoch,
  147. fromSeq: 0,
  148. toSeq: 0,
  149. payload: { kind: "snapshot", snapshot },
  150. } as ConversationTopicFrame,
  151. { deliveryKind: "initial" },
  152. ),
  153. unsubscribe: async () => {},
  154. } as unknown as ConversationTransport;
  155. store = new ConversationProjectionStore(topic, transport);
  156. void store.connect();
  157. return store;
  158. }
  159. const store = makeStore("edit");
  160. const other = makeStore(
  161. "other",
  162. rows.map((row) => ({ ...row, rowId: row.rowId + 1000, turnId: `other-${row.turnId}` })),
  163. );
  164. const commandId = "edit-command";
  165. let resolveAck: (value: CommandAck | false) => void = () => {};
  166. let editedText = "";
  167. const send = (deltas: ConversationDelta[]) => {
  168. const current = store.getState().snapshot!;
  169. store.handleFrame({
  170. topic: store.topic,
  171. subscriptionId: store.getState().subscriptionId!,
  172. logEpoch: current.logEpoch,
  173. fromSeq: current.seq,
  174. toSeq: current.seq + 1,
  175. payload: { kind: "deltas", deltas },
  176. } as ConversationTopicFrame);
  177. };
  178. const probe = {
  179. submitted: false,
  180. cut: () => send([{ op: "row.removed", fromRowId: (count - 1) * 10 + 1 }]),
  181. ack: () => resolveAck({ commandId, status: "accepted" } as CommandAck),
  182. reject: () => {
  183. store.settleCommand(commandId);
  184. resolveAck(false);
  185. },
  186. replace: (sourceCommandId = commandId) => {
  187. const base = {
  188. turnId: `edited-${sourceCommandId}`,
  189. createdAt: 1700000100000,
  190. createdAtSeq: 99,
  191. };
  192. send([
  193. {
  194. op: "row.appended",
  195. row: {
  196. ...base,
  197. rowId: count * 10 + 1,
  198. kind: "turnHeader",
  199. origin: "userInput",
  200. state: "running",
  201. startedAt: base.createdAt,
  202. },
  203. },
  204. {
  205. op: "row.appended",
  206. row: {
  207. ...base,
  208. rowId: count * 10 + 2,
  209. kind: "userInput",
  210. origin: "realUser",
  211. sourceCommandId,
  212. entityId: `edited-${sourceCommandId}`,
  213. text: editedText,
  214. actions: { canEdit: true },
  215. },
  216. },
  217. ]);
  218. },
  219. queued: () =>
  220. send([
  221. {
  222. op: "state.updated",
  223. patch: {
  224. queue: {
  225. autoDrain: false,
  226. items: [{ queueItemId: "edit-queued", sourceCommandId: commandId, text: editedText }],
  227. },
  228. },
  229. } as ConversationDelta,
  230. ]),
  231. error: () =>
  232. send([
  233. {
  234. op: "state.updated",
  235. patch: {
  236. control: {
  237. ...store.getState().snapshot!.control,
  238. phase: "error",
  239. lastError: {
  240. code: "fixture.failure",
  241. message: "Fixture failed",
  242. recoverable: true,
  243. at: 1700000100000,
  244. source: "runtime",
  245. },
  246. },
  247. },
  248. },
  249. ]),
  250. epoch: () => {
  251. const snapshot = { ...makeSnapshot("edit", []), logEpoch: "epoch-b" };
  252. store.handleFrame(
  253. {
  254. topic: store.topic,
  255. subscriptionId: store.getState().subscriptionId!,
  256. logEpoch: snapshot.logEpoch,
  257. fromSeq: 0,
  258. toSeq: 0,
  259. payload: { kind: "snapshot", snapshot },
  260. } as ConversationTopicFrame,
  261. { deliveryKind: "recovery" },
  262. );
  263. },
  264. close: () => store.close(),
  265. switchSession: () => {},
  266. state: () => ({
  267. rows: store.getState().snapshot?.rows.window.map((row) => row.rowId),
  268. pending: store.getState().editPresentation != null,
  269. seq: store.getState().snapshot?.seq,
  270. }),
  271. };
  272. Object.assign(window, { editProbe: probe });
  273. // 编辑在底部 composer 编辑态进行(docs/ui/composer-edit-mode.md):Edit 只标记目标行进入编辑,
  274. // 原行显示「正在下方编辑」。真实 composer 依赖 SessionPane 全量服务,这里用最小替身执行同一
  275. // 提交契约:editUserQuery ACK 后等待显示交接完成才退出编辑态,失败保留可重试的编辑内容。
  276. const editKey = composerEditSessionKey("/fixture", "edit");
  277. const beginEdit = (target: { rowId: number; entityId: string }) => {
  278. useComposerEditStore.getState().begin(editKey, {
  279. target: { kind: "userQuery", rowId: target.rowId, entityId: target.entityId },
  280. scopeId: "edit::composer-edit:fixture",
  281. inputKind: "sendText",
  282. loadedText: "",
  283. lockConfirmed: false,
  284. });
  285. };
  286. const submitEdit = async (text: string) => {
  287. editedText = text;
  288. probe.submitted = true;
  289. store.markCommandPending({ commandId, type: "editUserQuery", issuedAt: Date.now() });
  290. const ack = await new Promise<CommandAck | false>((resolve) => {
  291. resolveAck = resolve;
  292. });
  293. if (ack) await store.waitForEditPresentation(commandId);
  294. if (ack) useComposerEditStore.getState().end(editKey);
  295. return ack;
  296. };
  297. function FixtureComposer() {
  298. const editing = useComposerEditStore((state) => state.sessions[editKey] !== undefined);
  299. const [submitting, setSubmitting] = useState(false);
  300. if (!editing) {
  301. return (
  302. <div className="h-16 w-full bg-background" data-testid="fixture-composer">
  303. Composer
  304. </div>
  305. );
  306. }
  307. return (
  308. <div className="h-16 w-full bg-background" data-testid="fixture-composer">
  309. <button
  310. type="button"
  311. data-testid="fixture-edit-submit"
  312. disabled={submitting}
  313. onClick={() => {
  314. setSubmitting(true);
  315. void submitEdit("E2E_EDIT_PRESENTATION 编辑后的问题").finally(() => setSubmitting(false));
  316. }}
  317. >
  318. Send
  319. </button>
  320. </div>
  321. );
  322. }
  323. function Fixture() {
  324. const [active, setActive] = useState(store);
  325. probe.switchSession = () => setActive(other);
  326. const state = useSyncExternalStore(
  327. (listener) => active.subscribe(listener),
  328. () => active.getState(),
  329. );
  330. const snapshot = state.snapshot;
  331. if (!snapshot) return null;
  332. const displayed = state.editPresentation?.rows ?? snapshot.rows;
  333. return (
  334. <div className="flex h-dvh flex-col bg-background text-foreground">
  335. <div className="flex min-h-0 flex-1">
  336. <ConversationTimeline
  337. rows={displayed.window}
  338. totalCount={displayed.totalCount}
  339. sessionKey={snapshot.sessionId}
  340. compactForRemoteControl={mobile}
  341. rowContext={{
  342. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  343. sessionId: snapshot.sessionId,
  344. theme,
  345. workspacePath: "/fixture",
  346. }}
  347. onEdit={beginEdit}
  348. bottomDock={<FixtureComposer />}
  349. />
  350. </div>
  351. </div>
  352. );
  353. }
  354. createRoot(document.getElementById("root")!).render(
  355. <ServiceProvider services={services}>
  356. <PlatformProvider platform={platform}>
  357. <StoreContext.Provider value={settings}>
  358. <TabStoreProvider>
  359. <ZCodeIntlProvider initialLocale={mobile ? "en-US" : "zh-CN"}>
  360. <TooltipProvider>
  361. <Fixture />
  362. </TooltipProvider>
  363. </ZCodeIntlProvider>
  364. </TabStoreProvider>
  365. </StoreContext.Provider>
  366. </PlatformProvider>
  367. </ServiceProvider>,
  368. );