The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { useAtomValue } from "@effect/atom-react"; |
| 3 | import { msg } from "gt-react"; |
| 4 | import { |
| 5 | type CheckpointDiffTarget, |
| 6 | type ComposerPathSearchTarget, |
| 7 | } from "@t3tools/client-runtime/state/threads"; |
| 8 | import { |
| 9 | createThreadSearchResultsAtomFamily, |
| 10 | makeThreadSearchKey, |
| 11 | visibleThreadSearch, |
| 12 | type EnvironmentThreadSearchMatch, |
| 13 | type SettledThreadSearch, |
| 14 | type ThreadSearchResultsState, |
| 15 | type ThreadSearchScope, |
| 16 | } from "@t3tools/client-runtime/state/thread-search"; |
| 17 | import { |
| 18 | ProjectSearchContentsError, |
| 19 | PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH, |
| 20 | THREAD_SEARCH_QUERY_MAX_LENGTH, |
| 21 | } from "@t3tools/contracts"; |
| 22 | import { messageSearchTokens } from "@t3tools/shared/paletteSearch"; |
| 23 | import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs"; |
| 24 | import type { |
| 25 | EnvironmentId, |
| 26 | OrchestrationV2GetTurnItemResult, |
| 27 | ProjectContentMatch, |
| 28 | ProjectEntry, |
| 29 | ProjectEntryKind, |
| 30 | ThreadId, |
| 31 | TurnItemId, |
| 32 | VcsListRefsResult, |
| 33 | VcsRef, |
| 34 | } from "@t3tools/contracts"; |
| 35 | import * as Cause from "effect/Cause"; |
| 36 | import * as Schema from "effect/Schema"; |
| 37 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 38 | import { useEffect, useState } from "react"; |
| 39 | |
| 40 | import { m, type MessageResolver } from "../i18n/messages"; |
| 41 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 42 | import { useFilesystemReadAccess } from "./filesystem"; |
| 43 | import { orchestrationEnvironment } from "./orchestration"; |
| 44 | import { olderSettledThreads, threadFamilies } from "./threads"; |
| 45 | import { isPaginatedBranchesNextPagePending } from "./paginatedBranches"; |
| 46 | import { projectContentSearch, projectEnvironment } from "./projects"; |
| 47 | import { useEnvironmentQuery } from "./query"; |
| 48 | import { vcsEnvironment } from "./vcs"; |
| 49 | |
| 50 | const PROJECT_PATH_SEARCH_DEBOUNCE_MS = 120; |
| 51 | const COMPOSER_PATH_SEARCH_LIMIT = 80; |
| 52 | const PROJECT_CONTENT_SEARCH_DEBOUNCE_MS = 120; |
| 53 | const PROJECT_CONTENT_SEARCH_LIMIT = 500; |
| 54 | const PROJECT_CONTENT_SEARCH_SCAN_RETRY_MS = 30_000; |
| 55 | const isProjectSearchContentsError = Schema.is(ProjectSearchContentsError); |
| 56 | const THREAD_SEARCH_DEBOUNCE_MS = 120; |
| 57 | const VCS_REF_LIST_LIMIT = 100; |
| 58 | const EMPTY_REFS: ReadonlyArray<VcsRef> = []; |
| 59 | const EMPTY_PROJECT_ENTRIES: ReadonlyArray<ProjectEntry> = []; |
| 60 | const EMPTY_CONTENT_MATCHES: ReadonlyArray<ProjectContentMatch> = []; |
| 61 | const INITIAL_BRANCH_CURSORS = [undefined] as const; |
| 62 | const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]); |
| 63 | const EMPTY_THREAD_SEARCH_ATOM = Atom.make<ThreadSearchResultsState>({ |
| 64 | matches: EMPTY_THREAD_SEARCH_MATCHES, |
| 65 | isLoading: false, |
| 66 | failed: false, |
| 67 | rows: [], |
| 68 | }).pipe(Atom.withLabel("web:thread-search:empty")); |
| 69 | |
| 70 | const olderSettledBeforeAtom = Atom.family((environmentId: EnvironmentId) => |
| 71 | Atom.make((get) => get(olderSettledThreads.olderSettledAtom(environmentId))?.before ?? null).pipe( |
| 72 | Atom.withLabel(`web:older-settled-before:${environmentId}`), |
| 73 | ), |
| 74 | ); |
| 75 | // Whether any of these environments leaves older settled threads out, so short queries matter. |
| 76 | const anyOlderSettledAtom = Atom.family((environmentIdsKey: string) => |
| 77 | Atom.make((get) => |
| 78 | (JSON.parse(environmentIdsKey) as ReadonlyArray<EnvironmentId>).some( |
| 79 | (environmentId) => get(olderSettledBeforeAtom(environmentId)) !== null, |
| 80 | ), |
| 81 | ).pipe(Atom.withLabel(`web:any-older-settled:${environmentIdsKey}`)), |
| 82 | ); |
| 83 | const threadSearch = createThreadSearchResultsAtomFamily({ |
| 84 | getSearchAtom: (environmentId, input) => |
| 85 | input.olderSettledBefore === undefined |
| 86 | ? orchestrationEnvironment.threadSearch({ environmentId, input }) |
| 87 | : olderSettledThreads.searchAtom(environmentId, input), |
| 88 | olderSettledBefore: olderSettledBeforeAtom, |
| 89 | labelPrefix: "web:thread-search", |
| 90 | }); |
| 91 | |
| 92 | export function useDebouncedValue<A>(value: A, delayMs: number): A { |
| 93 | const [debounced, setDebounced] = useState(value); |
| 94 | |
| 95 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce timer that publishes the value after delayMs |
| 96 | useEffect(() => { |
| 97 | const timer = window.setTimeout(() => { |
| 98 | setDebounced(value); |
| 99 | }, delayMs); |
| 100 | return () => { |
| 101 | window.clearTimeout(timer); |
| 102 | }; |
| 103 | }, [delayMs, value]); |
| 104 | |
| 105 | return debounced; |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Server matches for a thread search: message hits, and on environments that leave older settled |
| 110 | * threads out of the shell, the rows of the best older matches, mounted into the thread list while |
| 111 | * they show so the caller's own ranking finds them. |
| 112 | */ |
| 113 | export function useThreadSearch( |
| 114 | environmentIds: ReadonlyArray<EnvironmentId>, |
| 115 | query: string, |
| 116 | scope: ThreadSearchScope = {}, |
| 117 | ): { |
| 118 | readonly matches: ReadonlyArray<EnvironmentThreadSearchMatch>; |
| 119 | readonly query: string; |
| 120 | readonly isPending: boolean; |
| 121 | /** No environment could run the search for the current query, so an empty result is not "no matches". */ |
| 122 | readonly failed: boolean; |
| 123 | } { |
| 124 | // A pasted wall of text searches by its start rather than failing the request. |
| 125 | const normalizedQuery = query.trim().slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH).trim(); |
| 126 | const debouncedQuery = useDebouncedValue(normalizedQuery, THREAD_SEARCH_DEBOUNCE_MS); |
| 127 | const anyOlderSettled = useAtomValue(anyOlderSettledAtom(JSON.stringify(environmentIds))); |
| 128 | // Messages need a word of three or more letters; older settled titles match from two. |
| 129 | const canSearch = |
| 130 | environmentIds.length > 0 && |
| 131 | ((scope.titlesOnly !== true && messageSearchTokens(normalizedQuery).long.length > 0) || |
| 132 | (anyOlderSettled && normalizedQuery.length >= 2)); |
| 133 | const settledQuery = canSearch && normalizedQuery === debouncedQuery ? debouncedQuery : null; |
| 134 | const searchKeyOf = (searchQuery: string) => |
| 135 | makeThreadSearchKey(environmentIds, searchQuery, scope); |
| 136 | const searchKey = settledQuery === null ? null : searchKeyOf(settledQuery); |
| 137 | const result = useAtomValue( |
| 138 | searchKey === null ? EMPTY_THREAD_SEARCH_ATOM : threadSearch.results(searchKey), |
| 139 | ); |
| 140 | const isPending = canSearch && (normalizedQuery !== debouncedQuery || result.isLoading); |
| 141 | const failed = settledQuery !== null && !result.isLoading && result.failed; |
| 142 | // What fast environments returned shows without waiting for a slow one; |
| 143 | // callers keep shown rows in place with `nextShownOrder`. |
| 144 | const ready = |
| 145 | settledQuery !== null && |
| 146 | (!result.isLoading || result.matches.length > 0 || result.rows.length > 0) |
| 147 | ? { query: settledQuery, matches: result.matches } |
| 148 | : null; |
| 149 | // Kept from earlier renders: React's pattern for information from previous renders. |
| 150 | const [previous, setPrevious] = useState<SettledThreadSearch | null>(null); |
| 151 | if (ready !== null && previous?.matches !== ready.matches) setPrevious(ready); |
| 152 | const visible = canSearch |
| 153 | ? visibleThreadSearch(normalizedQuery, ready, previous) |
| 154 | : { query: "", matches: EMPTY_THREAD_SEARCH_MATCHES }; |
| 155 | // The shown results' rows stay mounted until newer results replace them. |
| 156 | const shownKey = visible.query === "" ? null : searchKeyOf(visible.query); |
| 157 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mounts the shown search results' rows into the thread family registry until newer results replace them |
| 158 | useEffect(() => { |
| 159 | if (shownKey === null) return; |
| 160 | const environments = (JSON.parse(shownKey) as [ReadonlyArray<EnvironmentId>])[0]; |
| 161 | const releases = environments.map((environmentId) => |
| 162 | threadFamilies.mountRows( |
| 163 | appAtomRegistry, |
| 164 | environmentId, |
| 165 | `search:${shownKey}`, |
| 166 | threadSearch.rows(shownKey, environmentId), |
| 167 | ), |
| 168 | ); |
| 169 | return () => { |
| 170 | for (const release of releases) release(); |
| 171 | }; |
| 172 | }, [shownKey]); |
| 173 | return { |
| 174 | matches: visible.matches, |
| 175 | query: visible.query, |
| 176 | isPending, |
| 177 | failed, |
| 178 | }; |
| 179 | } |
| 180 | |
| 181 | function vcsRefPageAtom(targetKey: string, cursor: number | undefined) { |
| 182 | const [environmentId, cwd, query] = JSON.parse(targetKey) as [EnvironmentId, string, string]; |
| 183 | return vcsEnvironment.listRefs({ |
| 184 | environmentId, |
| 185 | input: { |
| 186 | cwd, |
| 187 | ...(query.length > 0 ? { query } : {}), |
| 188 | ...(cursor === undefined ? {} : { cursor }), |
| 189 | limit: VCS_REF_LIST_LIMIT, |
| 190 | }, |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | const EMPTY_VCS_REF_PAGES_ATOM = Atom.make< |
| 195 | ReadonlyArray<Atom.Type<ReturnType<typeof vcsRefPageAtom>>> |
| 196 | >([]).pipe(Atom.withLabel("web:vcs-ref-pages:empty")); |
| 197 | |
| 198 | const vcsRefPagesAtom = Atom.family((pagesKey: string) => { |
| 199 | const [targetKey, cursors] = JSON.parse(pagesKey) as [string, Array<number | null>]; |
| 200 | const pageAtoms = cursors.map((cursor) => vcsRefPageAtom(targetKey, cursor ?? undefined)); |
| 201 | return Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe( |
| 202 | Atom.withLabel(`web:vcs-ref-pages:${pagesKey}`), |
| 203 | ); |
| 204 | }); |
| 205 | |
| 206 | export function usePaginatedBranches(target: VcsRefTarget, resolve: MessageResolver = m) { |
| 207 | // Leave unkeyed; mismatches already reset cursors, and a seeded key would break caching across the hook. |
| 208 | const [pagination, setPagination] = useState<{ |
| 209 | readonly targetKey: string | null; |
| 210 | readonly cursors: ReadonlyArray<number | undefined>; |
| 211 | }>({ |
| 212 | targetKey: null, |
| 213 | cursors: INITIAL_BRANCH_CURSORS, |
| 214 | }); |
| 215 | const { environmentId, cwd } = target; |
| 216 | const query = target.query?.trim() ?? ""; |
| 217 | const targetKey = |
| 218 | environmentId !== null && cwd !== null ? JSON.stringify([environmentId, cwd, query]) : null; |
| 219 | const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS; |
| 220 | const pagesKey = targetKey === null ? null : JSON.stringify([targetKey, cursors]); |
| 221 | const results = useAtomValue( |
| 222 | pagesKey === null ? EMPTY_VCS_REF_PAGES_ATOM : vcsRefPagesAtom(pagesKey), |
| 223 | ); |
| 224 | const values = results.flatMap((result) => { |
| 225 | const value = AsyncResult.getOrElse(result, () => null); |
| 226 | return value === null ? [] : [value]; |
| 227 | }); |
| 228 | const refs = new Map<string, VcsRef>(); |
| 229 | for (const value of values) { |
| 230 | for (const ref of value.refs) { |
| 231 | refs.set(ref.name, ref); |
| 232 | } |
| 233 | } |
| 234 | const first = values[0] ?? null; |
| 235 | const last = values.at(-1) ?? null; |
| 236 | const data: VcsListRefsResult | null = |
| 237 | first === null || last === null |
| 238 | ? null |
| 239 | : { |
| 240 | refs: [...refs.values()], |
| 241 | isRepo: first.isRepo, |
| 242 | hasPrimaryRemote: first.hasPrimaryRemote, |
| 243 | nextCursor: last.nextCursor, |
| 244 | totalCount: Math.max(...values.map((value) => value.totalCount)), |
| 245 | }; |
| 246 | const failed = results.find((result) => result._tag === "Failure"); |
| 247 | const isFetchingNextPage = isPaginatedBranchesNextPagePending(results); |
| 248 | const error = |
| 249 | failed?._tag === "Failure" |
| 250 | ? (() => { |
| 251 | const cause = Cause.squash(failed.cause); |
| 252 | return ( |
| 253 | (cause instanceof Error ? errorDisplayMessage(cause, resolve) : null) ?? |
| 254 | resolve(msg("Failed to load refs.")) |
| 255 | ); |
| 256 | })() |
| 257 | : null; |
| 258 | const refresh = () => { |
| 259 | setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS }); |
| 260 | if (targetKey !== null) { |
| 261 | appAtomRegistry.refresh(vcsRefPageAtom(targetKey, undefined)); |
| 262 | } |
| 263 | }; |
| 264 | const nextCursor = data?.nextCursor; |
| 265 | const loadNext = () => { |
| 266 | if (targetKey === null || nextCursor === null || nextCursor === undefined) { |
| 267 | return; |
| 268 | } |
| 269 | setPagination((current) => { |
| 270 | const currentCursors = |
| 271 | current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS; |
| 272 | return currentCursors.includes(nextCursor) |
| 273 | ? { targetKey, cursors: currentCursors } |
| 274 | : { targetKey, cursors: [...currentCursors, nextCursor] }; |
| 275 | }); |
| 276 | }; |
| 277 | |
| 278 | return { |
| 279 | data, |
| 280 | refs: data?.refs ?? EMPTY_REFS, |
| 281 | error, |
| 282 | isPending: results.some((result) => result.waiting), |
| 283 | isFetchingNextPage, |
| 284 | refresh, |
| 285 | loadNext, |
| 286 | }; |
| 287 | } |
| 288 | |
| 289 | type ProjectPathSearchTarget = ComposerPathSearchTarget & { |
| 290 | readonly kind?: ProjectEntryKind | undefined; |
| 291 | readonly imageOnly?: boolean | undefined; |
| 292 | }; |
| 293 | |
| 294 | function areProjectPathSearchTargetsEqual( |
| 295 | left: ProjectPathSearchTarget, |
| 296 | right: ProjectPathSearchTarget, |
| 297 | ): boolean { |
| 298 | return ( |
| 299 | left.environmentId === right.environmentId && |
| 300 | left.cwd === right.cwd && |
| 301 | left.query === right.query && |
| 302 | left.kind === right.kind && |
| 303 | left.imageOnly === right.imageOnly |
| 304 | ); |
| 305 | } |
| 306 | |
| 307 | export function useProjectPathSearch( |
| 308 | target: ProjectPathSearchTarget, |
| 309 | limit: number, |
| 310 | options?: { readonly allowEmptyQuery?: boolean }, |
| 311 | resolve: MessageResolver = m, |
| 312 | ) { |
| 313 | const allowEmptyQuery = options?.allowEmptyQuery === true; |
| 314 | const normalizedTarget = { |
| 315 | environmentId: target.environmentId, |
| 316 | cwd: target.cwd, |
| 317 | query: target.query == null ? null : target.query.trim(), |
| 318 | kind: target.kind, |
| 319 | imageOnly: target.imageOnly, |
| 320 | }; |
| 321 | const debouncedTarget = useDebouncedValue(normalizedTarget, PROJECT_PATH_SEARCH_DEBOUNCE_MS); |
| 322 | const fileAccess = useFilesystemReadAccess(debouncedTarget.environmentId, resolve); |
| 323 | const { canReadFiles } = fileAccess; |
| 324 | const searchTarget = |
| 325 | debouncedTarget.environmentId !== null && |
| 326 | debouncedTarget.cwd !== null && |
| 327 | debouncedTarget.query !== null && |
| 328 | (allowEmptyQuery || debouncedTarget.query.length > 0) |
| 329 | ? { |
| 330 | environmentId: debouncedTarget.environmentId, |
| 331 | input: { |
| 332 | cwd: debouncedTarget.cwd, |
| 333 | query: debouncedTarget.query.slice(0, 256).replace(/[\uD800-\uDBFF]$/, ""), |
| 334 | limit, |
| 335 | ...(debouncedTarget.kind ? { kind: debouncedTarget.kind } : {}), |
| 336 | ...(debouncedTarget.imageOnly ? { imageOnly: true } : {}), |
| 337 | }, |
| 338 | } |
| 339 | : null; |
| 340 | const result = useEnvironmentQuery( |
| 341 | canReadFiles && searchTarget !== null ? projectEnvironment.searchEntries(searchTarget) : null, |
| 342 | resolve, |
| 343 | ); |
| 344 | const hasTarget = searchTarget !== null; |
| 345 | |
| 346 | return { |
| 347 | entries: result.data?.entries ?? EMPTY_PROJECT_ENTRIES, |
| 348 | error: |
| 349 | !hasTarget || fileAccess.isPending |
| 350 | ? null |
| 351 | : canReadFiles |
| 352 | ? result.error |
| 353 | : (fileAccess.error ?? resolve(msg("This connection cannot search host files."))), |
| 354 | isPending: |
| 355 | !areProjectPathSearchTargetsEqual(normalizedTarget, debouncedTarget) || |
| 356 | (hasTarget && (fileAccess.isPending || result.isPending)), |
| 357 | searchedTarget: debouncedTarget, |
| 358 | searchedQuery: debouncedTarget.query ?? "", |
| 359 | truncated: result.data?.truncated ?? false, |
| 360 | refresh: result.refresh, |
| 361 | }; |
| 362 | } |
| 363 | |
| 364 | export function useComposerPathSearch( |
| 365 | target: ComposerPathSearchTarget, |
| 366 | resolve: MessageResolver = m, |
| 367 | ) { |
| 368 | return useProjectPathSearch( |
| 369 | target, |
| 370 | COMPOSER_PATH_SEARCH_LIMIT, |
| 371 | { allowEmptyQuery: true }, |
| 372 | resolve, |
| 373 | ); |
| 374 | } |
| 375 | |
| 376 | interface ProjectContentSearchTarget { |
| 377 | readonly environmentId: EnvironmentId | null; |
| 378 | readonly cwd: string | null; |
| 379 | readonly query: string; |
| 380 | readonly caseSensitive: boolean; |
| 381 | readonly wholeWord: boolean; |
| 382 | readonly useRegex: boolean; |
| 383 | } |
| 384 | |
| 385 | export function useProjectContentSearch( |
| 386 | target: ProjectContentSearchTarget, |
| 387 | resolve: MessageResolver = m, |
| 388 | ) { |
| 389 | const hasTarget = target.environmentId !== null && target.cwd !== null; |
| 390 | const fileAccess = useFilesystemReadAccess(target.environmentId, resolve); |
| 391 | const canReadFiles = hasTarget && fileAccess.canReadFiles; |
| 392 | const isCheckingAccess = hasTarget && fileAccess.isPending; |
| 393 | // Preserve query whitespace; trim only to detect blank input. |
| 394 | const query = target.query; |
| 395 | const hasQuery = query.trim().length > 0; |
| 396 | const queryTooLong = query.length > PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH; |
| 397 | const debouncedQuery = useDebouncedValue(query, PROJECT_CONTENT_SEARCH_DEBOUNCE_MS); |
| 398 | const result = useEnvironmentQuery( |
| 399 | canReadFiles && |
| 400 | target.environmentId !== null && |
| 401 | target.cwd !== null && |
| 402 | hasQuery && |
| 403 | !queryTooLong && |
| 404 | debouncedQuery.trim().length > 0 && |
| 405 | debouncedQuery.length <= PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH |
| 406 | ? projectContentSearch({ |
| 407 | environmentId: target.environmentId, |
| 408 | input: { |
| 409 | cwd: target.cwd, |
| 410 | query: debouncedQuery, |
| 411 | limit: PROJECT_CONTENT_SEARCH_LIMIT, |
| 412 | caseSensitive: target.caseSensitive, |
| 413 | wholeWord: target.wholeWord, |
| 414 | useRegex: target.useRegex, |
| 415 | }, |
| 416 | }) |
| 417 | : null, |
| 418 | resolve, |
| 419 | ); |
| 420 | // Only once the timeout has come back: a refresh restarts a search still in flight. |
| 421 | const settledScanTimeout = |
| 422 | !result.isPending && |
| 423 | isProjectSearchContentsError(result.failure) && |
| 424 | result.failure.failure === "search_index_scan_timed_out" |
| 425 | ? result.failure |
| 426 | : null; |
| 427 | const { refresh } = result; |
| 428 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retry timer: nothing tells the client when the server's first scan ends |
| 429 | useEffect(() => { |
| 430 | if (settledScanTimeout === null) return; |
| 431 | const timer = window.setTimeout(refresh, PROJECT_CONTENT_SEARCH_SCAN_RETRY_MS); |
| 432 | return () => { |
| 433 | window.clearTimeout(timer); |
| 434 | }; |
| 435 | }, [refresh, settledScanTimeout]); |
| 436 | |
| 437 | return { |
| 438 | canReadFiles, |
| 439 | isCheckingAccess, |
| 440 | matches: result.data?.matches ?? EMPTY_CONTENT_MATCHES, |
| 441 | error: |
| 442 | !hasTarget || isCheckingAccess |
| 443 | ? null |
| 444 | : !canReadFiles |
| 445 | ? (fileAccess.error ?? resolve(msg("This connection cannot search host files."))) |
| 446 | : queryTooLong |
| 447 | ? resolve( |
| 448 | msg("Search is limited to {count} characters.", { |
| 449 | count: PROJECT_SEARCH_CONTENTS_QUERY_MAX_LENGTH, |
| 450 | }), |
| 451 | ) |
| 452 | : result.error, |
| 453 | isPending: |
| 454 | isCheckingAccess || |
| 455 | (canReadFiles && hasQuery && !queryTooLong && (query !== debouncedQuery || result.isPending)), |
| 456 | hasQuery, |
| 457 | truncated: result.data?.truncated ?? false, |
| 458 | invalidRegex: target.useRegex && result.data?.regexFallbackError !== undefined, |
| 459 | }; |
| 460 | } |
| 461 | |
| 462 | export function useCheckpointDiff( |
| 463 | target: CheckpointDiffTarget, |
| 464 | options?: { readonly enabled?: boolean }, |
| 465 | ) { |
| 466 | const enabled = |
| 467 | options?.enabled !== false && |
| 468 | target.environmentId !== null && |
| 469 | target.threadId !== null && |
| 470 | target.fromTurnCount !== null && |
| 471 | target.toTurnCount !== null; |
| 472 | const fullThreadTarget = |
| 473 | enabled && target.fromTurnCount === 0 |
| 474 | ? { |
| 475 | environmentId: target.environmentId!, |
| 476 | input: { |
| 477 | threadId: target.threadId!, |
| 478 | toTurnCount: target.toTurnCount!, |
| 479 | ignoreWhitespace: target.ignoreWhitespace, |
| 480 | }, |
| 481 | } |
| 482 | : null; |
| 483 | const turnTarget = |
| 484 | enabled && target.fromTurnCount !== 0 |
| 485 | ? { |
| 486 | environmentId: target.environmentId!, |
| 487 | input: { |
| 488 | threadId: target.threadId!, |
| 489 | fromTurnCount: target.fromTurnCount!, |
| 490 | toTurnCount: target.toTurnCount!, |
| 491 | ignoreWhitespace: target.ignoreWhitespace, |
| 492 | }, |
| 493 | } |
| 494 | : null; |
| 495 | const fullThread = useEnvironmentQuery( |
| 496 | fullThreadTarget === null ? null : orchestrationEnvironment.fullThreadDiff(fullThreadTarget), |
| 497 | ); |
| 498 | const turn = useEnvironmentQuery( |
| 499 | turnTarget === null ? null : orchestrationEnvironment.turnDiff(turnTarget), |
| 500 | ); |
| 501 | return fullThreadTarget === null ? turn : fullThread; |
| 502 | } |
| 503 | |
| 504 | /** Reads one item's detail from somewhere other than the environment, as the guest page does. */ |
| 505 | export type TurnItemDetailSource = (input: { |
| 506 | readonly threadId: ThreadId; |
| 507 | readonly itemId: TurnItemId; |
| 508 | readonly revision: string; |
| 509 | }) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2GetTurnItemResult, unknown>>; |
| 510 | |
| 511 | export function useTurnItemDetail( |
| 512 | target: { |
| 513 | readonly environmentId: EnvironmentId; |
| 514 | readonly threadId: ThreadId; |
| 515 | readonly itemId: TurnItemId; |
| 516 | readonly revision: string; |
| 517 | } | null, |
| 518 | source?: TurnItemDetailSource, |
| 519 | ) { |
| 520 | const input = |
| 521 | target === null |
| 522 | ? null |
| 523 | : { threadId: target.threadId, itemId: target.itemId, revision: target.revision }; |
| 524 | return useEnvironmentQuery<OrchestrationV2GetTurnItemResult, unknown>( |
| 525 | target === null || input === null |
| 526 | ? null |
| 527 | : source |
| 528 | ? source(input) |
| 529 | : orchestrationEnvironment.turnItem({ environmentId: target.environmentId, input }), |
| 530 | ); |
| 531 | } |