@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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