| 1 | import type { EnvironmentId, ThreadId, WorktreeSetupSnapshot } from "@t3tools/contracts"; |
| 2 | import { resolveVisibleWorktreeSetup } from "@t3tools/client-runtime/worktree-setup"; |
| 3 | import { useEffect, useState } from "react"; |
| 4 | import { useEnvironmentQuery } from "../../state/query"; |
| 5 | import { vcsEnvironment } from "../../state/vcs"; |
| 6 | import { resolveWorktreeSetupSnapshot } from "./worktree-setup-state"; |
| 7 | |
| 8 | /** Retain the last live snapshot when its subscription closes after setup. */ |
| 9 | export function useWorktreeSetup(input: { |
| 10 | environmentId: EnvironmentId | null; |
| 11 | threadId: ThreadId | null; |
| 12 | preparing: boolean; |
| 13 | turnStarted: boolean; |
| 14 | followUpSent: boolean; |
| 15 | }) { |
| 16 | const key = JSON.stringify([input.environmentId, input.threadId]); |
| 17 | const [held, setHeld] = useState<{ key: string; snapshot: WorktreeSetupSnapshot } | null>(null); |
| 18 | const live = held?.key === key ? held.snapshot : null; |
| 19 | const query = useEnvironmentQuery( |
| 20 | input.environmentId && |
| 21 | input.threadId && |
| 22 | (live?.phase === "running" || (!live && input.preparing)) |
| 23 | ? vcsEnvironment.worktreeSetup({ |
| 24 | environmentId: input.environmentId, |
| 25 | input: { threadId: input.threadId }, |
| 26 | }) |
| 27 | : null, |
| 28 | ); |
| 29 | const snapshot = resolveWorktreeSetupSnapshot(input.threadId, query.data, live); |
| 30 | useEffect(() => { |
| 31 | if (snapshot && snapshot !== live) setHeld({ key, snapshot }); |
| 32 | }, [key, live, snapshot]); |
| 33 | return { |
| 34 | snapshot, |
| 35 | visible: resolveVisibleWorktreeSetup({ |
| 36 | live: snapshot, |
| 37 | recorded: null, |
| 38 | turnStarted: input.turnStarted, |
| 39 | followUpSent: input.followUpSent, |
| 40 | }), |
| 41 | }; |
| 42 | } |