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