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

ThreadActivityBanners.tsx

272 lines9.6 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 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 };
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 };
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 };
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} <span className={cn(isCommand(only) && "font-mono")}>{only.task.label}</span>
195 </>
196 ) : (
197 presentation.title
198 ),
199 description: only ? (
200 only.activity
201 ) : newest ? (
202 `${newest.task.label}: ${newest.activity}`
203 ) : rows.every(isCommand) ? (
204 <span className="font-mono">{rows.map((row) => row.task.label).join(", ")}</span>
205 ) : (
206 rows.map((row) => row.task.label).join(", ")
207 ),
208 actions: (
209 <>
210 {startedAtMs === null ? null : (
211 <span
212 ref={tickTextContent(
213 (nowMs) => formatDuration(Math.max(1_000, nowMs - startedAtMs)),
214 true,
215 )}
216 className="tabular-nums"
217 />
218 )}
219 {onlyThreadId === undefined ? null : (
220 <InlineButton tone="muted" onClick={() => onOpenThread(onlyThreadId)}>
221 Open
222 </InlineButton>
223 )}
224 <InlineButton disabled={input.stopDisabled} onClick={() => void input.onStop()}>
225 {input.stopping ? "Stopping..." : "Stop"}
226 </InlineButton>
227 </>
228 ),
229 };
231​
232/** The local checkout moved off the branch this thread last ran on. */
233export function branchMismatchBannerItem(input: {
234 readonly mismatchKey: string;
235 readonly mismatch: { readonly threadBranch: string; readonly currentBranch: string };
236 readonly restoreDisabled: boolean;
237 readonly restoring: boolean;
238 readonly onRestore: () => void;
239 readonly onDismiss: () => void;
240}): ComposerBannerStackItem {
241 const { mismatch } = input;
242 return {
243 id: `branch-mismatch:${input.mismatchKey}`,
244 variant: "info",
245 icon: <GitBranchIcon />,
246 title: (
247 <span className="flex min-w-0 items-baseline gap-1.5">
248 <span className="shrink-0 font-normal text-muted-foreground">Branch changed from</span>
249 <Tooltip>
250 <TooltipTrigger
251 render={
252 <code className="min-w-0 truncate font-medium text-foreground">
253 {mismatch.threadBranch}
254 </code>
255 }
256 />
257 <TooltipPopup side="top">
258 This thread last ran on {mismatch.threadBranch}. Sending will continue on{" "}
259 {mismatch.currentBranch}.
260 </TooltipPopup>
261 </Tooltip>
262 </span>
263 ),
264 actions: (
265 <Button size="xs" variant="ghost" disabled={input.restoreDisabled} onClick={input.onRestore}>
266 {input.restoring ? "Restoring..." : "Restore branch"}
267 </Button>
268 ),
269 dismissLabel: "Dismiss branch change notice",
270 onDismiss: input.onDismiss,
271 };