Open History to see the last commit
1import type {
2 OrchestrationV2PendingBackgroundTask,
3 OrchestrationV2ProviderGoal,
4 ThreadId,
5} from "@t3tools/contracts";
6import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell";
7import {
8 presentPendingBackgroundWork,
9 presentProviderGoal,
10 type RunStopPresentation,
11} from "@t3tools/client-runtime/state/thread-execution";
12import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads";
13import { formatDuration } from "@t3tools/shared/orchestrationTiming";
14import * as DateTime from "effect/DateTime";
15import {
16 CircleDashedIcon,
17 CircleStopIcon,
18 GitBranchIcon,
19 MessageCircleIcon,
20 ShieldQuestionIcon,
21 TargetIcon,
22 TerminalIcon,
23 TriangleAlertIcon,
24} from "lucide-react";
25import { Fragment } from "react";
26import { tickTextContent } from "~/lib/tickTextContent";
27import { cn } from "~/lib/utils";
28import { Button, InlineButton } from "../ui/button";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import type { ComposerBannerStackItem } from "./ComposerBannerStack";
31import type { ThreadNowItem } from "./ThreadNow";
32
33/** Subagents and side chats waiting on the user, unless the parent is itself waiting on them. */
34export function childInputNowItem(input: {
35 readonly childThreadInputs: ReadonlyArray<EnvironmentThreadShell>;
36 readonly parentAwaitingUser: boolean;
37 readonly onOpenThread: (threadId: ThreadId) => void;
38}): (ThreadNowItem & { readonly waitingLabel: string }) | null {
39 const { childThreadInputs, onOpenThread } = input;
40 const first = childThreadInputs[0];
41 if (!first || input.parentAwaitingUser) return null;
42 return {
43 id: `child-input:${first.id}`,
44 // The only line at the end of the timeline that needs you gets the info color.
45 icon: first.hasPendingApprovals ? (
46 <ShieldQuestionIcon className="text-info-foreground" />
47 ) : (
48 <MessageCircleIcon className="text-info-foreground" />
49 ),
50 title: childThreadInputsTitle(childThreadInputs),
51 waitingLabel: childThreadInputs.every((child) => child.lineage.sideChat === true)
52 ? "Side chat waiting"
53 : "Subagent waiting",
54 description: childThreadInputs.map((child, index) => (
55 <Fragment key={child.id}>
56 {index > 0 ? " " : null}
57 <span className="whitespace-nowrap">
58 <InlineButton tone="muted" onClick={() => onOpenThread(child.id)}>
59 {child.title}
60 </InlineButton>
61 {index < childThreadInputs.length - 1 ? "," : null}
62 </span>
63 </Fragment>
64 )),
65 actions: (
66 <InlineButton onClick={() => onOpenThread(first.id)}>
67 {first.hasPendingApprovals ? "Open approval" : "Open question"}
68 </InlineButton>
69 ),
70 };
71}
72
73/** The thread's goal, for the end of the timeline. */
74export function goalNowItem(input: {
75 readonly threadId: ThreadId;
76 readonly goal: OrchestrationV2ProviderGoal;
77 readonly isWorking: boolean;
78 readonly onSendCommand: (text: string, failureMessage: string) => Promise<void>;
79}): ThreadNowItem {
80 const { isWorking, onSendCommand } = input;
81 const presentation = presentProviderGoal(input.goal, isWorking);
82 return {
83 id: `goal:${input.threadId}`,
84 icon: <TargetIcon />,
85 title:
86 presentation.usage === null
87 ? presentation.title
88 : `${presentation.title} · ${presentation.usage}`,
89 description: presentation.objective,
90 // Clear stops goal work; Resume would stop unrelated work, so it waits.
91 actions: (
92 <>
93 {presentation.canResume && !isWorking ? (
94 <>
95 <InlineButton
96 onClick={() => void onSendCommand("/goal resume", "Failed to resume goal.")}
97 >
98 Resume
99 </InlineButton>
100 <span aria-hidden>·</span>
101 </>
102 ) : null}
103 <InlineButton
104 tone="muted"
105 onClick={() => void onSendCommand("/goal clear", "Failed to clear goal.")}
106 >
107 Clear
108 </InlineButton>
109 </>
110 ),
111 };
112}
113
114/** A Stop the provider has not finished; Force stop once it stops answering. */
115export function runStopNowItem(input: {
116 readonly threadId: ThreadId;
117 readonly stop: RunStopPresentation;
118 readonly canForceStop: boolean;
119 readonly forceStopping: boolean;
120 readonly onForceStop: () => void;
121}): ThreadNowItem {
122 const unresponsive = input.stop.state === "unresponsive";
123 const requestedAtMs = Date.parse(input.stop.requestedAt);
124 return {
125 id: `run-stop:${input.threadId}`,
126 icon: unresponsive ? (
127 <TriangleAlertIcon className="text-warning-foreground" />
128 ) : (
129 <CircleStopIcon />
130 ),
131 title: unresponsive ? "Agent not responding to Stop" : "Stopping",
132 description: unresponsive
133 ? "It may be short on memory. Force stop kills its processes."
134 : undefined,
135 actions: (
136 <>
137 <span
138 ref={tickTextContent(
139 (nowMs) => formatDuration(Math.max(1_000, nowMs - requestedAtMs)),
140 true,
141 )}
142 className="tabular-nums"
143 />
144 {unresponsive && input.canForceStop ? (
145 <InlineButton disabled={input.forceStopping} onClick={input.onForceStop}>
146 {input.forceStopping ? "Force stopping..." : "Force stop"}
147 </InlineButton>
148 ) : null}
149 </>
150 ),
151 };
152}
153
154/** Background commands and subagents, for the end of the timeline. */
155export function backgroundWorkNowItem(input: {
156 readonly threadId: ThreadId;
157 readonly tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>;
158 readonly turnItems: ThreadStructure["turnItems"];
159 readonly stopDisabled: boolean;
160 readonly stopping: boolean;
161 readonly onStop: () => Promise<void>;
162 readonly onOpenThread: (threadId: ThreadId) => void;
163}): ThreadNowItem | null {
164 const { onOpenThread } = input;
165 const presentation = presentPendingBackgroundWork(input.tasks);
166 if (presentation === null) return null;
167 const rows = presentation.items.map((task) => {
168 // Same key derivePendingBackgroundWork gives turn-item tasks; subagent items carry progress.
169 const item = input.turnItems.findLast(
170 (candidate) => (candidate.nativeItemRef?.nativeId || candidate.id) === task.taskId,
171 );
172 const subagent = item?.type === "subagent" ? item : undefined;
173 return {
174 task,
175 activity: subagent?.progress?.replace(/\s+/gu, " ").trim() || null,
176 startedAtMs: item?.startedAt ? DateTime.toEpochMillis(item.startedAt) : null,
177 updatedAtMs: subagent ? DateTime.toEpochMillis(subagent.updatedAt) : 0,
178 childThreadId: task.childThreadId ?? subagent?.childThreadId ?? undefined,
179 };
180 });
181 const [only] = rows.length === 1 ? rows : [];
182 const newest = rows
183 .filter((row) => row.activity)
184 .toSorted((left, right) => right.updatedAtMs - left.updatedAtMs)[0];
185 const isCommand = (row: (typeof rows)[number]) => row.task.kind !== "subagent";
186 const verb = presentation.waiting ? "Waiting on" : "Running";
187 const onlyThreadId = only?.childThreadId;
188 const startedAtMs = only?.startedAtMs ?? null;
189 return {
190 id: `background-work:${input.threadId}`,
191 icon: rows.every(isCommand) ? <TerminalIcon /> : <CircleDashedIcon />,
192 title: only ? (
193 <>
194 {verb}{" "}
195 <span
196 className={cn(
197 isCommand(only) && "font-mono in-data-[slot=popover-popup]:whitespace-pre-wrap",
198 )}
199 >
200 {only.task.label}
201 </span>
202 </>
203 ) : (
204 presentation.title
205 ),
206 description: only ? (
207 only.activity
208 ) : newest ? (
209 `${newest.task.label}: ${newest.activity}`
210 ) : rows.every(isCommand) ? (
211 <span className="font-mono">{rows.map((row) => row.task.label).join(", ")}</span>
212 ) : (
213 rows.map((row) => row.task.label).join(", ")
214 ),
215 actions: (
216 <>
217 {startedAtMs === null ? null : (
218 <span
219 ref={tickTextContent(
220 (nowMs) => formatDuration(Math.max(1_000, nowMs - startedAtMs)),
221 true,
222 )}
223 className="tabular-nums"
224 />
225 )}
226 {onlyThreadId === undefined ? null : (
227 <InlineButton tone="muted" onClick={() => onOpenThread(onlyThreadId)}>
228 Open
229 </InlineButton>
230 )}
231 <InlineButton disabled={input.stopDisabled} onClick={() => void input.onStop()}>
232 {input.stopping ? "Stopping..." : "Stop"}
233 </InlineButton>
234 </>
235 ),
236 };
237}
238
239/** The local checkout moved off the branch this thread last ran on. */
240export function branchMismatchBannerItem(input: {
241 readonly mismatchKey: string;
242 readonly mismatch: { readonly threadBranch: string; readonly currentBranch: string };
243 readonly restoreDisabled: boolean;
244 readonly restoring: boolean;
245 readonly onRestore: () => void;
246 readonly onDismiss: () => void;
247}): ComposerBannerStackItem {
248 const { mismatch } = input;
249 return {
250 id: `branch-mismatch:${input.mismatchKey}`,
251 variant: "info",
252 icon: <GitBranchIcon />,
253 title: (
254 <span className="flex min-w-0 items-baseline gap-1.5">
255 <span className="shrink-0 font-normal text-muted-foreground">Branch changed from</span>
256 <Tooltip>
257 <TooltipTrigger
258 render={
259 <code className="min-w-0 truncate font-medium text-foreground">
260 {mismatch.threadBranch}
261 </code>
262 }
263 />
264 <TooltipPopup side="top">
265 This thread last ran on {mismatch.threadBranch}. Sending will continue on{" "}
266 {mismatch.currentBranch}.
267 </TooltipPopup>
268 </Tooltip>
269 </span>
270 ),
271 actions: (
272 <Button size="xs" variant="ghost" disabled={input.restoreDisabled} onClick={input.onRestore}>
273 {input.restoring ? "Restoring..." : "Restore branch"}
274 </Button>
275 ),
276 dismissLabel: "Dismiss branch change notice",
277 onDismiss: input.onDismiss,
278 };
279}