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