Open History to see the last commit
1import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts";
2import type {
3 OrchestrationLatestTurn,
4 OrchestrationThread,
5 OrchestrationThreadActivity,
6 ToolLifecycleItemType,
7 TurnId,
8 UserInputQuestion,
9} from "@t3tools/contracts";
10import { formatDuration } from "@t3tools/shared/orchestrationTiming";
11
12import * as Arr from "effect/Array";
13import * as Order from "effect/Order";
14
15export interface PendingApproval {
16 readonly requestId: ApprovalRequestId;
17 readonly requestKind: "command" | "file-read" | "file-change";
18 readonly createdAt: string;
19 readonly detail?: string;
20}
21
22export interface PendingUserInput {
23 readonly requestId: ApprovalRequestId;
24 readonly createdAt: string;
25 readonly questions: ReadonlyArray<UserInputQuestion>;
26}
27
28export interface PendingUserInputDraftAnswer {
29 readonly selectedOptionLabel?: string;
30 readonly customAnswer?: string;
31}
32
33export interface ThreadFeedActivity {
34 readonly id: string;
35 readonly createdAt: string;
36 readonly turnId: TurnId | null;
37 readonly summary: string;
38 readonly detail: string | null;
39 readonly fullDetail: string | null;
40 readonly copyText: string;
41 readonly icon:
42 | "agent"
43 | "alert"
44 | "check"
45 | "command"
46 | "edit"
47 | "eye"
48 | "globe"
49 | "hammer"
50 | "message"
51 | "warning"
52 | "wrench"
53 | "zap";
54 readonly toolLike: boolean;
55 readonly status: "success" | "failure" | "neutral" | null;
56}
57
58const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
59
60type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
61
62interface WorkLogEntry {
63 id: string;
64 createdAt: string;
65 turnId: TurnId | null;
66 label: string;
67 detail?: string;
68 command?: string;
69 rawCommand?: string;
70 changedFiles?: ReadonlyArray<string>;
71 tone: "thinking" | "tool" | "info" | "error";
72 toolTitle?: string;
73 itemType?: ToolLifecycleItemType;
74 requestKind?: PendingApproval["requestKind"];
75 toolLifecycleStatus?: WorkLogToolLifecycleStatus;
76 toolData?: unknown;
77}
78
79interface DerivedWorkLogEntry extends WorkLogEntry {
80 activityKind: OrchestrationThreadActivity["kind"];
81 collapseKey?: string;
82}
83
84type RawThreadFeedEntry =
85 | {
86 readonly type: "message";
87 readonly id: string;
88 readonly createdAt: string;
89 readonly message: OrchestrationThread["messages"][number];
90 }
91 | {
92 readonly type: "activity";
93 readonly id: string;
94 readonly createdAt: string;
95 readonly turnId: TurnId | null;
96 readonly activity: ThreadFeedActivity;
97 };
98
99export type ThreadFeedEntry =
100 | Extract<RawThreadFeedEntry, { type: "message" }>
101 | {
102 readonly type: "activity-group";
103 readonly id: string;
104 readonly createdAt: string;
105 readonly turnId: TurnId | null;
106 readonly activities: ReadonlyArray<ThreadFeedActivity>;
107 }
108 | {
109 readonly type: "work-toggle";
110 readonly id: string;
111 readonly createdAt: string;
112 readonly turnId: TurnId | null;
113 readonly groupId: string;
114 readonly hiddenCount: number;
115 readonly expanded: boolean;
116 readonly onlyToolActivities: boolean;
117 }
118 | {
119 readonly type: "turn-fold";
120 readonly id: string;
121 readonly createdAt: string;
122 readonly turnId: TurnId;
123 readonly label: string;
124 readonly expanded: boolean;
125 };
126
127export type ThreadFeedLatestTurn = Pick<
128 OrchestrationLatestTurn,
129 "turnId" | "state" | "startedAt" | "completedAt"
130>;
131
132function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
133 switch (requestType) {
134 case "command_execution_approval":
135 case "exec_command_approval":
136 return "command";
137 case "file_read_approval":
138 return "file-read";
139 case "file_change_approval":
140 case "apply_patch_approval":
141 return "file-change";
142 default:
143 return null;
144 }
145}
146
147function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
148 const normalized = detail?.toLowerCase();
149 if (!normalized) {
150 return false;
151 }
152 return (
153 normalized.includes("stale pending approval request") ||
154 normalized.includes("stale pending user-input request") ||
155 normalized.includes("unknown pending approval request") ||
156 normalized.includes("unknown pending permission request") ||
157 normalized.includes("unknown pending user-input request")
158 );
159}
160
161function parseApprovalRequestId(value: unknown): ApprovalRequestId | null {
162 return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null;
163}
164
165function parseUserInputQuestions(
166 payload: Record<string, unknown> | null,
167): ReadonlyArray<UserInputQuestion> | null {
168 const questions = payload?.questions;
169 if (!Array.isArray(questions)) {
170 return null;
171 }
172
173 const parsed = questions
174 .map<UserInputQuestion | null>((entry) => {
175 if (!entry || typeof entry !== "object") return null;
176 const question = entry as Record<string, unknown>;
177 if (
178 typeof question.id !== "string" ||
179 typeof question.header !== "string" ||
180 typeof question.question !== "string" ||
181 !Array.isArray(question.options)
182 ) {
183 return null;
184 }
185 const options = question.options
186 .map<UserInputQuestion["options"][number] | null>((option) => {
187 if (!option || typeof option !== "object") return null;
188 const record = option as Record<string, unknown>;
189 if (typeof record.label !== "string" || typeof record.description !== "string") {
190 return null;
191 }
192 return {
193 label: record.label,
194 description: record.description,
195 };
196 })
197 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
198 if (options.length === 0) {
199 return null;
200 }
201 return {
202 id: question.id,
203 header: question.header,
204 question: question.question,
205 options,
206 multiSelect: question.multiSelect === true,
207 };
208 })
209 .filter((question): question is UserInputQuestion => question !== null);
210
211 return parsed.length > 0 ? parsed : null;
212}
213
214function normalizeDraftAnswer(value: string | undefined): string | null {
215 if (typeof value !== "string") {
216 return null;
217 }
218 const trimmed = value.trim();
219 return trimmed.length > 0 ? trimmed : null;
220}
221
222function resolvePendingUserInputAnswer(
223 draft: PendingUserInputDraftAnswer | undefined,
224): string | null {
225 const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
226 if (customAnswer) {
227 return customAnswer;
228 }
229 return normalizeDraftAnswer(draft?.selectedOptionLabel);
230}
231
232/**
233 * Task ids owned by a workflow run. Mirrors the desktop derivation in
234 * apps/web/src/workflow-logic.ts (collectWorkflowTaskIds) — mobile has no
235 * workflow card yet, so all rows for those tasks are suppressed rather than
236 * rendered as per-tick noise.
237 */
238function collectWorkflowTaskIds(
239 activities: ReadonlyArray<OrchestrationThreadActivity>,
240): Set<string> {
241 const taskIds = new Set<string>();
242 for (const activity of activities) {
243 const payload = activity.payload as Record<string, unknown> | null | undefined;
244 const taskId =
245 payload && typeof payload === "object" && typeof payload["taskId"] === "string"
246 ? payload["taskId"]
247 : undefined;
248 if (!taskId) continue;
249 const workflowName =
250 payload && typeof payload === "object" ? payload["workflowName"] : undefined;
251 const taskType = payload && typeof payload === "object" ? payload["taskType"] : undefined;
252 if (
253 activity.kind === "task.workflow-updated" ||
254 activity.kind === "task.workflow-meta" ||
255 (activity.kind === "task.started" &&
256 (taskType === "local_workflow" || typeof workflowName === "string"))
257 ) {
258 taskIds.add(taskId);
259 }
260 }
261 return taskIds;
262}
263
264function activityBelongsToWorkflow(
265 activity: OrchestrationThreadActivity,
266 workflowTaskIds: ReadonlySet<string>,
267): boolean {
268 const payload = activity.payload as Record<string, unknown> | null | undefined;
269 const taskId = payload && typeof payload === "object" ? payload["taskId"] : undefined;
270 return typeof taskId === "string" && workflowTaskIds.has(taskId);
271}
272
273function deriveWorkLogEntries(
274 activities: ReadonlyArray<OrchestrationThreadActivity>,
275): DerivedWorkLogEntry[] {
276 const ordered = Arr.sort(activities, activityOrder);
277 const workflowTaskIds = collectWorkflowTaskIds(activities);
278 const entries: DerivedWorkLogEntry[] = [];
279 for (const activity of ordered) {
280 if (activity.kind === "tool.started") continue;
281 if (activity.kind === "task.started") continue;
282 // Workflow snapshot/meta activities back the desktop workflow card; on
283 // mobile they would render as ever-mutating raw rows, so skip them —
284 // along with the per-tick progress rows the workflow owns. task.completed
285 // stays: with no workflow card here it is mobile's only signal that a
286 // workflow finished, failed, or was stopped.
287 if (activity.kind === "task.workflow-updated") continue;
288 if (activity.kind === "task.workflow-meta") continue;
289 if (
290 activity.kind === "task.progress" &&
291 workflowTaskIds.size > 0 &&
292 activityBelongsToWorkflow(activity, workflowTaskIds)
293 ) {
294 continue;
295 }
296 if (activity.kind === "context-window.updated") continue;
297 if (activity.summary === "Checkpoint captured") continue;
298 if (isPlanBoundaryToolActivity(activity)) continue;
299 entries.push(toDerivedWorkLogEntry(activity));
300 }
301 return collapseDerivedWorkLogEntries(entries);
302}
303
304function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
305 if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
306 return false;
307 }
308
309 const payload =
310 activity.payload && typeof activity.payload === "object"
311 ? (activity.payload as Record<string, unknown>)
312 : null;
313 return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
314}
315
316function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
317 const payload =
318 activity.payload && typeof activity.payload === "object"
319 ? (activity.payload as Record<string, unknown>)
320 : null;
321 const commandPreview = extractToolCommand(payload);
322 const changedFiles = extractChangedFiles(payload);
323 const title = extractToolTitle(payload);
324 const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
325 const taskSummary =
326 isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
327 ? payload.summary
328 : null;
329 const taskDetailAsLabel =
330 isTaskActivity &&
331 !taskSummary &&
332 typeof payload?.detail === "string" &&
333 payload.detail.length > 0
334 ? payload.detail
335 : null;
336 const taskLabel = taskSummary || taskDetailAsLabel;
337 const entry: DerivedWorkLogEntry = {
338 id: activity.id,
339 createdAt: activity.createdAt,
340 turnId: activity.turnId,
341 label: taskLabel || activity.summary,
342 tone:
343 activity.kind === "task.progress"
344 ? "thinking"
345 : activity.tone === "approval"
346 ? "info"
347 : activity.tone,
348 activityKind: activity.kind,
349 };
350 const itemType = extractWorkLogItemType(payload);
351 const requestKind = extractWorkLogRequestKind(payload);
352 if (
353 !taskDetailAsLabel &&
354 payload &&
355 typeof payload.detail === "string" &&
356 payload.detail.length > 0
357 ) {
358 const detail = stripTrailingExitCode(payload.detail).output;
359 if (detail) {
360 entry.detail = detail;
361 }
362 }
363 if (commandPreview.command) {
364 entry.command = commandPreview.command;
365 }
366 if (commandPreview.rawCommand) {
367 entry.rawCommand = commandPreview.rawCommand;
368 }
369 if (changedFiles.length > 0) {
370 entry.changedFiles = changedFiles;
371 }
372 if (title) {
373 entry.toolTitle = title;
374 }
375 if (itemType === "mcp_tool_call") {
376 const data = asRecord(payload?.data);
377 if (data?.item !== undefined) {
378 entry.toolData = data.item;
379 }
380 }
381 if (itemType) {
382 entry.itemType = itemType;
383 }
384 if (requestKind) {
385 entry.requestKind = requestKind;
386 }
387 let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload);
388 if (!toolLifecycleStatus && activity.kind === "tool.completed") {
389 toolLifecycleStatus = "completed";
390 }
391 if (toolLifecycleStatus) {
392 entry.toolLifecycleStatus = toolLifecycleStatus;
393 }
394 const collapseKey = deriveToolLifecycleCollapseKey(entry);
395 if (collapseKey) {
396 entry.collapseKey = collapseKey;
397 }
398 return entry;
399}
400
401function collapseDerivedWorkLogEntries(
402 entries: ReadonlyArray<DerivedWorkLogEntry>,
403): DerivedWorkLogEntry[] {
404 const collapsed: DerivedWorkLogEntry[] = [];
405 for (const entry of entries) {
406 const previous = collapsed.at(-1);
407 if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
408 collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
409 continue;
410 }
411 collapsed.push(entry);
412 }
413 return collapsed;
414}
415
416function shouldCollapseToolLifecycleEntries(
417 previous: DerivedWorkLogEntry,
418 next: DerivedWorkLogEntry,
419): boolean {
420 if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
421 return false;
422 }
423 if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
424 return false;
425 }
426 if (previous.activityKind === "tool.completed") {
427 return false;
428 }
429 return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
430}
431
432function mergeDerivedWorkLogEntries(
433 previous: DerivedWorkLogEntry,
434 next: DerivedWorkLogEntry,
435): DerivedWorkLogEntry {
436 const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
437 const detail = next.detail ?? previous.detail;
438 const command = next.command ?? previous.command;
439 const rawCommand = next.rawCommand ?? previous.rawCommand;
440 const toolTitle = next.toolTitle ?? previous.toolTitle;
441 const itemType = next.itemType ?? previous.itemType;
442 const requestKind = next.requestKind ?? previous.requestKind;
443 const collapseKey = next.collapseKey ?? previous.collapseKey;
444 const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
445 const toolData = next.toolData ?? previous.toolData;
446 return {
447 ...previous,
448 ...next,
449 ...(detail ? { detail } : {}),
450 ...(command ? { command } : {}),
451 ...(rawCommand ? { rawCommand } : {}),
452 ...(changedFiles.length > 0 ? { changedFiles } : {}),
453 ...(toolTitle ? { toolTitle } : {}),
454 ...(itemType ? { itemType } : {}),
455 ...(requestKind ? { requestKind } : {}),
456 ...(collapseKey ? { collapseKey } : {}),
457 ...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
458 ...(toolData !== undefined ? { toolData } : {}),
459 };
460}
461
462function mergeChangedFiles(
463 previous: ReadonlyArray<string> | undefined,
464 next: ReadonlyArray<string> | undefined,
465): string[] {
466 const merged = [...(previous ?? []), ...(next ?? [])];
467 if (merged.length === 0) {
468 return [];
469 }
470 return [...new Set(merged)];
471}
472
473function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
474 if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
475 return undefined;
476 }
477 const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
478 const detail = entry.detail?.trim() ?? "";
479 const itemType = entry.itemType ?? "";
480 if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
481 return undefined;
482 }
483 return [itemType, normalizedLabel, detail].join("\u001f");
484}
485
486function normalizeCompactToolLabel(value: string): string {
487 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
488}
489
490function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
491 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {
492 return true;
493 }
494 if (entry.command !== undefined && entry.command.trim().length > 0) {
495 return true;
496 }
497 if (entry.requestKind !== undefined) {
498 return true;
499 }
500 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
501}
502
503function toolDetailTextLooksLikeFailure(text: string): boolean {
504 const normalized = text.toLowerCase();
505 return (
506 normalized.includes("file not found") ||
507 normalized.includes("no files found") ||
508 normalized.includes("enoent") ||
509 normalized.includes("no such file or directory") ||
510 normalized.includes("no such file") ||
511 normalized.includes("commandnotfoundexception") ||
512 normalized.includes("command not found") ||
513 (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
514 (normalized.includes("is not recognized") && normalized.includes("the term '")) ||
515 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
516 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
517 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
518 );
519}
520
521function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
522 if (entry.tone === "error") {
523 return true;
524 }
525 if (entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "declined") {
526 return true;
527 }
528 if (!workLogEntryIsToolLike(entry)) {
529 return false;
530 }
531 return toolDetailTextLooksLikeFailure([entry.detail, entry.command].filter(Boolean).join("\n"));
532}
533
534function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
535 if (!workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry)) {
536 return false;
537 }
538 if (entry.tone === "thinking") {
539 return false;
540 }
541 return (
542 entry.toolLifecycleStatus !== "inProgress" &&
543 entry.toolLifecycleStatus !== "stopped" &&
544 entry.toolLifecycleStatus !== "failed" &&
545 entry.toolLifecycleStatus !== "declined"
546 );
547}
548
549function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {
550 if (!workLogEntryIsToolLike(entry)) {
551 return null;
552 }
553 if (workEntryIndicatesToolFailure(entry)) {
554 return "failure";
555 }
556 if (workEntryIndicatesToolSuccess(entry)) {
557 return "success";
558 }
559 return "neutral";
560}
561
562function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] {
563 if (
564 entry.activityKind === "user-input.requested" ||
565 entry.activityKind === "user-input.resolved"
566 ) {
567 return "message";
568 }
569 if (entry.activityKind === "runtime.warning") return "warning";
570 if (entry.requestKind === "command") return "command";
571 if (entry.requestKind === "file-read") return "eye";
572 if (entry.requestKind === "file-change") return "edit";
573 if (entry.itemType === "command_execution" || entry.command) return "command";
574 if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
575 if (entry.itemType === "web_search") return "globe";
576 if (entry.itemType === "image_view") return "eye";
577 if (entry.itemType === "mcp_tool_call") return "wrench";
578 if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") {
579 return "hammer";
580 }
581 if (entry.tone === "error") return "alert";
582 if (entry.tone === "thinking") return "agent";
583 if (entry.tone === "info") return "check";
584 return "zap";
585}
586
587function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null {
588 const blocks: string[] = [];
589 const appendUniqueBlock = (value: string | null | undefined) => {
590 const trimmed = value?.trim();
591 if (trimmed && !blocks.includes(trimmed)) {
592 blocks.push(trimmed);
593 }
594 };
595
596 if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) {
597 appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`);
598 }
599 appendUniqueBlock(entry.rawCommand ?? entry.command);
600 appendUniqueBlock(entry.detail);
601 if ((entry.changedFiles?.length ?? 0) > 0) {
602 appendUniqueBlock(entry.changedFiles!.join("\n"));
603 }
604
605 return blocks.length > 0 ? blocks.join("\n\n") : null;
606}
607
608function workEntryPreview(
609 workEntry: Pick<WorkLogEntry, "detail" | "command" | "changedFiles">,
610): string | null {
611 if (workEntry.command) return workEntry.command;
612 if (workEntry.detail) return workEntry.detail;
613 if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
614 const [firstPath] = workEntry.changedFiles ?? [];
615 if (!firstPath) return null;
616 return workEntry.changedFiles!.length === 1
617 ? firstPath
618 : `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
619}
620
621function capitalizePhrase(value: string): string {
622 const trimmed = value.trim();
623 if (trimmed.length === 0) {
624 return value;
625 }
626 return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
627}
628
629function workEntryHeading(workEntry: WorkLogEntry): string {
630 if (!workEntry.toolTitle) {
631 return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
632 }
633 return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
634}
635
636function asRecord(value: unknown): Record<string, unknown> | null {
637 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
638}
639
640function asTrimmedString(value: unknown): string | null {
641 if (typeof value !== "string") {
642 return null;
643 }
644 const trimmed = value.trim();
645 return trimmed.length > 0 ? trimmed : null;
646}
647
648function trimMatchingOuterQuotes(value: string): string {
649 const trimmed = value.trim();
650 if (
651 (trimmed.startsWith("'") && trimmed.endsWith("'")) ||
652 (trimmed.startsWith('"') && trimmed.endsWith('"'))
653 ) {
654 const unquoted = trimmed.slice(1, -1).trim();
655 return unquoted.length > 0 ? unquoted : trimmed;
656 }
657 return trimmed;
658}
659
660function executableBasename(value: string): string | null {
661 const trimmed = trimMatchingOuterQuotes(value);
662 if (trimmed.length === 0) {
663 return null;
664 }
665 const normalized = trimmed.replace(/\\/g, "/");
666 const segments = normalized.split("/");
667 const last = segments.at(-1)?.trim() ?? "";
668 return last.length > 0 ? last.toLowerCase() : null;
669}
670
671function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
672 const trimmed = value.trim();
673 if (trimmed.length === 0) {
674 return null;
675 }
676
677 if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
678 const quote = trimmed.charAt(0);
679 const closeIndex = trimmed.indexOf(quote, 1);
680 if (closeIndex <= 0) {
681 return null;
682 }
683 return {
684 executable: trimmed.slice(0, closeIndex + 1),
685 rest: trimmed.slice(closeIndex + 1).trim(),
686 };
687 }
688
689 const firstWhitespace = trimmed.search(/\s/);
690 if (firstWhitespace < 0) {
691 return {
692 executable: trimmed,
693 rest: "",
694 };
695 }
696
697 return {
698 executable: trimmed.slice(0, firstWhitespace),
699 rest: trimmed.slice(firstWhitespace).trim(),
700 };
701}
702
703const SHELL_WRAPPER_SPECS = [
704 {
705 executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
706 wrapperFlagPattern: /(?:^|\s)-command\s+/i,
707 },
708 {
709 executables: ["cmd", "cmd.exe"],
710 wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
711 },
712 {
713 executables: ["bash", "sh", "zsh"],
714 wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
715 },
716] as const;
717
718function findShellWrapperSpec(shell: string) {
719 return SHELL_WRAPPER_SPECS.find((spec) =>
720 (spec.executables as ReadonlyArray<string>).includes(shell),
721 );
722}
723
724function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
725 const match = wrapperFlagPattern.exec(value);
726 if (!match) {
727 return null;
728 }
729
730 const command = value.slice(match.index + match[0].length).trim();
731 if (command.length === 0) {
732 return null;
733 }
734
735 const unwrapped = trimMatchingOuterQuotes(command);
736 return unwrapped.length > 0 ? unwrapped : null;
737}
738
739function unwrapKnownShellCommandWrapper(value: string): string {
740 const split = splitExecutableAndRest(value);
741 if (!split || split.rest.length === 0) {
742 return value;
743 }
744
745 const shell = executableBasename(split.executable);
746 if (!shell) {
747 return value;
748 }
749
750 const spec = findShellWrapperSpec(shell);
751 if (!spec) {
752 return value;
753 }
754
755 return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
756}
757
758function formatCommandArrayPart(value: string): string {
759 return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
760}
761
762function formatCommandValue(value: unknown): string | null {
763 const direct = asTrimmedString(value);
764 if (direct) {
765 return direct;
766 }
767 if (!Array.isArray(value)) {
768 return null;
769 }
770 const parts: Array<string> = [];
771 for (const entry of value) {
772 const part = asTrimmedString(entry);
773 if (part !== null) {
774 parts.push(part);
775 }
776 }
777 if (parts.length === 0) {
778 return null;
779 }
780 return parts.map((part) => formatCommandArrayPart(part)).join(" ");
781}
782
783function normalizeCommandValue(value: unknown): string | null {
784 const formatted = formatCommandValue(value);
785 return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
786}
787
788function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
789 const formatted = formatCommandValue(value);
790 if (!formatted || normalizedCommand === null) {
791 return null;
792 }
793 return formatted === normalizedCommand ? null : formatted;
794}
795
796function extractToolCommand(payload: Record<string, unknown> | null): {
797 command: string | null;
798 rawCommand: string | null;
799} {
800 const data = asRecord(payload?.data);
801 const item = asRecord(data?.item);
802 const itemResult = asRecord(item?.result);
803 const itemInput = asRecord(item?.input);
804 const itemType = asTrimmedString(payload?.itemType);
805 const detail = asTrimmedString(payload?.detail);
806 const candidates: unknown[] = [
807 item?.command,
808 itemInput?.command,
809 itemResult?.command,
810 data?.command,
811 itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
812 ];
813
814 for (const candidate of candidates) {
815 const command = normalizeCommandValue(candidate);
816 if (!command) {
817 continue;
818 }
819 return {
820 command,
821 rawCommand: toRawToolCommand(candidate, command),
822 };
823 }
824
825 return {
826 command: null,
827 rawCommand: null,
828 };
829}
830
831function extractToolTitle(payload: Record<string, unknown> | null): string | null {
832 return asTrimmedString(payload?.title);
833}
834
835function extractWorkLogToolLifecycleStatus(
836 payload: Record<string, unknown> | null,
837): WorkLogToolLifecycleStatus | undefined {
838 const status = payload?.status;
839 if (
840 status === "inProgress" ||
841 status === "completed" ||
842 status === "failed" ||
843 status === "declined" ||
844 status === "stopped"
845 ) {
846 return status;
847 }
848 return undefined;
849}
850
851function stripTrailingExitCode(value: string): {
852 output: string | null;
853 exitCode?: number | undefined;
854} {
855 const trimmed = value.trim();
856 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(
857 trimmed,
858 );
859 if (!match?.groups) {
860 return {
861 output: trimmed.length > 0 ? trimmed : null,
862 };
863 }
864 const exitCode = Number.parseInt(match.groups.code ?? "", 10);
865 const normalizedOutput = match.groups.output?.trim() ?? "";
866 return {
867 output: normalizedOutput.length > 0 ? normalizedOutput : null,
868 ...(Number.isInteger(exitCode) ? { exitCode } : {}),
869 };
870}
871
872function extractWorkLogItemType(
873 payload: Record<string, unknown> | null,
874): WorkLogEntry["itemType"] | undefined {
875 if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
876 return payload.itemType;
877 }
878 return undefined;
879}
880
881function extractWorkLogRequestKind(
882 payload: Record<string, unknown> | null,
883): WorkLogEntry["requestKind"] | undefined {
884 if (
885 payload?.requestKind === "command" ||
886 payload?.requestKind === "file-read" ||
887 payload?.requestKind === "file-change"
888 ) {
889 return payload.requestKind;
890 }
891 return requestKindFromRequestType(payload?.requestType) ?? undefined;
892}
893
894function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
895 const normalized = asTrimmedString(value);
896 if (!normalized || seen.has(normalized)) {
897 return;
898 }
899 seen.add(normalized);
900 target.push(normalized);
901}
902
903function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
904 if (depth > 4 || target.length >= 12) {
905 return;
906 }
907 if (Array.isArray(value)) {
908 for (const entry of value) {
909 collectChangedFiles(entry, target, seen, depth + 1);
910 if (target.length >= 12) {
911 return;
912 }
913 }
914 return;
915 }
916
917 const record = asRecord(value);
918 if (!record) {
919 return;
920 }
921
922 pushChangedFile(target, seen, record.path);
923 pushChangedFile(target, seen, record.filePath);
924 pushChangedFile(target, seen, record.relativePath);
925 pushChangedFile(target, seen, record.filename);
926 pushChangedFile(target, seen, record.newPath);
927 pushChangedFile(target, seen, record.oldPath);
928
929 for (const nestedKey of [
930 "item",
931 "result",
932 "input",
933 "data",
934 "changes",
935 "files",
936 "edits",
937 "patch",
938 "patches",
939 "operations",
940 ]) {
941 if (!(nestedKey in record)) {
942 continue;
943 }
944 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
945 if (target.length >= 12) {
946 return;
947 }
948 }
949}
950
951function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
952 const changedFiles: string[] = [];
953 const seen = new Set<string>();
954 collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
955 return changedFiles;
956}
957
958function compareActivityLifecycleRank(kind: string): number {
959 if (kind.endsWith(".started") || kind === "tool.started") {
960 return 0;
961 }
962 if (kind.endsWith(".progress") || kind.endsWith(".updated")) {
963 return 1;
964 }
965 if (kind.endsWith(".completed") || kind.endsWith(".resolved")) {
966 return 2;
967 }
968 return 1;
969}
970
971const activityOrder = Order.combineAll<OrchestrationThreadActivity>([
972 Order.mapInput(Order.Number, (activity) => activity.sequence ?? Number.MAX_SAFE_INTEGER),
973 Order.mapInput(Order.String, (activity) => activity.createdAt),
974 Order.mapInput(Order.Number, (activity) => compareActivityLifecycleRank(activity.kind)),
975 Order.mapInput(Order.String, (activity) => activity.id),
976]);
977
978function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
979 if (entry.type !== "message") {
980 return false;
981 }
982 const hasText = entry.message.text.trim().length > 0;
983 const hasAttachments = (entry.message.attachments ?? []).length > 0;
984 return !hasText && !hasAttachments;
985}
986
987function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
988 const grouped: ThreadFeedEntry[] = [];
989
990 for (const entry of entries) {
991 // Skip empty messages so they don't break activity grouping.
992 if (isEmptyMessage(entry)) {
993 continue;
994 }
995
996 if (entry.type !== "activity") {
997 grouped.push(entry);
998 continue;
999 }
1000
1001 const previous = grouped.at(-1);
1002 if (previous?.type === "activity-group" && previous.turnId === entry.turnId) {
1003 grouped[grouped.length - 1] = {
1004 ...previous,
1005 activities: [...previous.activities, entry.activity],
1006 };
1007 continue;
1008 }
1009
1010 grouped.push({
1011 type: "activity-group",
1012 id: entry.id,
1013 createdAt: entry.createdAt,
1014 turnId: entry.turnId,
1015 activities: [entry.activity],
1016 });
1017 }
1018
1019 return grouped;
1020}
1021
1022function computeElapsedMs(startIso: string, endIso: string): number | null {
1023 const start = Date.parse(startIso);
1024 const end = Date.parse(endIso);
1025 if (!Number.isFinite(start) || !Number.isFinite(end)) {
1026 return null;
1027 }
1028 return Math.max(0, end - start);
1029}
1030
1031function maxIsoTimestamp(a: string | null, b: string | null): string | null {
1032 if (a === null) return b;
1033 if (b === null) return a;
1034 const aMs = Date.parse(a);
1035 const bMs = Date.parse(b);
1036 if (!Number.isFinite(aMs)) return b;
1037 if (!Number.isFinite(bMs)) return a;
1038 return bMs > aMs ? b : a;
1039}
1040
1041function deriveUnsettledTurnId(latestTurn: ThreadFeedLatestTurn | null): TurnId | null {
1042 if (!latestTurn) {
1043 return null;
1044 }
1045 const settled = latestTurn.completedAt !== null && latestTurn.state !== "running";
1046 return settled ? null : latestTurn.turnId;
1047}
1048
1049interface ThreadFeedTurnFold {
1050 readonly turnId: TurnId;
1051 readonly createdAt: string;
1052 readonly hiddenEntryIds: ReadonlySet<string>;
1053 readonly label: string;
1054}
1055
1056function deriveThreadFeedTurnFolds(
1057 feed: ReadonlyArray<ThreadFeedEntry>,
1058 latestTurn: ThreadFeedLatestTurn | null,
1059): ReadonlyMap<string, ThreadFeedTurnFold> {
1060 const terminalAssistantMessageIdByTurn = new Map<TurnId, string>();
1061 for (const entry of feed) {
1062 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
1063 terminalAssistantMessageIdByTurn.set(entry.message.turnId, entry.id);
1064 }
1065 }
1066
1067 interface TurnGroup {
1068 readonly entries: ThreadFeedEntry[];
1069 readonly startBoundary: string | null;
1070 }
1071 const groupsByTurnId = new Map<TurnId, TurnGroup>();
1072 let pendingUserBoundary: string | null = null;
1073 for (const entry of feed) {
1074 if (entry.type === "message" && entry.message.role === "user") {
1075 pendingUserBoundary = entry.message.createdAt;
1076 continue;
1077 }
1078 const turnId =
1079 entry.type === "message" && entry.message.role === "assistant"
1080 ? entry.message.turnId
1081 : entry.type === "activity-group"
1082 ? entry.turnId
1083 : null;
1084 if (!turnId) {
1085 continue;
1086 }
1087 let group = groupsByTurnId.get(turnId);
1088 if (!group) {
1089 group = {
1090 entries: [],
1091 startBoundary: pendingUserBoundary,
1092 };
1093 pendingUserBoundary = null;
1094 groupsByTurnId.set(turnId, group);
1095 }
1096 group.entries.push(entry);
1097 }
1098
1099 const unsettledTurnId = deriveUnsettledTurnId(latestTurn);
1100 const foldsByAnchorId = new Map<string, ThreadFeedTurnFold>();
1101 for (const [turnId, group] of groupsByTurnId) {
1102 const { entries } = group;
1103 if (turnId === unsettledTurnId) {
1104 continue;
1105 }
1106 if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) {
1107 continue;
1108 }
1109
1110 const terminalAssistantMessageId = terminalAssistantMessageIdByTurn.get(turnId);
1111 const hiddenEntryIds = new Set(
1112 entries.filter((entry) => entry.id !== terminalAssistantMessageId).map((entry) => entry.id),
1113 );
1114 if (hiddenEntryIds.size === 0) {
1115 continue;
1116 }
1117
1118 const firstEntry = entries[0];
1119 const lastEntry = entries.at(-1);
1120 if (!firstEntry || !lastEntry) {
1121 continue;
1122 }
1123 const terminalEntry = terminalAssistantMessageId
1124 ? entries.find((entry) => entry.id === terminalAssistantMessageId)
1125 : null;
1126 const latestTurnMatches = latestTurn?.turnId === turnId;
1127 const lastEntryEnd =
1128 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
1129 const elapsedMs =
1130 latestTurnMatches && latestTurn.startedAt && latestTurn.completedAt
1131 ? computeElapsedMs(latestTurn.startedAt, latestTurn.completedAt)
1132 : computeElapsedMs(
1133 group.startBoundary ?? firstEntry.createdAt,
1134 maxIsoTimestamp(
1135 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
1136 lastEntryEnd,
1137 ) ?? lastEntryEnd,
1138 );
1139 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
1140 const interrupted = latestTurnMatches && latestTurn.state === "interrupted";
1141 const label = interrupted
1142 ? duration
1143 ? `You stopped after ${duration}`
1144 : "You stopped this response"
1145 : duration
1146 ? `Worked for ${duration}`
1147 : "Worked";
1148
1149 foldsByAnchorId.set(firstEntry.id, {
1150 turnId,
1151 createdAt: firstEntry.createdAt,
1152 hiddenEntryIds,
1153 label,
1154 });
1155 }
1156 return foldsByAnchorId;
1157}
1158
1159export function deriveThreadFeedPresentation(
1160 feed: ReadonlyArray<ThreadFeedEntry>,
1161 latestTurn: ThreadFeedLatestTurn | null,
1162 expandedTurnIds: ReadonlySet<TurnId>,
1163 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
1164): ThreadFeedEntry[] {
1165 const sourceFeed = feed.filter(
1166 (entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
1167 );
1168 const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
1169 const collapsedEntryIds = new Set<string>();
1170 for (const fold of foldsByAnchorId.values()) {
1171 if (!expandedTurnIds.has(fold.turnId)) {
1172 for (const entryId of fold.hiddenEntryIds) {
1173 collapsedEntryIds.add(entryId);
1174 }
1175 }
1176 }
1177
1178 const result: ThreadFeedEntry[] = [];
1179 for (const entry of sourceFeed) {
1180 const fold = foldsByAnchorId.get(entry.id);
1181 if (fold) {
1182 result.push({
1183 type: "turn-fold",
1184 id: `turn-fold:${fold.turnId}`,
1185 createdAt: fold.createdAt,
1186 turnId: fold.turnId,
1187 label: fold.label,
1188 expanded: expandedTurnIds.has(fold.turnId),
1189 });
1190 }
1191 if (!collapsedEntryIds.has(entry.id)) {
1192 appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
1193 }
1194 }
1195 return result;
1196}
1197
1198function appendPresentedFeedEntry(
1199 result: ThreadFeedEntry[],
1200 entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
1201 expandedWorkGroupIds: ReadonlySet<string>,
1202): void {
1203 if (entry.type !== "activity-group") {
1204 result.push(entry);
1205 return;
1206 }
1207
1208 const activities = entry.activities.filter(
1209 (activity) => !(activity.toolLike && activity.status === "neutral"),
1210 );
1211 if (activities.length === 0) {
1212 return;
1213 }
1214 if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
1215 result.push({
1216 ...entry,
1217 activities,
1218 });
1219 return;
1220 }
1221
1222 const groupId = entry.id;
1223 const expanded = expandedWorkGroupIds.has(groupId);
1224 const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
1225 const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
1226
1227 for (const activity of visibleActivities) {
1228 result.push({
1229 type: "activity-group",
1230 id: activity.id,
1231 createdAt: activity.createdAt,
1232 turnId: activity.turnId,
1233 activities: [activity],
1234 });
1235 }
1236 result.push({
1237 type: "work-toggle",
1238 id: `work-toggle:${groupId}`,
1239 createdAt: entry.createdAt,
1240 turnId: entry.turnId,
1241 groupId,
1242 hiddenCount,
1243 expanded,
1244 onlyToolActivities: activities.every((activity) => activity.toolLike),
1245 });
1246}
1247
1248export function derivePendingApprovals(
1249 activities: ReadonlyArray<OrchestrationThreadActivity>,
1250): PendingApproval[] {
1251 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
1252 const ordered = Arr.sort(activities, activityOrder);
1253
1254 for (const activity of ordered) {
1255 const payload =
1256 activity.payload && typeof activity.payload === "object"
1257 ? (activity.payload as Record<string, unknown>)
1258 : null;
1259 const requestId = parseApprovalRequestId(payload?.requestId);
1260 const requestKind =
1261 payload?.requestKind === "command" ||
1262 payload?.requestKind === "file-read" ||
1263 payload?.requestKind === "file-change"
1264 ? payload.requestKind
1265 : requestKindFromRequestType(payload?.requestType);
1266 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
1267
1268 if (activity.kind === "approval.requested" && requestId && requestKind) {
1269 openByRequestId.set(requestId, {
1270 requestId,
1271 requestKind,
1272 createdAt: activity.createdAt,
1273 ...(detail ? { detail } : {}),
1274 });
1275 continue;
1276 }
1277
1278 if (activity.kind === "approval.resolved" && requestId) {
1279 openByRequestId.delete(requestId);
1280 continue;
1281 }
1282
1283 if (
1284 activity.kind === "provider.approval.respond.failed" &&
1285 requestId &&
1286 isStalePendingRequestFailureDetail(detail)
1287 ) {
1288 openByRequestId.delete(requestId);
1289 }
1290 }
1291
1292 return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date);
1293}
1294
1295export function derivePendingUserInputs(
1296 activities: ReadonlyArray<OrchestrationThreadActivity>,
1297): PendingUserInput[] {
1298 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
1299 const ordered = Arr.sort(activities, activityOrder);
1300
1301 for (const activity of ordered) {
1302 const payload =
1303 activity.payload && typeof activity.payload === "object"
1304 ? (activity.payload as Record<string, unknown>)
1305 : null;
1306 const requestId = parseApprovalRequestId(payload?.requestId);
1307 const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
1308
1309 if (activity.kind === "user-input.requested" && requestId) {
1310 const questions = parseUserInputQuestions(payload);
1311 if (!questions) {
1312 continue;
1313 }
1314 openByRequestId.set(requestId, {
1315 requestId,
1316 createdAt: activity.createdAt,
1317 questions,
1318 });
1319 continue;
1320 }
1321
1322 if (activity.kind === "user-input.resolved" && requestId) {
1323 openByRequestId.delete(requestId);
1324 continue;
1325 }
1326
1327 if (
1328 activity.kind === "provider.user-input.respond.failed" &&
1329 requestId &&
1330 isStalePendingRequestFailureDetail(detail)
1331 ) {
1332 openByRequestId.delete(requestId);
1333 }
1334 }
1335
1336 return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date);
1337}
1338
1339export function setPendingUserInputCustomAnswer(
1340 draft: PendingUserInputDraftAnswer | undefined,
1341 customAnswer: string,
1342): PendingUserInputDraftAnswer {
1343 const selectedOptionLabel =
1344 customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
1345 return {
1346 customAnswer,
1347 ...(selectedOptionLabel ? { selectedOptionLabel } : {}),
1348 };
1349}
1350
1351export function buildPendingUserInputAnswers(
1352 questions: ReadonlyArray<UserInputQuestion>,
1353 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
1354): Record<string, string> | null {
1355 const answers: Record<string, string> = {};
1356
1357 for (const question of questions) {
1358 const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
1359 if (!answer) {
1360 return null;
1361 }
1362 answers[question.id] = answer;
1363 }
1364
1365 return answers;
1366}
1367
1368export function buildThreadFeed(
1369 thread: OrchestrationThread,
1370 options?: {
1371 readonly loadedMessages?: ReadonlyArray<OrchestrationThread["messages"][number]>;
1372 },
1373): ThreadFeedEntry[] {
1374 const loadedMessages = options?.loadedMessages ?? thread.messages;
1375 const oldestLoadedMessageCreatedAt =
1376 options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;
1377 const workLogEntries = deriveWorkLogEntries(thread.activities);
1378 const entries = Arr.sortWith(
1379 [
1380 ...loadedMessages.map<RawThreadFeedEntry>((message) => ({
1381 type: "message",
1382 id: message.id,
1383 createdAt: message.createdAt,
1384 message,
1385 })),
1386 ...workLogEntries
1387 .filter((entry) => {
1388 if (options?.loadedMessages === undefined) {
1389 return true;
1390 }
1391 return (
1392 oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt
1393 );
1394 })
1395 .map<RawThreadFeedEntry>((entry) => {
1396 const summary = workEntryHeading(entry);
1397 const detail = workEntryPreview(entry);
1398 const fullDetail = buildWorkEntryExpandedBody(entry);
1399 return {
1400 type: "activity",
1401 id: entry.id,
1402 createdAt: entry.createdAt,
1403 turnId: entry.turnId,
1404 activity: {
1405 id: entry.id,
1406 createdAt: entry.createdAt,
1407 turnId: entry.turnId,
1408 summary,
1409 detail,
1410 fullDetail,
1411 icon: workEntryIcon(entry),
1412 copyText: [summary, detail, fullDetail]
1413 .filter((value, index, values): value is string => {
1414 return Boolean(value) && values.indexOf(value) === index;
1415 })
1416 .join("\n"),
1417 toolLike: workLogEntryIsToolLike(entry),
1418 status: workEntryStatus(entry),
1419 },
1420 };
1421 }),
1422 ],
1423 (s) => new Date(s.createdAt),
1424 Order.Date,
1425 );
1426
1427 return groupAdjacentActivities(entries);
1428}