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

ThreadActivityBanners.tsx

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