Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

worktree-setup-state.ts

65 lines2.3 KB

1import type { ThreadId, WorktreeSetupSnapshot } from "@t3tools/contracts";
2import {
3 holdWorktreeSetupSnapshot,
4 worktreeSetupSettledTurn,
5 type HeldWorktreeSetup,
6} from "@t3tools/client-runtime/worktree-setup";
7import type { ThreadFeedRow } from "./pending-thread-feed";
8​
9/** A subscription can close or replay an older value during the setup handoff. */
10export function resolveWorktreeSetupSnapshot(
11 threadId: ThreadId | null,
12 latest: WorktreeSetupSnapshot | null | undefined,
13 held: HeldWorktreeSetup | null,
14): HeldWorktreeSetup | null {
15 const previous = held?.snapshot.threadId === threadId ? held : null;
16 if (latest === undefined || (latest !== null && latest.threadId !== threadId)) return previous;
17 return holdWorktreeSetupSnapshot(previous, latest);
19​
20function setupWentWrong(snapshot: WorktreeSetupSnapshot): boolean {
21 return (
22 snapshot.phase === "failed" ||
23 snapshot.phase === "cancelled" ||
24 (snapshot.phase === "done" &&
25 snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed"))
26 );
28​
29/**
30 * Before handoff the full card shows. After it, running setup is a chip on the live Working
31 * fold, so the card stays only while no fold carries that chip; setup that went wrong shows a summary.
32 */
33export function worktreeSetupCardMode(
34 snapshot: WorktreeSetupSnapshot,
35 handedOff: boolean,
36 chipCarried: boolean,
37): "card" | "summary" | null {
38 if (!handedOff) return "card";
39 if (snapshot.phase === "running") return chipCarried ? null : "card";
40 return setupWentWrong(snapshot) ? "summary" : null;
42​
43/**
44 * The feed row the setup card renders below: the first prompt, or, as on web, the end of the
45 * follow-up turn a handed-off setup settled in. -1 when the feed has no prompt yet.
46 */
47export function resolveWorktreeSetupAnchorIndex(
48 feed: ReadonlyArray<ThreadFeedRow>,
49 handedOffSnapshot: WorktreeSetupSnapshot | null,
50): number {
51 const userEntries = feed.flatMap((entry, index) =>
52 entry.type === "message" && entry.message.role === "user"
53 ? [{ index, sentAt: entry.message.createdAt }]
54 : [],
55 );
56 const lateTurn = handedOffSnapshot
57 ? worktreeSetupSettledTurn(
58 handedOffSnapshot,
59 userEntries.map((entry) => entry.sentAt),
60 )
61 : -1;
62 return lateTurn > 0
63 ? (userEntries[lateTurn + 1]?.index ?? feed.length) - 1
64 : (userEntries[0]?.index ?? -1);