app-subagents.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import React from "react";
  2. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  3. import type {
  4. ZCodeSessionSubagentsResult,
  5. ZCodeSessionRunningSubagent,
  6. ZCodeSessionEndedSubagent,
  7. } from "@zcode/shared";
  8. import type { TuiOptions } from "./types.js";
  9. import { changesSubagentDirectory } from "./app-subagent-events.js";
  10. import {
  11. applySubagentTranscriptEvent,
  12. hydrateSubagentTranscript,
  13. type SubagentTranscript,
  14. } from "./app-subagent-transcript.js";
  15. export type SubagentItem = ZCodeSessionRunningSubagent | ZCodeSessionEndedSubagent;
  16. const EMPTY_DIRECTORY: ZCodeSessionSubagentsResult = {
  17. revision: 0,
  18. childSessionIds: [],
  19. running: [],
  20. ended: { total: 0, items: [] },
  21. };
  22. export function useSubagents(options: TuiOptions) {
  23. const sessionId = options.getMainSessionId?.();
  24. const [directory, setDirectory] = React.useState(EMPTY_DIRECTORY);
  25. const [directoryError, setDirectoryError] = React.useState<string>();
  26. const [selected, setSelected] = React.useState<SubagentItem>();
  27. const [transcript, setTranscript] = React.useState<SubagentTranscript>();
  28. const [loading, setLoading] = React.useState(false);
  29. const [error, setError] = React.useState<string>();
  30. const generation = React.useRef(0);
  31. const selection = React.useRef<SubagentItem | undefined>(undefined);
  32. const pendingEvents = React.useRef<SessionEvent[] | null>(null);
  33. const loaded = React.useRef<SubagentTranscript | undefined>(undefined);
  34. const directoryGeneration = React.useRef(0);
  35. const directoryRequest = React.useRef<Promise<void> | undefined>(undefined);
  36. const directoryDirty = React.useRef(false);
  37. const directoryRef = React.useRef(directory);
  38. directoryRef.current = directory;
  39. const refreshDirectory = React.useCallback((): void => {
  40. if (!options.readSubagents) return;
  41. directoryDirty.current = true;
  42. if (directoryRequest.current) return;
  43. const epoch = directoryGeneration.current;
  44. const parentId = options.getMainSessionId?.();
  45. directoryRequest.current = (async () => {
  46. while (directoryDirty.current && epoch === directoryGeneration.current) {
  47. directoryDirty.current = false;
  48. try {
  49. const snapshot = await options.readSubagents!();
  50. if (epoch !== directoryGeneration.current || parentId !== options.getMainSessionId?.())
  51. return;
  52. setDirectory(snapshot);
  53. setDirectoryError(undefined);
  54. } catch (cause) {
  55. if (epoch === directoryGeneration.current) setDirectoryError(String(cause));
  56. }
  57. }
  58. })().finally(() => {
  59. if (epoch === directoryGeneration.current) {
  60. directoryRequest.current = undefined;
  61. // An event can invalidate the directory after the loop exits but before
  62. // this continuation runs. Preserve that final refresh request as well.
  63. if (directoryDirty.current) refreshDirectory();
  64. }
  65. });
  66. }, [options]);
  67. const back = React.useCallback(() => {
  68. generation.current += 1;
  69. selection.current = undefined;
  70. pendingEvents.current = null;
  71. loaded.current = undefined;
  72. setSelected(undefined);
  73. setTranscript(undefined);
  74. setLoading(false);
  75. setError(undefined);
  76. }, []);
  77. const open = React.useCallback(
  78. (item: SubagentItem) => {
  79. const epoch = ++generation.current;
  80. const parentId = options.getMainSessionId?.();
  81. selection.current = item;
  82. pendingEvents.current = [];
  83. loaded.current = undefined;
  84. setSelected(item);
  85. setTranscript(undefined);
  86. setLoading(true);
  87. setError(undefined);
  88. void (async () => {
  89. try {
  90. if (!options.readSubagentTranscript)
  91. throw new Error("Subagent transcript is unavailable.");
  92. const snapshot = await options.readSubagentTranscript(item.childSessionId);
  93. if (epoch !== generation.current || parentId !== options.getMainSessionId?.()) return;
  94. if (snapshot.sessionId !== item.childSessionId)
  95. throw new Error("Subagent transcript session mismatch.");
  96. let next = hydrateSubagentTranscript(snapshot, options.workspaceDirectory);
  97. for (const event of pendingEvents.current ?? [])
  98. next = applySubagentTranscriptEvent(next, event, options.workspaceDirectory);
  99. pendingEvents.current = null;
  100. loaded.current = next;
  101. setTranscript(next);
  102. } catch (cause) {
  103. if (epoch === generation.current) {
  104. pendingEvents.current = null;
  105. setError(String(cause));
  106. }
  107. } finally {
  108. if (epoch === generation.current) setLoading(false);
  109. }
  110. })();
  111. },
  112. [options],
  113. );
  114. React.useEffect(() => {
  115. directoryGeneration.current += 1;
  116. directoryRequest.current = undefined;
  117. setDirectory(EMPTY_DIRECTORY);
  118. setDirectoryError(undefined);
  119. back();
  120. refreshDirectory();
  121. return () => {
  122. generation.current += 1;
  123. directoryGeneration.current += 1;
  124. };
  125. }, [sessionId, refreshDirectory, back]);
  126. const onEvent = React.useCallback(
  127. (event: SessionEvent) => {
  128. if (
  129. changesSubagentDirectory(event) &&
  130. (event.type !== SessionEventType.ToolCallResult ||
  131. event.sessionId === options.getMainSessionId?.())
  132. )
  133. refreshDirectory();
  134. if (event.sessionId !== selection.current?.childSessionId) return;
  135. if (pendingEvents.current) {
  136. pendingEvents.current.push(event);
  137. if (pendingEvents.current.length > 4096 && selection.current) open(selection.current);
  138. } else if (loaded.current) {
  139. if (event.sequenceNumber > loaded.current.sequenceNumber + 1 && selection.current) {
  140. open(selection.current);
  141. return;
  142. }
  143. const next = applySubagentTranscriptEvent(
  144. loaded.current,
  145. event,
  146. options.workspaceDirectory,
  147. );
  148. if (next !== loaded.current) {
  149. loaded.current = next;
  150. setTranscript(next);
  151. }
  152. }
  153. },
  154. [options, refreshDirectory, open],
  155. );
  156. const loadMore = React.useCallback(async () => {
  157. const cursor = directoryRef.current.ended.nextCursor;
  158. if (!cursor || !options.readSubagents) return;
  159. const epoch = directoryGeneration.current;
  160. try {
  161. const page = await options.readSubagents({ endedCursor: cursor });
  162. if (epoch !== directoryGeneration.current) return;
  163. setDirectory((current) => ({
  164. ...current,
  165. ended: {
  166. ...page.ended,
  167. items: [
  168. ...new Map(
  169. [...current.ended.items, ...page.ended.items].map((item) => [
  170. item.childSessionId,
  171. item,
  172. ]),
  173. ).values(),
  174. ],
  175. },
  176. }));
  177. } catch (cause) {
  178. if (epoch === directoryGeneration.current) setDirectoryError(String(cause));
  179. }
  180. }, [options]);
  181. return {
  182. directory,
  183. directoryError,
  184. selected:
  185. selected &&
  186. ([...directory.running, ...directory.ended.items].find(
  187. (item) => item.childSessionId === selected.childSessionId,
  188. ) ??
  189. selected),
  190. transcript,
  191. loading,
  192. error,
  193. open,
  194. back,
  195. onEvent,
  196. loadMore,
  197. refreshDirectory,
  198. };
  199. }
  200. export type SubagentsController = ReturnType<typeof useSubagents>;