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

ThreadActivityBanners.tsx

314 lines11.1 KB

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