app.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import type { ModelUsageSummary, TodoItem, TurnId } from "@zcode/contracts";
  2. import { getZCodeCopy } from "@zcode/i18n";
  3. import React, { useCallback, useMemo, useRef, useState } from "react";
  4. import { AppView } from "./app-view.js";
  5. import type { PromptInputEditor } from "./app-input-pane.js";
  6. import { selectionCopyStatus, type SelectionCopyResult } from "./app-copy.js";
  7. import { useClipboardImagePaste } from "./app-clipboard-image.js";
  8. import { useFileMentionController } from "./app-file-mentions.js";
  9. import { useTuiKeyboardControls } from "./app-keyboard.js";
  10. import { useTuiModeSwitcher } from "./app-mode.js";
  11. import { createTuiPermissionRequester } from "./app-permission.js";
  12. import { appendAgentResult } from "./app-submit.js";
  13. import { useSubmitValue } from "./app-submit-controller.js";
  14. import { filterSlashCommands, reconcileSlashSelection } from "./app-input.js";
  15. import { useEffortCommandController } from "./app-effort-command.js";
  16. import { useInputHistory } from "./app-input-history.js";
  17. import { useModeCommandController } from "./app-mode-command.js";
  18. import { useModelCommandController } from "./app-model-command.js";
  19. import { useSidebarController } from "./app-sidebar-layout.js";
  20. import { createSelectionState } from "./app-selection-state.js";
  21. import { resolveComposerSubmittedText } from "./app-submit-resolver.js";
  22. import type {
  23. ApprovalPrompt,
  24. CacheStats,
  25. ContextUsage,
  26. DraftAttachment,
  27. Message,
  28. ModifiedFileStat,
  29. NetworkRequest,
  30. QueuedInput,
  31. SelectionState,
  32. SlashSelectionState,
  33. } from "./app-model.js";
  34. import { useTuiThemeSync } from "./app-theme-sync.js";
  35. import { useSessionEventApplier } from "./app-session-event-handler.js";
  36. import { useTuiWorkflowRuns } from "./app-workflow-controller.js";
  37. import { useTuiApplyResult } from "./app-result.js";
  38. import { useSubagents } from "./app-subagents.js";
  39. import type { TuiOptions } from "./types.js";
  40. type TuiAppProps = {
  41. copySelection: () => Promise<SelectionCopyResult>;
  42. hasCopyableSelection: () => boolean;
  43. options: TuiOptions;
  44. onExit: (code: number) => void;
  45. };
  46. export function TuiApp({
  47. copySelection,
  48. hasCopyableSelection,
  49. onExit,
  50. options,
  51. }: TuiAppProps): React.ReactElement {
  52. // Startup sentinels are diagnostics, not user-visible transcript messages.
  53. const initialResult = options.initialResult;
  54. const initialLoginRequired = initialResult?.loginRequired ?? options.loginRequired ?? false;
  55. const initialLocale = options.locale ?? "en-US";
  56. const initialCopy = getZCodeCopy(initialLocale).tui;
  57. useTuiThemeSync(options);
  58. const [messages, setMessages] = useState<Message[]>(() =>
  59. initialResult
  60. ? appendAgentResult([], initialResult, { workspaceDirectory: options.workspaceDirectory })
  61. : [],
  62. );
  63. const [draft, setDraftState] = useState("");
  64. const [, setDraftAttachmentsState] = useState<DraftAttachment[]>([]);
  65. const [busy, setBusy] = useState(false);
  66. const [mode, setMode] = useState(initialResult?.mode ?? options.initialMode ?? "build");
  67. const [model, setModel] = useState(initialResult?.model ?? options.initialModel ?? "unknown");
  68. const [thoughtLevel, setThoughtLevel] = useState(
  69. initialResult?.thoughtLevel ?? options.initialThoughtLevel ?? "",
  70. );
  71. const [locale, setLocale] = useState(initialLocale);
  72. const [lastEvent, setLastEvent] = useState("idle");
  73. const [lastError, setLastError] = useState<string | undefined>();
  74. const copy = useMemo(() => getZCodeCopy(locale), [locale]);
  75. const [loginRequired, setLoginRequired] = useState(initialLoginRequired);
  76. const [status, setStatus] = useState(
  77. initialResult?.selection?.prompt ??
  78. (initialLoginRequired ? initialCopy.loginRequired.status : initialCopy.status.ready),
  79. );
  80. const [statusDetails, setStatusDetails] = useState<string[]>([]);
  81. const [traceId, setTraceId] = useState<string | undefined>();
  82. const [activeTurnId, setActiveTurnId] = useState<TurnId | undefined>();
  83. const [contextUsage, setContextUsage] = useState<ContextUsage>({});
  84. const [cacheStats, setCacheStats] = useState<CacheStats | undefined>();
  85. const [usage, setUsage] = useState<ModelUsageSummary | undefined>();
  86. const [todos, setTodos] = useState<TodoItem[]>([]);
  87. const [networkRequests, setNetworkRequests] = useState<NetworkRequest[]>([]);
  88. const [modifiedFiles, setModifiedFiles] = useState<ModifiedFileStat[]>([]);
  89. const [liveModelText, setLiveModelText] = useState("");
  90. const [queuedInputs, setQueuedInputs] = useState<QueuedInput[]>([]);
  91. const [selection, setSelection] = useState<SelectionState | undefined>(() =>
  92. createSelectionState(initialResult?.selection),
  93. );
  94. const [slashSelection, setSlashSelection] = useState<SlashSelectionState | undefined>();
  95. const [approvalQueue, setApprovalQueue] = useState<ApprovalPrompt[]>([]);
  96. const [inputCursorToEndVersion, setInputCursorToEndVersion] = useState(0);
  97. // dwf 运行态镜像:共享 reducer 逐事件维护 + 冷启动一次性补种,无第二时钟。
  98. const workflowRuns = useTuiWorkflowRuns({ copy: copy.tui, options, setMessages });
  99. const sidebar = useSidebarController();
  100. const subagents = useSubagents(options);
  101. const abortControllerRef = useRef<AbortController | undefined>(undefined);
  102. const draftRef = useRef("");
  103. const draftAttachmentsRef = useRef<DraftAttachment[]>([]);
  104. const inputEditorRef = useRef<PromptInputEditor | null>(null);
  105. const inputHistoryIndexRef = useRef(0);
  106. const inputHistoryDraftAttachmentsRef = useRef<DraftAttachment[] | undefined>(undefined);
  107. const inputHistoryDraftRef = useRef<string | undefined>(undefined);
  108. const nextAttachmentIdRef = useRef(1);
  109. const assistantMessageIdsByToolCallIdRef = useRef(new Map<string, string>());
  110. const modifiedFileToolCallIdsRef = useRef(new Set<string>());
  111. const toolNamesByIdRef = useRef(new Map<string, string>());
  112. const slashCommands = options.slashCommands ?? [];
  113. const [effortOptions, setEffortOptions] = useState<NonNullable<TuiOptions["effortOptions"]>>(
  114. () => initialResult?.effortOptions ?? options.effortOptions ?? [],
  115. );
  116. const filteredSlashCommands = useMemo(
  117. () => filterSlashCommands(draft, slashCommands),
  118. [draft, slashCommands],
  119. );
  120. const effortCommand = useEffortCommandController(draft, effortOptions);
  121. const modelCommand = useModelCommandController(draft, options);
  122. const modeCommand = useModeCommandController(draft);
  123. const setDraftAttachments = useCallback((action: React.SetStateAction<DraftAttachment[]>) => {
  124. const nextAttachments =
  125. typeof action === "function" ? action(draftAttachmentsRef.current) : action;
  126. draftAttachmentsRef.current = nextAttachments;
  127. setDraftAttachmentsState(nextAttachments);
  128. }, []);
  129. const setDraftValue = useCallback(
  130. (value: string) => {
  131. draftRef.current = value;
  132. setDraftState(value);
  133. setDraftAttachments((current) =>
  134. current.filter((attachment) => value.includes(attachment.placeholder)),
  135. );
  136. inputHistoryIndexRef.current = 0;
  137. inputHistoryDraftAttachmentsRef.current = undefined;
  138. inputHistoryDraftRef.current = undefined;
  139. const nextModelSelection = modelCommand.reconcileDraft(value);
  140. const nextEffortSelection = nextModelSelection
  141. ? undefined
  142. : effortCommand.reconcileDraft(value);
  143. const nextModeSelection =
  144. nextModelSelection || nextEffortSelection ? undefined : modeCommand.reconcileDraft(value);
  145. if (nextModelSelection) {
  146. effortCommand.setSelection(undefined);
  147. modeCommand.setSelection(undefined);
  148. } else if (nextEffortSelection) {
  149. modelCommand.setSelection(undefined);
  150. modeCommand.setSelection(undefined);
  151. } else if (nextModeSelection) {
  152. effortCommand.setSelection(undefined);
  153. modelCommand.setSelection(undefined);
  154. }
  155. setSlashSelection(
  156. nextModelSelection || nextEffortSelection || nextModeSelection
  157. ? undefined
  158. : reconcileSlashSelection(value, slashCommands),
  159. );
  160. },
  161. [effortCommand, modeCommand, modelCommand, setDraftAttachments, slashCommands],
  162. );
  163. const applyResult = useTuiApplyResult({
  164. fallback: { locale, loginRequired, mode, model },
  165. modifiedFileToolCallIds: modifiedFileToolCallIdsRef.current,
  166. setActiveTurnId,
  167. setCacheStats,
  168. setContextUsage,
  169. setEffortOptions,
  170. setLastEvent,
  171. setLiveModelText,
  172. setLocale,
  173. setLoginRequired,
  174. setMessages,
  175. setMode,
  176. setModel,
  177. setModelOptions: modelCommand.setModelOptions,
  178. setModifiedFiles,
  179. setNetworkRequests,
  180. setQueuedInputs,
  181. setSelection,
  182. setStatus,
  183. setThoughtLevel,
  184. setTodos,
  185. setTraceId,
  186. setUsage,
  187. workspaceDirectory: options.workspaceDirectory,
  188. });
  189. const applySessionEvent = useSessionEventApplier({
  190. subscribeSessionEvents: options.subscribeSessionEvents,
  191. observeSessionEvent: subagents.onEvent,
  192. copy: copy.tui,
  193. getMainSessionId: options.getMainSessionId,
  194. setActiveTurnId,
  195. setCacheStats,
  196. setContextUsage,
  197. setLastError,
  198. setLastEvent,
  199. setLiveModelText,
  200. setMessages,
  201. setModel,
  202. setThoughtLevel,
  203. setModifiedFiles,
  204. setNetworkRequests,
  205. setQueuedInputs,
  206. setStatus,
  207. setTodos,
  208. setUsage,
  209. setWorkflowMirror: workflowRuns.setMirror,
  210. assistantMessageIdsByToolCallId: assistantMessageIdsByToolCallIdRef.current,
  211. modifiedFileToolCallIds: modifiedFileToolCallIdsRef.current,
  212. toolNamesById: toolNamesByIdRef.current,
  213. workspaceDirectory: options.workspaceDirectory,
  214. });
  215. const requestPermission = useMemo(
  216. () => createTuiPermissionRequester({ setApprovalQueue, setStatus }),
  217. [],
  218. );
  219. const resolveSubmittedText = useCallback(
  220. (submittedValue: string) => {
  221. const modelOption = modelCommand.selectedOption(submittedValue);
  222. const effortOption = modelOption ? undefined : effortCommand.selectedOption(submittedValue);
  223. return resolveComposerSubmittedText({
  224. effortOption,
  225. modeOption:
  226. modelOption || effortOption ? undefined : modeCommand.selectedOption(submittedValue),
  227. modelOption,
  228. slashCommands: filteredSlashCommands,
  229. slashSelection,
  230. submittedValue,
  231. });
  232. },
  233. [effortCommand, filteredSlashCommands, modeCommand, modelCommand, slashSelection],
  234. );
  235. const submitValue = useSubmitValue({
  236. activeTurnId,
  237. applyResult,
  238. applySessionEvent,
  239. busy,
  240. draftAttachmentsRef,
  241. emptyPromptStatus: copy.tui.input.typePrompt,
  242. messageInsertIndex: messages.length,
  243. options,
  244. requestPermission,
  245. resolveSubmittedText,
  246. resolveSubmittedModel: (value) => modelCommand.selectedOption(value)?.ref,
  247. setBusy,
  248. setDraftAttachments,
  249. setDraftValue,
  250. setLastError,
  251. setLiveModelText,
  252. setMessages,
  253. setQueuedInputs,
  254. setSelection,
  255. setSlashSelection,
  256. setStatus,
  257. setStatusDetails,
  258. turnRef: abortControllerRef,
  259. });
  260. const pasteClipboardImage = useClipboardImagePaste({
  261. abortControllerRef,
  262. busy,
  263. getDraftValue: () => draftRef.current,
  264. inputEditorRef,
  265. nextAttachmentIdRef,
  266. options,
  267. setDraftAttachments,
  268. setDraftValue,
  269. setStatus,
  270. setStatusDetails,
  271. });
  272. const { recallNextInput, recallPreviousInput } = useInputHistory({
  273. copy: copy.tui,
  274. draftAttachmentsRef,
  275. draftRef,
  276. inputHistoryDraftAttachmentsRef,
  277. inputHistoryDraftRef,
  278. inputHistoryIndexRef,
  279. nextAttachmentIdRef,
  280. options,
  281. setDraftAttachments,
  282. setDraftState,
  283. setDraftValue,
  284. setInputCursorToEndVersion,
  285. setSlashSelection,
  286. setStatus,
  287. setStatusDetails,
  288. });
  289. const fileMentions = useFileMentionController({
  290. busy,
  291. draft,
  292. editorRef: inputEditorRef,
  293. listWorkspacePathSuggestions: options.listWorkspacePathSuggestions,
  294. nextAttachmentIdRef,
  295. setDraftAttachments,
  296. setDraftValue,
  297. setSlashSelection,
  298. setStatus,
  299. });
  300. const copyCurrentSelection = useCallback((): boolean => {
  301. if (!hasCopyableSelection()) return false;
  302. void copySelection().then((result) => {
  303. const copyStatus = selectionCopyStatus(result, copy.tui.copy);
  304. if (copyStatus.status) setStatus(copyStatus.status);
  305. if (copyStatus.details) setStatusDetails(copyStatus.details);
  306. });
  307. return true;
  308. }, [copy, copySelection, hasCopyableSelection]);
  309. const switchMode = useTuiModeSwitcher({
  310. mode,
  311. setMode,
  312. setModeHandler: options.setMode,
  313. setStatus,
  314. });
  315. useTuiKeyboardControls({
  316. readOnlyView: subagents.selected ? { back: subagents.back } : undefined,
  317. abortControllerRef,
  318. approvalQueue,
  319. busy,
  320. copyCurrentSelection,
  321. effortSelection: effortCommand.selection,
  322. filteredEffortOptions: effortCommand.filteredOptions,
  323. filteredSlashCommands,
  324. filteredModeOptions: modeCommand.filteredOptions,
  325. filteredModelOptions: modelCommand.filteredOptions,
  326. handleFileMentionKey: fileMentions.handleKey,
  327. onExit,
  328. pasteClipboardImage,
  329. recallNextInput,
  330. recallPreviousInput,
  331. draftValue: draft,
  332. inputHistoryActive: inputHistoryDraftRef.current !== undefined,
  333. messages,
  334. modelSelection: modelCommand.selection,
  335. modeSelection: modeCommand.selection,
  336. selection,
  337. setApprovalQueue,
  338. setDraftAttachments,
  339. setDraftValue,
  340. setEffortSelection: effortCommand.setSelection,
  341. setModelSelection: modelCommand.setSelection,
  342. setModeSelection: modeCommand.setSelection,
  343. setSelection,
  344. setSlashSelection,
  345. setStatus,
  346. slashSelection,
  347. submitValue,
  348. switchMode,
  349. workflowExpansion: workflowRuns.expansion,
  350. toggleSidebar: sidebar.toggleSidebar,
  351. toggleSidebarSection: sidebar.toggleSidebarSection,
  352. });
  353. return React.createElement(AppView, {
  354. subagents,
  355. toggleSidebar: sidebar.toggleSidebar,
  356. activeTurnId,
  357. approvalQueue,
  358. busy,
  359. cacheStats,
  360. contextUsage,
  361. copy: copy.tui,
  362. copyCurrentSelection,
  363. draft,
  364. editorRef: inputEditorRef,
  365. inputCursorToEndVersion,
  366. lastError,
  367. lastEvent,
  368. loginRequired,
  369. liveModelText,
  370. mode,
  371. model,
  372. messages,
  373. modifiedFiles,
  374. networkRequests,
  375. options,
  376. queuedInputs,
  377. selection,
  378. fileMention: fileMentions.state,
  379. setDraftValue,
  380. sidebarLayout: sidebar.layout,
  381. sidebarSections: sidebar.sections,
  382. effortOptions: effortCommand.filteredOptions,
  383. effortSelection: effortCommand.selection,
  384. modelOptions: modelCommand.filteredOptions,
  385. modelSelection: modelCommand.selection,
  386. modeOptions: modeCommand.filteredOptions,
  387. modeSelection: modeCommand.selection,
  388. slashCommands: filteredSlashCommands,
  389. slashSelection,
  390. status,
  391. statusDetails,
  392. submitValue,
  393. thoughtLevel,
  394. todos,
  395. toggleSidebarSection: sidebar.toggleSidebarSection,
  396. traceId,
  397. terminalWidth: sidebar.terminalWidth,
  398. usage,
  399. workflowCardsByToolCallId: workflowRuns.cardsByToolCallId,
  400. expandedWorkflowRunIds: workflowRuns.expandedRunIds,
  401. });
  402. }