Render mobile timelines from V2 turn items

Use the authoritative visibleTurnItems projection directly so mobile preserves server ordering, inherited items, and synthetic items without rebuilding a parallel feed.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-25 00:32:19 -07:00
1 parent 3a12575b05
commit 5df6529caa
4 files changed
+380 -147

No files matched your search

+122 -51
View File
@@ -1,72 +1,142 @@
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
import { MessageId, RunId } from "@t3tools/contracts";
import {
MessageId,
RunId,
ThreadId,
TurnItemId,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import { makeThreadFixture } from "../test-fixtures";
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
const threadId = ThreadId.make("thread-1");
const sourceThreadId = ThreadId.make("thread-source");
const runId = RunId.make("run-1");
function message(role: "user" | "assistant", text: string, createdAt: string, id: string) {
function base(id: string, updatedAt: string, ordinal: number) {
const timestamp = DateTime.makeUnsafe(updatedAt);
return {
id: MessageId.make(id),
role,
text,
attachments: [],
runId: role === "assistant" ? runId : null,
streaming: false,
createdAt,
updatedAt: createdAt,
} as const;
id: TurnItemId.make(id),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal,
status: "completed" as const,
title: null,
startedAt: timestamp,
completedAt: timestamp,
updatedAt: timestamp,
};
}
function commandEntry(overrides: Partial<ThreadWorkEntry> = {}): ThreadWorkEntry {
const structuredPayload = {
type: "command_execution",
function projected(
item: OrchestrationV2TurnItem,
position: number,
visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
): OrchestrationV2ProjectedTurnItem {
return {
position,
visibility,
sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
sourceItemId: item.id,
item,
};
}
function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
return {
...base("item-user", updatedAt, 0),
type: "user_message" as const,
messageId: MessageId.make("message-user"),
createdBy: "user" as const,
creationSource: "mobile" as const,
inputIntent: "turn_start" as const,
text: "Run checks",
attachments: [],
};
}
function command(updatedAt = "2026-06-20T00:00:02.000Z") {
return {
...base("item-command", updatedAt, 1),
type: "command_execution" as const,
input: "vp check",
output: "ok",
} as ThreadWorkEntry["structuredPayload"];
exitCode: 0,
};
}
function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
return {
id: "item-1",
createdAt: "2026-06-20T00:00:02.000Z",
runId,
label: "Ran command",
command: "vp check",
detail: "ok",
tone: "tool",
itemType: "command_execution",
toolLifecycleStatus: "completed",
structuredPayload,
...overrides,
...base("item-assistant", updatedAt, 2),
type: "assistant_message" as const,
messageId: MessageId.make("message-assistant"),
text: "Done",
streaming: false,
};
}
describe("buildThreadFeed", () => {
it("orders V2 messages and work entries while retaining structured tool data", () => {
const thread = makeThreadFixture({
messages: [
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
],
workEntries: [commandEntry()],
});
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
const rows = [
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
projected(command("2026-06-20T00:00:01.000Z"), 1),
projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
];
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed(rows);
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
expect(feed.map((entry) => entry.id)).toEqual([
"message-user",
"local:thread-1:item-command",
"message-assistant",
]);
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
expect(activity?.runId).toBe(runId);
expect(activity?.projectedItem).toBe(rows[1]);
expect(activity?.fullDetail).toContain('"input": "vp check"');
});
it("retains inherited and synthetic rows with their original projected identity", () => {
const inherited = projected(command(), 0, "inherited");
const { providerThreadId: _providerThreadId, ...forkBase } = base(
"item-fork",
"2026-06-20T00:00:03.000Z",
2,
);
const synthetic = projected(
{
...forkBase,
type: "fork",
source: { type: "run", threadId: sourceThreadId, runId },
targetThreadId: threadId,
},
1,
"synthetic",
);
const feed = buildThreadFeed([inherited, synthetic]);
const activities = feed.flatMap((entry) =>
entry.type === "activity-group" ? entry.activities : [],
);
expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
"inherited",
"synthetic",
]);
});
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
const thread = makeThreadFixture({
messages: [
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
],
workEntries: [commandEntry()],
});
const feed = buildThreadFeed(thread);
const feed = buildThreadFeed([
projected(userMessage(), 0),
projected(command(), 1),
projected(assistantMessage(), 2),
]);
const latestRun = {
runId,
status: "completed" as const,
@@ -87,11 +157,12 @@ describe("buildThreadFeed", () => {
});
it("keeps an active run expanded and marks failed tools as failures", () => {
const thread = makeThreadFixture({
messages: [message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user")],
workEntries: [commandEntry({ tone: "error", toolLifecycleStatus: "failed" })],
});
const feed = buildThreadFeed(thread);
const failedCommand: OrchestrationV2TurnItem = {
...command(),
status: "failed",
completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
};
const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
const presented = deriveThreadFeedPresentation(
feed,
{
+224 -92
View File
@@ -1,14 +1,22 @@
import type {
EnvironmentThread,
ThreadConversationMessage,
ThreadPendingApproval,
ThreadPendingUserInput,
ThreadRunSummary,
ThreadUserInputQuestion,
ThreadWorkEntry,
} from "@t3tools/client-runtime/state/shell";
import type { RunId } from "@t3tools/contracts";
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;
@@ -41,6 +49,24 @@ export interface ThreadFeedActivity {
| "zap";
readonly toolLike: 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;
}
type RawThreadFeedEntry =
@@ -48,7 +74,7 @@ type RawThreadFeedEntry =
readonly type: "message";
readonly id: string;
readonly createdAt: string;
readonly message: ThreadConversationMessage;
readonly message: ThreadFeedMessage;
}
| {
readonly type: "activity";
@@ -76,10 +102,12 @@ export type ThreadFeedEntry =
readonly expanded: boolean;
};
export type ThreadFeedLatestRun = Pick<
ThreadRunSummary,
"runId" | "status" | "startedAt" | "completedAt"
>;
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;
@@ -100,30 +128,29 @@ function capitalizePhrase(value: string): string {
return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
}
function workEntryIsToolLike(entry: ThreadWorkEntry): boolean {
function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
return (
entry.tone === "tool" ||
entry.tone === "thinking" ||
entry.tone === "error" ||
entry.command !== undefined ||
entry.requestKind !== undefined
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 workEntryStatus(entry: ThreadWorkEntry): ThreadFeedActivity["status"] {
if (!workEntryIsToolLike(entry)) return null;
if (
entry.tone === "error" ||
entry.toolLifecycleStatus === "failed" ||
entry.toolLifecycleStatus === "declined"
) {
return "failure";
}
return entry.toolLifecycleStatus === "completed" ? "success" : "neutral";
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 workEntryIcon(entry: ThreadWorkEntry): ThreadFeedActivity["icon"] {
switch (entry.itemType) {
function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
switch (item.type) {
case "reasoning":
return "agent";
case "command_execution":
@@ -136,6 +163,8 @@ function workEntryIcon(entry: ThreadWorkEntry): ThreadFeedActivity["icon"] {
return "globe";
case "approval_request":
case "user_input_request":
case "user_message":
case "assistant_message":
return "message";
case "dynamic_tool":
return "wrench";
@@ -144,71 +173,153 @@ function workEntryIcon(entry: ThreadWorkEntry): ThreadFeedActivity["icon"] {
case "run_interrupt_request":
case "run_interrupt_result":
return "warning";
case "error":
return "alert";
case "checkpoint":
case "proposed_plan":
case "todo_list":
return "check";
default:
if (entry.tone === "error") return "alert";
if (entry.tone === "thinking") return "agent";
if (entry.tone === "info") return "check";
case "compaction":
case "handoff":
case "fork":
case "thread_created":
return "zap";
}
}
function workEntryPreview(entry: ThreadWorkEntry): string | null {
if (entry.command) return entry.command;
if (entry.detail) return entry.detail;
const firstPath = entry.changedFiles?.[0];
if (!firstPath) return null;
return entry.changedFiles?.length === 1
? firstPath
: `${firstPath} +${(entry.changedFiles?.length ?? 1) - 1} more`;
function itemSummary(item: OrchestrationV2TurnItem): string {
const title = item.title?.trim();
if (title) return 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 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 buildWorkEntryExpandedBody(entry: ThreadWorkEntry): string | null {
const blocks: string[] = [];
const append = (value: string | null | undefined) => {
const trimmed = value?.trim();
if (trimmed && !blocks.includes(trimmed)) blocks.push(trimmed);
};
append(entry.rawCommand ?? entry.command);
append(entry.detail);
if (entry.changedFiles?.length) append(entry.changedFiles.join("\n"));
append(JSON.stringify(entry.structuredPayload, null, 2));
return blocks.length === 0 ? null : blocks.join("\n\n");
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(entry: ThreadWorkEntry): ThreadFeedActivity {
const summary = capitalizePhrase(entry.toolTitle ?? entry.label);
const detail = workEntryPreview(entry);
const fullDetail = buildWorkEntryExpandedBody(entry);
function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
const item = row.item;
const summary = itemSummary(item);
const detail = itemPreview(item);
const fullDetail = JSON.stringify(
{
visibility: row.visibility,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
item,
},
null,
2,
);
return {
id: entry.id,
createdAt: entry.createdAt,
runId: entry.runId,
id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
createdAt: DateTime.formatIso(item.startedAt ?? item.updatedAt),
runId: item.runId,
summary,
detail,
fullDetail,
icon: workEntryIcon(entry),
icon: itemIcon(item),
copyText: [summary, detail, fullDetail]
.filter(
(value, index, values): value is string =>
Boolean(value) && values.indexOf(value) === index,
)
.join("\n"),
toolLike: workEntryIsToolLike(entry),
status: workEntryStatus(entry),
toolLike: itemIsToolLike(item),
status: itemStatus(item),
projectedItem: row,
};
}
function byCreatedAt<A extends { readonly createdAt: string }>(left: A, right: A): number {
return left.createdAt.localeCompare(right.createdAt);
}
function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
return (
entry.type === "message" &&
entry.message.text.trim().length === 0 &&
(entry.message.attachments ?? []).length === 0
entry.message.attachments.length === 0
);
}
@@ -410,32 +521,53 @@ export function buildPendingUserInputAnswers(
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(
thread: EnvironmentThread,
options?: { readonly loadedMessages?: ReadonlyArray<ThreadConversationMessage> },
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
): ThreadFeedEntry[] {
const loadedMessages = options?.loadedMessages ?? thread.messages;
const oldestLoadedMessageCreatedAt =
options?.loadedMessages === undefined ? null : (loadedMessages[0]?.createdAt ?? null);
const entries: RawThreadFeedEntry[] = [
...loadedMessages.map((message) => ({
type: "message" as const,
id: message.id,
createdAt: message.createdAt,
message,
})),
...thread.workEntries
.filter(
(entry) =>
oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt,
)
.map((entry) => ({
type: "activity" as const,
id: entry.id,
createdAt: entry.createdAt,
runId: entry.runId,
activity: toFeedActivity(entry),
})),
];
return groupAdjacentActivities(entries.toSorted(byCreatedAt));
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);
}
@@ -37,7 +37,10 @@ import {
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
import { useSelectedThreadDetail } from "../state/use-thread-detail";
import {
useSelectedThreadDetail,
useSelectedThreadProjection,
} from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
@@ -76,6 +79,7 @@ export function useThreadDraftForThread(input: {
export function useThreadComposerState() {
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const selectedThreadProjection = useSelectedThreadProjection();
const composerDrafts = useAtomValue(composerDraftsAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
@@ -91,8 +95,8 @@ export function useThreadComposerState() {
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
() => buildThreadFeed(selectedThreadProjection?.projection.visibleTurnItems ?? []),
[selectedThreadProjection?.projection.visibleTurnItems],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
+27 -1
View File
@@ -1,9 +1,16 @@
import { useAtomValue } from "@effect/atom-react";
import type { ScopedThreadProjection } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { Atom } from "effect/unstable/reactivity";
import { useEnvironmentThread } from "./threads";
import { environmentThreadDetails, useEnvironmentThread } from "./threads";
import { useThreadSelection } from "./use-thread-selection";
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<ScopedThreadProjection | null>(null).pipe(
Atom.withLabel("mobile-thread-projection:empty"),
);
export interface ThreadDetailTarget {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
@@ -24,3 +31,22 @@ export function useSelectedThreadDetailState() {
export function useSelectedThreadDetail() {
return Option.getOrNull(useSelectedThreadDetailState().data);
}
export function useThreadProjection(target: ThreadDetailTarget): ScopedThreadProjection | null {
return useAtomValue(
target.environmentId === null || target.threadId === null
? EMPTY_THREAD_PROJECTION_ATOM
: environmentThreadDetails.threadAtom({
environmentId: target.environmentId,
threadId: target.threadId,
}),
);
}
export function useSelectedThreadProjection(): ScopedThreadProjection | null {
const { selectedThread } = useThreadSelection();
return useThreadProjection({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
}