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

ThreadActivityBanners.tsx

269 lines9.4 KB

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 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 | 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 description: childThreadInputs.map((child, index) => (
52 <Fragment key={child.id}>
53 {index > 0 ? " " : null}
54 <span className="whitespace-nowrap">
55 <InlineButton tone="muted" onClick={() => onOpenThread(child.id)}>
56 {child.title}
57 </InlineButton>
58 {index < childThreadInputs.length - 1 ? "," : null}
59 </span>
60 </Fragment>
61 )),
62 actions: (
63 <InlineButton onClick={() => onOpenThread(first.id)}>
64 {first.hasPendingApprovals ? "Open approval" : "Open question"}
65 </InlineButton>
66 ),
67 };
69​
70/** The thread's goal, for the end of the timeline. */
71export function goalNowItem(input: {
72 readonly threadId: ThreadId;
73 readonly goal: OrchestrationV2ProviderGoal;
74 readonly isWorking: boolean;
75 readonly onSendCommand: (text: string, failureMessage: string) => Promise<void>;
76}): ThreadNowItem {
77 const { isWorking, onSendCommand } = input;
78 const presentation = presentProviderGoal(input.goal, isWorking);
79 return {
80 id: `goal:${input.threadId}`,
81 icon: <TargetIcon />,
82 title:
83 presentation.usage === null
84 ? presentation.title
85 : `${presentation.title} · ${presentation.usage}`,
86 description: presentation.objective,
87 // Clear stops goal work; Resume would stop unrelated work, so it waits.
88 actions: (
89 <>
90 {presentation.canResume && !isWorking ? (
91 <>
92 <InlineButton
93 onClick={() => void onSendCommand("/goal resume", "Failed to resume goal.")}
94 >
95 Resume
96 </InlineButton>
97 <span aria-hidden>·</span>
98 </>
99 ) : null}
100 <InlineButton
101 tone="muted"
102 onClick={() => void onSendCommand("/goal clear", "Failed to clear goal.")}
103 >
104 Clear
105 </InlineButton>
106 </>
107 ),
108 };
110​
111/** A Stop the provider has not finished; Force stop once it stops answering. */
112export function runStopNowItem(input: {
113 readonly threadId: ThreadId;
114 readonly stop: RunStopPresentation;
115 readonly canForceStop: boolean;
116 readonly forceStopping: boolean;
117 readonly onForceStop: () => void;
118}): ThreadNowItem {
119 const unresponsive = input.stop.state === "unresponsive";
120 const requestedAtMs = Date.parse(input.stop.requestedAt);
121 return {
122 id: `run-stop:${input.threadId}`,
123 icon: unresponsive ? (
124 <TriangleAlertIcon className="text-warning-foreground" />
125 ) : (
126 <CircleStopIcon />
127 ),
128 title: unresponsive ? "Agent not responding to Stop" : "Stopping",
129 description: unresponsive
130 ? "It may be short on memory. Force stop kills its processes."
131 : undefined,
132 actions: (
133 <>
134 <span
135 ref={tickTextContent(
136 (nowMs) => formatDuration(Math.max(1_000, nowMs - requestedAtMs)),
137 true,
138 )}
139 className="tabular-nums"
140 />
141 {unresponsive && input.canForceStop ? (
142 <InlineButton disabled={input.forceStopping} onClick={input.onForceStop}>
143 {input.forceStopping ? "Force stopping..." : "Force stop"}
144 </InlineButton>
145 ) : null}
146 </>
147 ),
148 };
150​
151/** Background commands and subagents, for the end of the timeline. */
152export function backgroundWorkNowItem(input: {
153 readonly threadId: ThreadId;
154 readonly tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>;
155 readonly turnItems: ThreadStructure["turnItems"];
156 readonly stopDisabled: boolean;
157 readonly stopping: boolean;
158 readonly onStop: () => Promise<void>;
159 readonly onOpenThread: (threadId: ThreadId) => void;
160}): ThreadNowItem | null {
161 const { onOpenThread } = input;
162 const presentation = presentPendingBackgroundWork(input.tasks);
163 if (presentation === null) return null;
164 const rows = presentation.items.map((task) => {
165 // Same key derivePendingBackgroundWork gives turn-item tasks; subagent items carry progress.
166 const item = input.turnItems.findLast(
167 (candidate) => (candidate.nativeItemRef?.nativeId || candidate.id) === task.taskId,
168 );
169 const subagent = item?.type === "subagent" ? item : undefined;
170 return {
171 task,
172 activity: subagent?.progress?.replace(/\s+/gu, " ").trim() || null,
173 startedAtMs: item?.startedAt ? DateTime.toEpochMillis(item.startedAt) : null,
174 updatedAtMs: subagent ? DateTime.toEpochMillis(subagent.updatedAt) : 0,
175 childThreadId: task.childThreadId ?? subagent?.childThreadId ?? undefined,
176 };
177 });
178 const [only] = rows.length === 1 ? rows : [];
179 const newest = rows
180 .filter((row) => row.activity)
181 .toSorted((left, right) => right.updatedAtMs - left.updatedAtMs)[0];
182 const isCommand = (row: (typeof rows)[number]) => row.task.kind !== "subagent";
183 const verb = presentation.waiting ? "Waiting on" : "Running";
184 const onlyThreadId = only?.childThreadId;
185 const startedAtMs = only?.startedAtMs ?? null;
186 return {
187 id: `background-work:${input.threadId}`,
188 icon: rows.every(isCommand) ? <TerminalIcon /> : <CircleDashedIcon />,
189 title: only ? (
190 <>
191 {verb} <span className={cn(isCommand(only) && "font-mono")}>{only.task.label}</span>
192 </>
193 ) : (
194 presentation.title
195 ),
196 description: only ? (
197 only.activity
198 ) : newest ? (
199 `${newest.task.label}: ${newest.activity}`
200 ) : rows.every(isCommand) ? (
201 <span className="font-mono">{rows.map((row) => row.task.label).join(", ")}</span>
202 ) : (
203 rows.map((row) => row.task.label).join(", ")
204 ),
205 actions: (
206 <>
207 {startedAtMs === null ? null : (
208 <span
209 ref={tickTextContent(
210 (nowMs) => formatDuration(Math.max(1_000, nowMs - startedAtMs)),
211 true,
212 )}
213 className="tabular-nums"
214 />
215 )}
216 {onlyThreadId === undefined ? null : (
217 <InlineButton tone="muted" onClick={() => onOpenThread(onlyThreadId)}>
218 Open
219 </InlineButton>
220 )}
221 <InlineButton disabled={input.stopDisabled} onClick={() => void input.onStop()}>
222 {input.stopping ? "Stopping..." : "Stop"}
223 </InlineButton>
224 </>
225 ),
226 };
228​
229/** The local checkout moved off the branch this thread last ran on. */
230export function branchMismatchBannerItem(input: {
231 readonly mismatchKey: string;
232 readonly mismatch: { readonly threadBranch: string; readonly currentBranch: string };
233 readonly restoreDisabled: boolean;
234 readonly restoring: boolean;
235 readonly onRestore: () => void;
236 readonly onDismiss: () => void;
237}): ComposerBannerStackItem {
238 const { mismatch } = input;
239 return {
240 id: `branch-mismatch:${input.mismatchKey}`,
241 variant: "info",
242 icon: <GitBranchIcon />,
243 title: (
244 <span className="flex min-w-0 items-baseline gap-1.5">
245 <span className="shrink-0 font-normal text-muted-foreground">Branch changed from</span>
246 <Tooltip>
247 <TooltipTrigger
248 render={
249 <code className="min-w-0 truncate font-medium text-foreground">
250 {mismatch.threadBranch}
251 </code>
252 }
253 />
254 <TooltipPopup side="top">
255 This thread last ran on {mismatch.threadBranch}. Sending will continue on{" "}
256 {mismatch.currentBranch}.
257 </TooltipPopup>
258 </Tooltip>
259 </span>
260 ),
261 actions: (
262 <Button size="xs" variant="ghost" disabled={input.restoreDisabled} onClick={input.onRestore}>
263 {input.restoring ? "Restoring..." : "Restore branch"}
264 </Button>
265 ),
266 dismissLabel: "Dismiss branch change notice",
267 onDismiss: input.onDismiss,
268 };