Files
t3code/apps/mobile/src/lib/threadActivity.ts
T
Julius Marmingeandcodex ffe2daac90 fix(mobile): preserve active thread state
Keep executing runs visible when newer work is queued, expose provider errors in compact shells, and preserve mobile creation metadata for fork and merge operations.

Co-authored-by: codex <[email protected]>
2026-08-14 11:23:28 +02:00

996 lines
32 KiB
TypeScript

import type {
ThreadPendingApproval,
ThreadPendingUserInput,
ThreadUserInputQuestion,
} from "@t3tools/client-runtime/state/thread-requests";
import {
resolveT3McpToolPresentation,
type T3McpToolLogo,
type T3McpToolPresentation,
} from "@t3tools/shared/t3McpToolPresentation";
import type {
ChatAttachment,
MessageId,
OrchestrationV2Actor,
OrchestrationV2CreationSource,
OrchestrationV2ProjectedTurnItem,
OrchestrationV2RunStatus,
OrchestrationV2TurnItem,
OrchestrationV2UserMessageInputIntent,
RunId,
ThreadId,
} from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import * as DateTime from "effect/DateTime";
export type PendingApproval = ThreadPendingApproval;
export type PendingUserInput = ThreadPendingUserInput;
export interface PendingUserInputDraftAnswer {
readonly selectedOptionLabel?: string;
readonly customAnswer?: string;
}
export interface ThreadFeedActivity {
readonly id: string;
readonly createdAt: string;
readonly runId: RunId | null;
readonly summary: string;
readonly detail: string | null;
readonly canExpand: boolean;
readonly getFullDetail: () => string | null;
readonly getCopyText: () => string;
readonly icon:
| "agent"
| "alert"
| "check"
| "command"
| "edit"
| "eye"
| "globe"
| "hammer"
| "message"
| "warning"
| "wrench"
| "zap";
readonly logo: T3McpToolLogo | null;
readonly toolLike: boolean;
readonly prominent: boolean;
readonly status: "success" | "failure" | "neutral" | null;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
}
export interface ThreadFeedMessage {
readonly id: MessageId;
readonly role: "user" | "assistant";
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
readonly runId: RunId | null;
readonly streaming: boolean;
readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
readonly createdBy?: OrchestrationV2Actor;
readonly creationSource?: OrchestrationV2CreationSource;
readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
readonly sourceThreadId: ThreadId;
readonly createdAt: string;
readonly updatedAt: string;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
}
<<<<<<< HEAD
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
interface WorkLogEntry {
id: string;
createdAt: string;
turnId: TurnId | null;
label: string;
detail?: string;
command?: string;
rawCommand?: string;
changedFiles?: ReadonlyArray<string>;
tone: "thinking" | "tool" | "info" | "error";
toolTitle?: string;
itemType?: ToolLifecycleItemType;
requestKind?: PendingApproval["requestKind"];
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
toolData?: unknown;
}
interface DerivedWorkLogEntry extends WorkLogEntry {
activityKind: OrchestrationThreadActivity["kind"];
collapseKey?: string;
/** Grouping key for subagent lifecycle rows (one row per agent). */
taskId?: string;
}
=======
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
type RawThreadFeedEntry =
| {
readonly type: "message";
readonly id: string;
readonly createdAt: string;
readonly message: ThreadFeedMessage;
}
| {
readonly type: "activity";
readonly id: string;
readonly createdAt: string;
readonly runId: RunId | null;
readonly activity: ThreadFeedActivity;
};
export type ThreadFeedEntry =
| Extract<RawThreadFeedEntry, { type: "message" }>
| {
readonly type: "working";
readonly id: string;
readonly createdAt: string;
}
| {
readonly type: "activity-group";
readonly id: string;
readonly createdAt: string;
readonly runId: RunId | null;
readonly activities: ReadonlyArray<ThreadFeedActivity>;
}
| {
readonly type: "run-fold";
readonly id: string;
readonly createdAt: string;
readonly runId: RunId;
readonly label: string;
readonly expanded: boolean;
};
export interface ThreadFeedLatestRun {
readonly runId: RunId;
readonly status: OrchestrationV2RunStatus;
readonly startedAt: string | null;
readonly completedAt: string | null;
}
function normalizeDraftAnswer(value: string | undefined): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function resolvePendingUserInputAnswer(
draft: PendingUserInputDraftAnswer | undefined,
): string | null {
<<<<<<< HEAD
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
* task.completed — these rows are mobile's only terminal signal for them. */
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
"idle",
"completed",
"failed",
"cancelled",
"interrupted",
]);
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "task.updated") {
return false;
}
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
return (
payload?.timelineBypass === true &&
typeof payload.status === "string" &&
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
);
}
/**
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
* activity lives in the Agents sheet, not the work log. Terminal rows are
* kept — with no Agents surface on mobile they are the terminal signal
* (a surface that hides rows must keep its own terminal signal). That means
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
* children never emit task.completed — review finding).
*/
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
if (!payload) {
return false;
}
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
if (payload.timelineBypass === true && !isTerminalTaskRow) {
return true;
}
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
// the only signal mobile gets (no Agents sheet), so it stays. Only an
// agent's own background work (stamped "background") is internal — same
// rule as web (review finding: hiding on agentId alone dropped nested
// completions with no replacement UI).
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
if (!ownedByAgent) {
return false;
}
return !(isTerminalTaskRow && payload.agentKind === "agent");
}
function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): DerivedWorkLogEntry[] {
const ordered = Arr.sort(activities, activityOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
// Terminal bypassed updates pass: Codex children's only terminal signal.
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
if (activity.kind === "tool.progress") continue;
if (activity.kind === "context-window.updated") continue;
if (activity.summary === "Checkpoint captured") continue;
if (isPlanBoundaryToolActivity(activity)) continue;
if (isAgentInternalActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries);
}
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") {
return false;
}
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
}
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const commandPreview = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
// task.updated included: terminal bypassed updates (Codex children's only
// terminal signal) must carry task identity so they collapse per child
// instead of stacking anonymous "Task idle" rows.
const isTaskActivity =
activity.kind === "task.progress" ||
activity.kind === "task.completed" ||
activity.kind === "task.updated";
const taskSummary =
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
? payload.summary
: null;
const taskDetailAsLabel =
isTaskActivity &&
!taskSummary &&
typeof payload?.detail === "string" &&
payload.detail.length > 0
? payload.detail
: null;
const taskLabel = taskSummary || taskDetailAsLabel;
const taskId =
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
? payload.taskId
: undefined;
const entry: DerivedWorkLogEntry = {
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
...(taskId ? { taskId } : {}),
label: taskLabel || activity.summary,
tone:
activity.kind === "task.progress"
? "thinking"
: activity.tone === "approval"
? "info"
: activity.tone,
activityKind: activity.kind,
};
const itemType = extractWorkLogItemType(payload);
const requestKind = extractWorkLogRequestKind(payload);
if (
!taskDetailAsLabel &&
payload &&
typeof payload.detail === "string" &&
payload.detail.length > 0
) {
const detail = stripTrailingExitCode(payload.detail).output;
if (detail) {
entry.detail = detail;
}
}
if (commandPreview.command) {
entry.command = commandPreview.command;
}
if (commandPreview.rawCommand) {
entry.rawCommand = commandPreview.rawCommand;
}
if (changedFiles.length > 0) {
entry.changedFiles = changedFiles;
}
if (title) {
entry.toolTitle = title;
}
if (itemType === "mcp_tool_call") {
const data = asRecord(payload?.data);
if (data?.item !== undefined) {
entry.toolData = data.item;
}
}
if (itemType) {
entry.itemType = itemType;
}
if (requestKind) {
entry.requestKind = requestKind;
}
let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload);
if (!toolLifecycleStatus && activity.kind === "tool.completed") {
toolLifecycleStatus = "completed";
}
if (toolLifecycleStatus) {
entry.toolLifecycleStatus = toolLifecycleStatus;
}
const collapseKey = deriveToolLifecycleCollapseKey(entry);
if (collapseKey) {
entry.collapseKey = collapseKey;
}
return entry;
}
function collapseDerivedWorkLogEntries(
entries: ReadonlyArray<DerivedWorkLogEntry>,
): DerivedWorkLogEntry[] {
const collapsed: DerivedWorkLogEntry[] = [];
// Subagent rows collapse by identity, not adjacency (quiet-timeline
// guarantee; mirrors web's session-logic).
const taskRowIndex = new Map<string, number>();
for (const entry of entries) {
const isTaskRow =
entry.taskId !== undefined &&
(entry.activityKind === "task.progress" ||
entry.activityKind === "task.completed" ||
entry.activityKind === "task.updated");
if (isTaskRow && entry.taskId !== undefined) {
const existingIndex = taskRowIndex.get(entry.taskId);
if (existingIndex !== undefined) {
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
continue;
}
taskRowIndex.set(entry.taskId, collapsed.length);
collapsed.push(entry);
continue;
}
const previous = collapsed.at(-1);
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
continue;
}
collapsed.push(entry);
}
return collapsed;
}
function shouldCollapseToolLifecycleEntries(
previous: DerivedWorkLogEntry,
next: DerivedWorkLogEntry,
): boolean {
if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") {
return false;
}
if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") {
return false;
}
if (previous.activityKind === "tool.completed") {
return false;
}
return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey;
}
function mergeDerivedWorkLogEntries(
previous: DerivedWorkLogEntry,
next: DerivedWorkLogEntry,
): DerivedWorkLogEntry {
const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
const detail = next.detail ?? previous.detail;
const command = next.command ?? previous.command;
const rawCommand = next.rawCommand ?? previous.rawCommand;
const toolTitle = next.toolTitle ?? previous.toolTitle;
const itemType = next.itemType ?? previous.itemType;
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
const toolData = next.toolData ?? previous.toolData;
return {
...previous,
...next,
...(detail ? { detail } : {}),
...(command ? { command } : {}),
...(rawCommand ? { rawCommand } : {}),
...(changedFiles.length > 0 ? { changedFiles } : {}),
...(toolTitle ? { toolTitle } : {}),
...(itemType ? { itemType } : {}),
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolLifecycleStatus ? { toolLifecycleStatus } : {}),
...(toolData !== undefined ? { toolData } : {}),
};
}
function mergeChangedFiles(
previous: ReadonlyArray<string> | undefined,
next: ReadonlyArray<string> | undefined,
): string[] {
const merged = [...(previous ?? []), ...(next ?? [])];
if (merged.length === 0) {
return [];
}
return [...new Set(merged)];
}
function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined {
if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") {
return undefined;
}
const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label);
const detail = entry.detail?.trim() ?? "";
const itemType = entry.itemType ?? "";
if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) {
return undefined;
}
return [itemType, normalizedLabel, detail].join("\u001f");
}
function normalizeCompactToolLabel(value: string): string {
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
}
function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {
return true;
}
if (entry.command !== undefined && entry.command.trim().length > 0) {
return true;
}
if (entry.requestKind !== undefined) {
return true;
}
return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
}
function toolDetailTextLooksLikeFailure(text: string): boolean {
const normalized = text.toLowerCase();
=======
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
return (
<<<<<<< HEAD
normalized.includes("file not found") ||
normalized.includes("no files found") ||
normalized.includes("enoent") ||
normalized.includes("no such file or directory") ||
normalized.includes("no such file") ||
normalized.includes("commandnotfoundexception") ||
normalized.includes("command not found") ||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
normalized.includes("is not recognized as the name of a cmdlet") ||
normalized.includes("a parameter cannot be found that matches parameter name") ||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
=======
normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel)
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
);
}
function capitalizePhrase(value: string): string {
const trimmed = value.trim();
return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
}
function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
return (
item.type === "reasoning" ||
item.type === "command_execution" ||
item.type === "file_change" ||
item.type === "file_search" ||
item.type === "web_search" ||
item.type === "approval_request" ||
item.type === "user_input_request" ||
item.type === "dynamic_tool" ||
item.type === "subagent" ||
item.type === "error"
);
}
function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
return item.type === "fork" || item.type === "thread_created" || item.type === "subagent";
}
function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
if (!itemIsToolLike(item)) return null;
if (item.type === "error" || item.status === "failed") return "failure";
return item.status === "completed" ? "success" : "neutral";
}
function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
switch (item.type) {
case "reasoning":
return "agent";
case "command_execution":
return "command";
case "file_change":
return "edit";
case "file_search":
return "eye";
case "web_search":
return "globe";
case "approval_request":
case "user_input_request":
case "user_message":
case "assistant_message":
return "message";
case "dynamic_tool":
return "wrench";
case "subagent":
return "hammer";
case "run_interrupt_request":
case "run_interrupt_result":
return "warning";
case "error":
return "alert";
case "checkpoint":
case "proposed_plan":
case "todo_list":
return "check";
case "compaction":
case "handoff":
case "fork":
case "thread_created":
return "zap";
}
}
function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
if (item.type !== "dynamic_tool") {
return null;
}
return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
}
function itemSummary(
item: OrchestrationV2TurnItem,
toolPresentation: T3McpToolPresentation | null = null,
): string {
const title = item.title?.trim();
if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
switch (item.type) {
case "reasoning":
return "Thinking";
case "command_execution":
return "Command";
case "file_change":
return `Changed ${item.fileName}`;
case "file_search":
return "Searched files";
case "web_search":
return "Searched the web";
case "approval_request":
return "Approval requested";
case "user_input_request":
return "Input requested";
case "checkpoint":
return "Checkpoint captured";
case "run_interrupt_request":
return "Interrupt requested";
case "run_interrupt_result":
return "Run interrupted";
case "error":
return "Provider error";
case "compaction":
return "Context compacted";
case "handoff":
return "Context handed off";
case "fork":
return "Thread forked";
case "thread_created":
return "Thread created";
case "subagent":
return "Subagent";
case "dynamic_tool":
return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
case "proposed_plan":
return "Proposed plan";
case "todo_list":
return "Plan updated";
case "user_message":
return "User message";
case "assistant_message":
return "Assistant message";
}
}
function itemPreview(item: OrchestrationV2TurnItem): string | null {
switch (item.type) {
case "reasoning":
return item.text || null;
case "command_execution":
return item.input || null;
case "file_change":
return item.fileName;
case "file_search":
return item.pattern ?? null;
case "web_search":
return item.patterns?.join(", ") ?? null;
case "approval_request":
return item.prompt ?? null;
case "user_input_request":
return item.questions.map((question) => question.question).join(" · ") || null;
case "checkpoint":
return item.files.length === 1
? (item.files[0]?.path ?? null)
: `${item.files.length} changed files`;
case "run_interrupt_request":
case "run_interrupt_result":
return item.message || null;
case "error":
return item.failure.message;
case "compaction":
case "handoff":
return item.summary ?? null;
case "fork":
case "thread_created":
return item.targetThreadId;
case "subagent":
return item.result ?? item.progress ?? item.prompt;
case "dynamic_tool":
return null;
case "proposed_plan":
return item.markdown || null;
case "todo_list":
return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
case "user_message":
case "assistant_message":
return item.text || null;
}
}
function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
const item = row.item;
const toolPresentation = itemToolPresentation(item);
const summary = itemSummary(item, toolPresentation);
const detail = itemPreview(item);
const fullDetail = JSON.stringify(
{
visibility: row.visibility,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
item,
},
null,
2,
);
return {
id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
createdAt: DateTime.formatIso(item.startedAt ?? item.updatedAt),
runId: item.runId,
summary,
detail,
fullDetail,
icon: itemIcon(item),
logo: toolPresentation?.logo ?? null,
copyText: [summary, detail, fullDetail]
.filter(
(value, index, values): value is string =>
Boolean(value) && values.indexOf(value) === index,
)
.join("\n"),
toolLike: itemIsToolLike(item),
prominent: itemIsProminent(item),
status: itemStatus(item),
projectedItem: row,
};
}
function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
return (
entry.type === "message" &&
entry.message.text.trim().length === 0 &&
entry.message.attachments.length === 0
);
}
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
const grouped: ThreadFeedEntry[] = [];
for (const entry of entries) {
if (isEmptyMessage(entry)) continue;
if (entry.type !== "activity") {
grouped.push(entry);
openGroupActivities = null;
continue;
}
const previous = grouped.at(-1);
if (
previous?.type === "activity-group" &&
previous.runId === entry.runId &&
!entry.activity.prominent &&
!previous.activities.some((activity) => activity.prominent)
) {
grouped[grouped.length - 1] = {
...previous,
activities: [...previous.activities, entry.activity],
};
continue;
}
grouped.push({
type: "activity-group",
id: entry.id,
createdAt: entry.createdAt,
runId: entry.runId,
activities: [entry.activity],
});
}
return grouped;
}
function computeElapsedMs(startIso: string, endIso: string): number | null {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
}
function maxIsoTimestamp(left: string | null, right: string | null): string | null {
if (left === null) return right;
if (right === null) return left;
return Date.parse(right) > Date.parse(left) ? right : left;
}
function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
}
export function threadFeedRunIsUnsettled(
run: ThreadFeedLatestRun | null,
): run is ThreadFeedLatestRun {
return (
run !== null &&
(run.status === "preparing" ||
run.status === "starting" ||
run.status === "running" ||
run.status === "waiting")
);
}
interface ThreadFeedRunFold {
readonly runId: RunId;
readonly createdAt: string;
readonly hiddenEntryIds: ReadonlySet<string>;
readonly label: string;
}
function deriveThreadFeedRunFolds(
feed: ReadonlyArray<ThreadFeedEntry>,
latestRun: ThreadFeedLatestRun | null,
): ReadonlyMap<string, ThreadFeedRunFold> {
const terminalAssistantMessageIdByRun = new Map<RunId, string>();
for (const entry of feed) {
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
}
}
const groupsByRunId = new Map<
RunId,
{ entries: ThreadFeedEntry[]; startBoundary: string | null }
>();
let pendingUserBoundary: string | null = null;
for (const entry of feed) {
if (entry.type === "message" && entry.message.role === "user") {
pendingUserBoundary = entry.message.createdAt;
continue;
}
const runId =
entry.type === "message" && entry.message.role === "assistant"
? entry.message.runId
: entry.type === "activity-group"
? entry.runId
: null;
if (!runId) continue;
let group = groupsByRunId.get(runId);
if (!group) {
group = { entries: [], startBoundary: pendingUserBoundary };
pendingUserBoundary = null;
groupsByRunId.set(runId, group);
}
group.entries.push(entry);
}
const activeRunId = unsettledRunId(latestRun);
const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
for (const [runId, group] of groupsByRunId) {
if (
runId === activeRunId ||
group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
) {
continue;
}
const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
const hiddenEntryIds = new Set(
group.entries
.filter(
(entry) =>
entry.id !== terminalAssistantId &&
!(
entry.type === "activity-group" &&
entry.activities.some((activity) => activity.prominent)
),
)
.map((entry) => entry.id),
);
const firstEntry = group.entries[0];
const lastEntry = group.entries.at(-1);
if (hiddenEntryIds.size === 0 || !firstEntry || !lastEntry) continue;
const terminalEntry = terminalAssistantId
? group.entries.find((entry) => entry.id === terminalAssistantId)
: null;
const latestRunMatches = latestRun?.runId === runId;
const lastEntryEnd =
lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
const elapsedMs =
latestRunMatches && latestRun.startedAt && latestRun.completedAt
? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
: computeElapsedMs(
group.startBoundary ?? firstEntry.createdAt,
maxIsoTimestamp(
terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
lastEntryEnd,
) ?? lastEntryEnd,
);
const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
const interrupted =
latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
foldsByAnchorId.set(firstEntry.id, {
runId,
createdAt: firstEntry.createdAt,
hiddenEntryIds,
label: interrupted
? duration
? `You stopped after ${duration}`
: "You stopped this response"
: duration
? `Worked for ${duration}`
: "Worked",
});
}
return foldsByAnchorId;
}
export function deriveThreadFeedPresentation(
feed: ReadonlyArray<ThreadFeedEntry>,
latestRun: ThreadFeedLatestRun | null,
expandedRunIds: ReadonlySet<RunId>,
): ThreadFeedEntry[] {
const sourceFeed = feed.filter((entry) => entry.type !== "run-fold");
const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorId.values()) {
if (!expandedRunIds.has(fold.runId)) {
for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
}
}
const result: ThreadFeedEntry[] = [];
for (const entry of sourceFeed) {
const fold = foldsByAnchorId.get(entry.id);
if (fold) {
result.push({
type: "run-fold",
id: `run-fold:${fold.runId}`,
createdAt: fold.createdAt,
runId: fold.runId,
label: fold.label,
expanded: expandedRunIds.has(fold.runId),
});
}
if (!collapsedEntryIds.has(entry.id)) result.push(entry);
}
if (activeWorkStartedAt !== null) {
result.push({
type: "working",
id: "working-indicator-row",
createdAt: activeWorkStartedAt,
});
}
return result;
}
export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
const selectedOptionLabel =
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
return { customAnswer, ...(selectedOptionLabel ? { selectedOptionLabel } : {}) };
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<ThreadUserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): Record<string, string> | null {
const answers: Record<string, string> = {};
for (const question of questions) {
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
if (!answer) return null;
answers[question.id] = answer;
}
return answers;
}
/**
* Projects the server-authored visible sequence into mobile row presentation.
* It deliberately preserves the incoming order and never rebuilds chat from
* separate message, plan, or work-entry collections.
*/
export function buildThreadFeed(
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
): ThreadFeedEntry[] {
const entries = visibleTurnItems.map((row): RawThreadFeedEntry => {
const item = row.item;
const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
if (item.type === "user_message" || item.type === "assistant_message") {
const updatedAt = DateTime.formatIso(item.updatedAt);
return {
type: "message",
id: item.messageId,
createdAt,
message: {
id: item.messageId,
role: item.type === "user_message" ? "user" : "assistant",
text: item.text,
attachments: item.type === "user_message" ? item.attachments : [],
runId: item.runId,
streaming: item.type === "assistant_message" && item.streaming,
...(item.type === "user_message"
? {
inputIntent: item.inputIntent,
createdBy: item.createdBy,
creationSource: item.creationSource,
}
: {}),
visibility: row.visibility,
sourceThreadId: row.sourceThreadId,
createdAt,
updatedAt,
projectedItem: row,
},
};
}
const activity = toFeedActivity(row);
return {
type: "activity",
id: activity.id,
createdAt,
runId: item.runId,
activity,
};
});
return groupAdjacentActivities(entries);
}