Rework message metadata, timestamps, and tool work log rows (#3022)

Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-06-10 14:38:42 -07:00
1 parent 343061a053
commit 1916ac6d55
10 files changed
+1562 -494

No files matched your search

+2 -33
View File
@@ -50,7 +50,6 @@ import {
parseStandaloneComposerSlashCommand,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -61,9 +60,7 @@ import {
findLatestProposedPlan,
deriveWorkLogEntries,
hasActionableProposedPlan,
hasToolActivityForTurn,
isLatestTurnSettled,
formatElapsed,
} from "../session-logic";
import { type LegendListRef } from "@legendapp/list/react";
import {
@@ -1517,14 +1514,7 @@ export default function ChatView(props: ChatViewProps) {
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
const phase = derivePhase(activeThread?.session ?? null);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
[activeLatestTurn?.turnId, threadActivities],
);
const latestTurnHasToolActivity = useMemo(
() => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId),
[activeLatestTurn?.turnId, threadActivities],
);
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
const pendingApprovals = useMemo(
() => derivePendingApprovals(threadActivities),
[threadActivities],
@@ -1859,25 +1849,6 @@ export default function ChatView(props: ChatViewProps) {
return byUserMessageId;
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
const completionSummary = useMemo(() => {
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!latestTurnHasToolActivity) return null;
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
return elapsed ? `Worked for ${elapsed}` : null;
}, [
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
latestTurnHasToolActivity,
latestTurnSettled,
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!latestTurnSettled) return null;
if (!completionSummary) return null;
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
@@ -3885,12 +3856,10 @@ export default function ChatView(props: ChatViewProps) {
key={activeThread.id}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
activeTurnId={activeLatestTurn?.turnId ?? null}
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
completionSummary={completionSummary}
latestTurn={activeLatestTurn}
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
activeThreadEnvironmentId={activeThread.environmentId}
routeThreadKey={routeThreadKey}
@@ -68,11 +68,11 @@ export const MessageCopyButton = memo(function MessageCopyButton({
type="button"
size={size}
variant={variant}
className={cn(className)}
className={cn("text-muted-foreground hover:text-foreground", className)}
/>
}
>
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
{isCopied ? <CheckIcon className="size-3 text-primary" /> : <CopyIcon className="size-3" />}
</TooltipTrigger>
<TooltipPopup>
<p>Copy to clipboard</p>
@@ -54,11 +54,9 @@ function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
latestTurn: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: vi.fn(),
@@ -131,9 +129,9 @@ describe("MessagesTimeline", () => {
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:00.000Z",
label: "thinking",
label: "read files",
detail: "Inspecting repository state",
tone: "thinking",
tone: "tool",
},
},
]}
@@ -144,7 +142,7 @@ describe("MessagesTimeline", () => {
await expect
.element(page.getByText("Send a message to start the conversation."))
.not.toBeInTheDocument();
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
} finally {
await screen.unmount();
@@ -231,16 +229,16 @@ describe("MessagesTimeline", () => {
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:00.000Z",
label: "thinking",
label: "read files",
detail: "Inspecting repository state",
tone: "thinking",
tone: "tool",
},
},
]}
/>,
);
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
expect(props.onIsAtEndChange).toHaveBeenCalledWith(true);
expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false });
expect(requestAnimationFrameSpy).toHaveBeenCalled();
@@ -415,4 +413,78 @@ describe("MessagesTimeline", () => {
await screen.unmount();
}
});
it("folds settled-turn work behind a Worked-for row and expands it on click", async () => {
const screen = await render(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-commentary",
kind: "message" as const,
createdAt: "2026-04-13T12:00:00.000Z",
message: {
id: "message-commentary" as never,
role: "assistant" as const,
text: "Let me look around first.",
turnId: "turn-1" as never,
createdAt: "2026-04-13T12:00:00.000Z",
completedAt: "2026-04-13T12:00:02.000Z",
streaming: false,
},
},
{
id: "entry-work",
kind: "work" as const,
createdAt: "2026-04-13T12:00:05.000Z",
entry: {
id: "work-1",
createdAt: "2026-04-13T12:00:05.000Z",
turnId: "turn-1" as never,
label: "read files",
detail: "Inspecting repository state",
tone: "tool" as const,
},
},
{
id: "entry-final",
kind: "message" as const,
createdAt: "2026-04-13T12:00:20.000Z",
message: {
id: "message-final" as never,
role: "assistant" as const,
text: "All done.",
turnId: "turn-1" as never,
createdAt: "2026-04-13T12:00:20.000Z",
completedAt: "2026-04-13T12:00:30.000Z",
streaming: false,
},
},
]}
/>,
);
try {
const foldButton = page.getByRole("button", { name: "Worked for 30s" });
await expect.element(foldButton).toBeVisible();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
expect(document.body.textContent).toContain("All done.");
expect(document.body.textContent).not.toContain("Let me look around first.");
expect(document.body.textContent).not.toContain("Inspecting repository state");
await foldButton.click();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "true");
expect(document.body.textContent).toContain("Let me look around first.");
expect(document.body.textContent).toContain("Inspecting repository state");
await foldButton.click();
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
expect(document.body.textContent).not.toContain("Inspecting repository state");
} finally {
await screen.unmount();
}
});
});
@@ -250,7 +250,7 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: "assistant-final-entry",
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -265,7 +265,6 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRows).toHaveLength(2);
expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
});
it("marks only the active assistant turn as streaming for copy controls", () => {
@@ -300,11 +299,13 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: "assistant-two-entry",
completionSummary: "done",
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:19Z",
completedAt: null,
},
isWorking: false,
activeTurnInProgress: true,
activeTurnId: "turn-2" as never,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
@@ -316,9 +317,7 @@ describe("deriveMessagesTimelineRows", () => {
);
expect(assistantRows[0]?.assistantCopyStreaming).toBe(false);
expect(assistantRows[0]?.completionSummary).toBeNull();
expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
expect(assistantRows[1]?.completionSummary).toBe("done");
});
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
@@ -360,7 +359,6 @@ describe("deriveMessagesTimelineRows", () => {
},
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map([
@@ -381,6 +379,347 @@ describe("deriveMessagesTimelineRows", () => {
expect(userRow?.revertTurnCount).toBe(1);
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
});
it("folds settled-turn commentary and work behind a Worked-for row", () => {
const timelineEntries = [
{
id: "user-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-1" as never,
role: "user" as const,
text: "Build it",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "assistant-thought-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:05Z",
message: {
id: "assistant-thought" as never,
role: "assistant" as const,
text: "Looking around first.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:05Z",
completedAt: "2026-01-01T00:00:06Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work" as const,
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "assistant-final-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant" as const,
text: "Done",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:22Z",
streaming: false,
},
},
];
const collapsedRows = deriveMessagesTimelineRows({
timelineEntries,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const foldRow = collapsedRows.find(
(row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
row.kind === "turn-fold",
);
expect(foldRow?.turnId).toBe("turn-1");
expect(foldRow?.expanded).toBe(false);
// First fold entry (00:00:05) → terminal message completedAt (00:00:22).
expect(foldRow?.label).toBe("Worked for 17s");
expect(collapsedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"assistant-final-entry",
]);
const expandedRows = deriveMessagesTimelineRows({
timelineEntries,
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(expandedRows.map((row) => row.id)).toEqual([
"user-entry",
"turn-fold:turn-1",
"assistant-thought-entry",
"work-entry-1",
"assistant-final-entry",
]);
expect(
expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
).toBeDefined();
});
it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:05Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:05Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "interrupted",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:47Z",
},
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows).toEqual([
expect.objectContaining({
kind: "turn-fold",
turnId: "turn-1",
label: "You stopped after 47s",
expanded: false,
}),
]);
});
it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
// Right after send, isWorking is true but latestTurn still points at the
// previous, settled turn — it must stay folded through that window.
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:05Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:05Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
{
id: "assistant-final-entry",
kind: "message",
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant",
text: "Done",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:22Z",
streaming: false,
},
},
{
id: "user-followup-entry",
kind: "message",
createdAt: "2026-01-01T00:01:00Z",
message: {
id: "user-followup" as never,
role: "user",
text: "yooo",
turnId: null,
createdAt: "2026-01-01T00:01:00Z",
streaming: false,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "completed",
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:22Z",
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:01:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.map((row) => row.id)).toEqual([
"turn-fold:turn-1",
"assistant-final-entry",
"user-followup-entry",
"working-indicator-row",
]);
const finalRow = rows.find((row) => row.id === "assistant-final-entry");
expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true);
});
it("does not fold the active in-progress turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:05Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Working on it.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:05Z",
completedAt: "2026-01-01T00:00:06Z",
streaming: false,
},
},
{
id: "work-entry-1",
kind: "work",
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Ran command",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "running",
startedAt: "2026-01-01T00:00:00Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
expect(rows.map((row) => row.id)).toEqual([
"assistant-thought-entry",
"work-entry-1",
"working-indicator-row",
]);
});
it("only shows assistant metadata on the terminal assistant message", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:10Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Checking first.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:10Z",
completedAt: "2026-01-01T00:00:11Z",
streaming: false,
},
},
{
id: "assistant-final-entry",
kind: "message",
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-final" as never,
role: "assistant",
text: "Done.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
completedAt: "2026-01-01T00:00:30Z",
streaming: false,
},
},
],
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const assistantRows = rows.filter(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "assistant",
);
expect(assistantRows.map((row) => row.showAssistantMeta)).toEqual([false, true]);
});
it("withholds assistant metadata while the active turn is still in progress", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "assistant-thought-entry",
kind: "message",
createdAt: "2026-01-01T00:00:10Z",
message: {
id: "assistant-thought" as never,
role: "assistant",
text: "Working on it.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:10Z",
completedAt: "2026-01-01T00:00:11Z",
streaming: false,
},
},
],
latestTurn: {
turnId: "turn-1" as never,
state: "running",
startedAt: "2026-01-01T00:00:00Z",
completedAt: null,
},
isWorking: true,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const assistantRow = rows.find(
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
row.kind === "message" && row.message.role === "assistant",
);
expect(assistantRow?.showAssistantMeta).toBe(false);
expect(assistantRow?.showAssistantCopyButton).toBe(false);
});
});
describe("computeStableMessagesTimelineRows", () => {
@@ -417,7 +756,6 @@ describe("computeStableMessagesTimelineRows", () => {
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -467,7 +805,6 @@ describe("computeStableMessagesTimelineRows", () => {
entry: secondWorkEntry,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -522,7 +859,6 @@ describe("computeStableMessagesTimelineRows", () => {
message: secondUserMessage,
},
],
completionDividerBeforeEntryId: null,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
@@ -1,9 +1,16 @@
import * as Equal from "effect/Equal";
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type TurnId } from "@t3tools/contracts";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
function computeElapsedMs(startIso: string, endIso: string): number | null {
const start = Date.parse(startIso);
const end = Date.parse(endIso);
if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
return Math.max(0, end - start);
}
export interface TimelineDurationMessage {
id: string;
@@ -12,6 +19,11 @@ export interface TimelineDurationMessage {
completedAt?: string | undefined;
}
export type TimelineLatestTurn = Pick<
OrchestrationLatestTurn,
"turnId" | "state" | "startedAt" | "completedAt"
>;
export type MessagesTimelineRow =
| {
kind: "work";
@@ -19,14 +31,21 @@ export type MessagesTimelineRow =
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "turn-fold";
id: string;
createdAt: string;
turnId: TurnId;
label: string;
expanded: boolean;
}
| {
kind: "message";
id: string;
createdAt: string;
message: ChatMessage;
durationStart: string;
showCompletionDivider: boolean;
completionSummary: string | null;
showAssistantMeta: boolean;
showAssistantCopyButton: boolean;
assistantCopyStreaming: boolean;
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
@@ -110,13 +129,137 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
return new Set(lastAssistantMessageIdByResponseKey.values());
}
interface TurnFold {
turnId: TurnId;
anchorEntryId: string;
createdAt: string;
hiddenEntryIds: ReadonlySet<string>;
label: string;
}
/**
* The latest turn counts as unsettled while it is still running (or has not
* recorded a completion). This is deliberately keyed on the turn's own
* lifecycle rather than transient working state: right after the user sends
* a message, the previous turn is still the "active" one until the server
* creates the new turn, and folding must not flicker through that window.
*/
function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null {
if (!latestTurn) {
return null;
}
const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
return isSettled ? null : latestTurn.turnId;
}
/**
* Settled turns fold their commentary and tool activity behind a
* "Worked for ..." row anchored at the turn's first foldable entry; the
* terminal assistant message stays visible below the fold.
*/
function deriveTurnFolds(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
terminalAssistantMessageIds: ReadonlySet<string>;
latestTurn: TimelineLatestTurn | null;
unsettledTurnId: TurnId | null;
}): ReadonlyMap<string, TurnFold> {
interface TurnGroup {
entries: Array<TimelineEntry>;
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
hasStreamingMessage: boolean;
}
const groupsByTurnId = new Map<TurnId, TurnGroup>();
for (const entry of input.timelineEntries) {
const turnId =
entry.kind === "message" && entry.message.role === "assistant"
? (entry.message.turnId ?? null)
: entry.kind === "work"
? (entry.entry.turnId ?? null)
: null;
if (!turnId) {
continue;
}
const group = groupsByTurnId.get(turnId) ?? {
entries: [],
terminalEntry: null,
hasStreamingMessage: false,
};
group.entries.push(entry);
if (entry.kind === "message") {
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
group.terminalEntry = entry;
}
if (entry.message.streaming) {
group.hasStreamingMessage = true;
}
}
groupsByTurnId.set(turnId, group);
}
const foldsByAnchorEntryId = new Map<string, TurnFold>();
for (const [turnId, group] of groupsByTurnId) {
if (turnId === input.unsettledTurnId) {
continue;
}
if (group.hasStreamingMessage) {
continue;
}
const hiddenEntryIds = new Set<string>();
for (const entry of group.entries) {
if (entry.id !== group.terminalEntry?.id) {
hiddenEntryIds.add(entry.id);
}
}
if (hiddenEntryIds.size === 0) {
continue;
}
const firstEntry = group.entries[0];
const lastEntry = group.entries.at(-1);
if (!firstEntry || !lastEntry) {
continue;
}
const isLatestInterruptedTurn =
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
const elapsedMs =
input.latestTurn?.turnId === turnId &&
input.latestTurn.startedAt &&
input.latestTurn.completedAt
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
: computeElapsedMs(
firstEntry.createdAt,
group.terminalEntry?.message.completedAt ??
(lastEntry.kind === "message"
? (lastEntry.message.completedAt ?? lastEntry.createdAt)
: lastEntry.createdAt),
);
const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
const label = isLatestInterruptedTurn
? duration
? `You stopped after ${duration}`
: "You stopped this response"
: duration
? `Worked for ${duration}`
: "Worked";
foldsByAnchorEntryId.set(firstEntry.id, {
turnId,
anchorEntryId: firstEntry.id,
createdAt: firstEntry.createdAt,
hiddenEntryIds,
label,
});
}
return foldsByAnchorEntryId;
}
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
completionDividerBeforeEntryId: string | null;
completionSummary?: string | null;
latestTurn?: TimelineLatestTurn | null;
expandedTurnIds?: ReadonlySet<TurnId>;
isWorking: boolean;
activeTurnInProgress?: boolean;
activeTurnId?: TurnId | null;
activeTurnStartedAt: string | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
@@ -126,6 +269,21 @@ export function deriveMessagesTimelineRows(input: {
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
);
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null);
const foldsByAnchorEntryId = deriveTurnFolds({
timelineEntries: input.timelineEntries,
terminalAssistantMessageIds,
latestTurn: input.latestTurn ?? null,
unsettledTurnId,
});
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorEntryId.values()) {
if (!input.expandedTurnIds?.has(fold.turnId)) {
for (const entryId of fold.hiddenEntryIds) {
collapsedEntryIds.add(entryId);
}
}
}
for (let index = 0; index < input.timelineEntries.length; index += 1) {
const timelineEntry = input.timelineEntries[index];
@@ -133,12 +291,35 @@ export function deriveMessagesTimelineRows(input: {
continue;
}
const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
if (turnFold) {
nextRows.push({
kind: "turn-fold",
id: `turn-fold:${turnFold.turnId}`,
createdAt: turnFold.createdAt,
turnId: turnFold.turnId,
label: turnFold.label,
expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
});
}
if (collapsedEntryIds.has(timelineEntry.id)) {
continue;
}
if (timelineEntry.kind === "work") {
const groupedEntries = [timelineEntry.entry];
let cursor = index + 1;
while (cursor < input.timelineEntries.length) {
const nextEntry = input.timelineEntries[cursor];
if (!nextEntry || nextEntry.kind !== "work") break;
if (
!nextEntry ||
nextEntry.kind !== "work" ||
collapsedEntryIds.has(nextEntry.id) ||
foldsByAnchorEntryId.has(nextEntry.id)
) {
break;
}
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
@@ -164,26 +345,28 @@ export function deriveMessagesTimelineRows(input: {
const assistantTurnStillInProgress =
timelineEntry.message.role === "assistant" &&
input.activeTurnInProgress === true &&
input.activeTurnId != null &&
timelineEntry.message.turnId === input.activeTurnId;
unsettledTurnId !== null &&
timelineEntry.message.turnId === unsettledTurnId;
const showCompletionDivider =
const durationStart =
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
// While the turn is still running, the latest assistant message is only
// provisionally terminal — withhold the metadata row until the turn
// settles so commentary doesn't flash timestamps mid-work.
const showAssistantMeta =
timelineEntry.message.role === "assistant" &&
input.completionDividerBeforeEntryId === timelineEntry.id;
terminalAssistantMessageIds.has(timelineEntry.message.id) &&
!assistantTurnStillInProgress;
nextRows.push({
kind: "message",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
message: timelineEntry.message,
durationStart:
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
showCompletionDivider,
completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null,
showAssistantCopyButton:
timelineEntry.message.role === "assistant" &&
terminalAssistantMessageIds.has(timelineEntry.message.id),
durationStart,
showAssistantMeta,
showAssistantCopyButton: showAssistantMeta,
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
assistantTurnDiffSummary:
timelineEntry.message.role === "assistant"
@@ -235,6 +418,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "working":
return a.createdAt === (b as typeof a).createdAt;
case "turn-fold": {
const bf = b as typeof a;
return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
}
case "proposed-plan":
return a.proposedPlan === (b as typeof a).proposedPlan;
@@ -246,8 +434,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
return (
a.message === bm.message &&
a.durationStart === bm.durationStart &&
a.showCompletionDivider === bm.showCompletionDivider &&
a.completionSummary === bm.completionSummary &&
a.showAssistantMeta === bm.showAssistantMeta &&
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
@@ -94,11 +94,9 @@ function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnId: null,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
completionDividerBeforeEntryId: null,
completionSummary: null,
latestTurn: null,
turnDiffSummaryByAssistantMessageId: new Map(),
routeThreadKey: "environment-local:thread-1",
onOpenTurnDiff: () => {},
@@ -229,7 +227,7 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Context compacted");
expect(markup).toContain("Work log");
expect(markup).toContain("work log");
});
it("formats changed file paths from the workspace root", async () => {
@@ -297,4 +295,31 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("&lt;review_comment");
expect(markup).not.toContain("&lt;/review_comment&gt;");
});
it("renders a failure marker for failed tool lifecycle entries", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
timelineEntries={[
{
id: "entry-1",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "work-1",
createdAt: "2026-03-17T19:12:28.000Z",
label: "Glob",
tone: "tool",
toolLifecycleStatus: "failed",
detail: "No files found",
},
},
]}
/>,
);
expect(markup).toContain("lucide-x");
expect(markup).toContain('aria-label="Tool call failed"');
});
});
+469 -237
View File
@@ -6,20 +6,28 @@ import {
} from "@t3tools/contracts";
import {
createContext,
Fragment,
memo,
use,
useCallback,
useEffect,
Fragment,
useMemo,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
import {
deriveTimelineEntries,
workEntryIndicatesToolFailure,
workEntryIndicatesToolNeutralStatus,
workEntryIndicatesToolSuccess,
workLogEntryIsToolLike,
} from "../../session-logic";
import { type TurnDiffSummary } from "../../types";
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -29,21 +37,28 @@ import ChatMarkdown from "../ChatMarkdown";
import {
BotIcon,
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronUpIcon,
CircleAlertIcon,
EyeIcon,
GlobeIcon,
HammerIcon,
type LucideIcon,
MessageCircleIcon,
MinusIcon,
SquarePenIcon,
TerminalIcon,
Undo2Icon,
WrenchIcon,
XIcon,
ZapIcon,
} from "lucide-react";
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesCard } from "./ChangedFilesTree";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
@@ -53,6 +68,7 @@ import {
resolveAssistantMessageCopyState,
type StableMessagesTimelineRowsState,
type MessagesTimelineRow,
type TimelineLatestTurn,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -63,7 +79,7 @@ import {
import { cn } from "~/lib/utils";
import { useUiStateStore } from "~/uiStateStore";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatTimestamp } from "../../timestampFormat";
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
import {
buildInlineTerminalContextText,
@@ -96,11 +112,13 @@ interface TimelineRowSharedState {
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
}
interface TimelineRowActivityState {
isWorking: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
@@ -116,12 +134,10 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d
interface MessagesTimelineProps {
isWorking: boolean;
activeTurnInProgress: boolean;
activeTurnId?: TurnId | null;
activeTurnStartedAt: string | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
completionDividerBeforeEntryId: string | null;
completionSummary: string | null;
latestTurn: TimelineLatestTurn | null;
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
routeThreadKey: string;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
@@ -145,12 +161,10 @@ interface MessagesTimelineProps {
export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
activeTurnInProgress,
activeTurnId,
activeTurnStartedAt,
listRef,
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
latestTurn,
turnDiffSummaryByAssistantMessageId,
routeThreadKey,
onOpenTurnDiff,
@@ -166,26 +180,90 @@ export const MessagesTimeline = memo(function MessagesTimeline({
skills = EMPTY_TIMELINE_SKILLS,
onIsAtEndChange,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
// Toggling a fold inserts/removes rows between the fold row and the final
// message — everything above the trigger is unchanged, so the trigger stays
// put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
// exactly that (pin the bottom content when row data changes while scrolled
// to the end), yanking the trigger out of view. Suppress it for the frames
// in which the toggle's data change and item measurements settle.
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
setFoldToggleSettling(true);
setExpandedTurnIds((existing) => {
const next = new Set(existing);
if (next.has(turnId)) {
next.delete(turnId);
} else {
next.add(turnId);
}
return next;
});
}, []);
useEffect(() => {
if (!foldToggleSettling) {
return;
}
let secondFrameId: number | null = null;
const firstFrameId = window.requestAnimationFrame(() => {
secondFrameId = window.requestAnimationFrame(() => {
setFoldToggleSettling(false);
});
});
return () => {
window.cancelAnimationFrame(firstFrameId);
if (secondFrameId !== null) {
window.cancelAnimationFrame(secondFrameId);
}
};
}, [foldToggleSettling]);
// An in-session interrupt leaves its turn expanded so the user keeps their
// place; the next turn (or a reload, since this is local state) folds it.
const previousLatestTurnRef = useRef(latestTurn);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = latestTurn;
if (!latestTurn || previous?.turnId === undefined) {
return;
}
if (latestTurn.turnId === previous.turnId) {
if (previous.state === "running" && latestTurn.state === "interrupted") {
setExpandedTurnIds((existing) => {
const next = new Set(existing);
next.add(latestTurn.turnId);
return next;
});
}
return;
}
setExpandedTurnIds((existing) => {
if (!existing.has(previous.turnId)) {
return existing;
}
const next = new Set(existing);
next.delete(previous.turnId);
return next;
});
}, [latestTurn]);
const rawRows = useMemo(
() =>
deriveMessagesTimelineRows({
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
latestTurn,
expandedTurnIds,
isWorking,
activeTurnInProgress,
activeTurnId: activeTurnId ?? null,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
}),
[
timelineEntries,
completionDividerBeforeEntryId,
completionSummary,
latestTurn,
expandedTurnIds,
isWorking,
activeTurnInProgress,
activeTurnId,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
revertTurnCountByUserMessageId,
@@ -230,6 +308,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
}),
[
timestampFormat,
@@ -242,14 +321,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
],
);
const activityState = useMemo<TimelineRowActivityState>(
() => ({
isWorking,
isRevertingCheckpoint,
activeTurnInProgress,
}),
[isRevertingCheckpoint, isWorking],
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
);
// Stable renderItem — no closure deps. Row components read shared state
@@ -283,7 +364,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
renderItem={renderItem}
estimatedItemSize={90}
initialScrollAtEnd
maintainScrollAtEnd
maintainScrollAtEnd={!foldToggleSettling}
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
onScroll={handleScroll}
@@ -313,7 +394,11 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
return (
<div
className={cn(
"pb-4",
// Commentary (non-terminal assistant) rows carry no metadata row, so
// they sit closer to the work that follows them.
row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta
? "pb-2"
: "pb-4",
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
)}
data-timeline-row-id={row.id}
@@ -322,6 +407,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
<AssistantTimelineRow row={row} />
@@ -340,8 +426,8 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
<div className="flex justify-end">
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
<div className="group flex flex-col items-end gap-1">
<div className="relative max-w-[80%] rounded-2xl border border-border bg-secondary p-3">
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
@@ -380,21 +466,26 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
terminalContexts={terminalContexts}
skills={ctx.skills}
markdownCwd={ctx.markdownCwd}
footer={
<>
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} />
)}
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
</div>
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, ctx.timestampFormat)}
</p>
</>
}
/>
</div>
<div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
<div className="flex shrink-0 items-center gap-2">
<Tooltip>
<TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
{formatShortTimestamp(row.message.createdAt, ctx.timestampFormat)}
</TooltipTrigger>
<TooltipPopup>
{formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
</TooltipPopup>
</Tooltip>
<div className="flex items-center gap-0.5">
{canRevertAgentWork && <RevertUserMessageButton messageId={row.message.id} />}
{displayedUserMessage.copyText && (
<MessageCopyButton text={displayedUserMessage.copyText} variant="ghost" />
)}
</div>
</div>
</div>
</div>
);
}
@@ -410,7 +501,7 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
<Button
type="button"
size="xs"
variant="outline"
variant="ghost"
disabled={activity.isRevertingCheckpoint || activity.isWorking}
onClick={() => ctx.onRevertUserMessage(messageId)}
aria-label="Revert to this message"
@@ -424,16 +515,33 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
);
}
function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
const ctx = use(TimelineRowCtx);
const Icon = row.expanded ? ChevronDownIcon : ChevronRightIcon;
return (
<div className="border-b border-border/60 pb-2 pt-1">
<button
type="button"
aria-expanded={row.expanded}
data-scroll-anchor-ignore
onClick={() => ctx.onToggleTurnFold(row.turnId)}
className="flex items-center gap-1 px-1 text-xs text-muted-foreground tabular-nums transition-colors hover:text-foreground"
>
<span>{row.label}</span>
<Icon className="size-3.5" />
</button>
</div>
);
}
function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
return (
<>
{row.showCompletionDivider && (
<AssistantCompletionDivider completionSummary={row.completionSummary} />
)}
<div className="min-w-0 px-1 py-0.5">
<div className="relative min-w-0 px-1 py-0.5">
<ChatMarkdown
text={messageText}
cwd={ctx.markdownCwd}
@@ -446,41 +554,34 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
resolvedTheme={ctx.resolvedTheme}
onOpenTurnDiff={ctx.onOpenTurnDiff}
/>
<div className="mt-1.5 flex items-center gap-2">
<p className="text-[10px] text-muted-foreground/30">
{row.message.streaming ? (
<LiveMessageMeta
createdAt={row.message.createdAt}
durationStart={row.durationStart}
timestampFormat={ctx.timestampFormat}
/>
) : (
formatMessageMeta(
row.message.createdAt,
formatElapsed(row.durationStart, row.message.completedAt),
ctx.timestampFormat,
)
{row.showAssistantMeta ? (
<div className="mt-1.5 flex items-center gap-2 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover/assistant:opacity-100">
<AssistantCopyButton row={row} />
{!row.message.streaming && (
<Tooltip>
<TooltipTrigger
render={<p className="text-muted-foreground text-xs tabular-nums" />}
>
{formatShortTimestamp(
row.message.completedAt ?? row.message.createdAt,
ctx.timestampFormat,
)}
</TooltipTrigger>
<TooltipPopup>
{formatChatTimestampTooltip(
row.message.completedAt ?? row.message.createdAt,
ctx.timestampFormat,
)}
</TooltipPopup>
</Tooltip>
)}
</p>
<AssistantCopyButton row={row} />
</div>
</div>
) : null}
</div>
</>
);
}
function AssistantCompletionDivider({ completionSummary }: { completionSummary: string | null }) {
return (
<div className="my-3 flex items-center gap-3">
<span className="h-px flex-1 bg-border" />
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
{completionSummary ? `Response • ${completionSummary}` : "Response"}
</span>
<span className="h-px flex-1 bg-border" />
</div>
);
}
function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const assistantCopyState = resolveAssistantMessageCopyState({
text: row.message.text ?? null,
@@ -492,16 +593,7 @@ function AssistantCopyButton({ row }: { row: Extract<TimelineRow, { kind: "messa
return null;
}
return (
<div className="flex items-center opacity-0 transition-opacity duration-200 group-hover/assistant:opacity-100">
<MessageCopyButton
text={assistantCopyState.text ?? ""}
size="icon-xs"
variant="outline"
className="border-border/50 bg-background/35 text-muted-foreground/45 shadow-none hover:border-border/70 hover:bg-background/55 hover:text-muted-foreground/70"
/>
</div>
);
return <MessageCopyButton text={assistantCopyState.text ?? ""} variant="ghost" />;
}
function ProposedPlanTimelineRow({
@@ -526,7 +618,7 @@ function ProposedPlanTimelineRow({
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
return (
<div className="py-0.5 pl-1.5">
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70 tabular-nums">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
@@ -567,41 +659,11 @@ function WorkingTimer({ createdAt }: { createdAt: string }) {
return () => clearInterval(id);
}, [createdAt]);
return <span ref={textRef}>{initialText}</span>;
}
/** Live timestamp + elapsed duration for a streaming assistant message. */
function LiveMessageMeta({
createdAt,
durationStart,
timestampFormat,
}: {
createdAt: string;
durationStart: string | null | undefined;
timestampFormat: TimestampFormat;
}) {
const textRef = useRef<HTMLSpanElement>(null);
const initialText = formatLiveMessageMetaNow(createdAt, durationStart, timestampFormat);
useEffect(() => {
const updateText = () => {
if (textRef.current) {
textRef.current.textContent = formatLiveMessageMetaNow(
createdAt,
durationStart,
timestampFormat,
);
}
};
updateText();
if (!durationStart) {
return;
}
const id = setInterval(updateText, 1000);
return () => clearInterval(id);
}, [createdAt, durationStart, timestampFormat]);
return <span ref={textRef}>{initialText}</span>;
return (
<span ref={textRef} className="tabular-nums">
{initialText}
</span>
);
}
// ---------------------------------------------------------------------------
@@ -609,8 +671,7 @@ function LiveMessageMeta({
// re-render only the affected row, not the entire list.
// ---------------------------------------------------------------------------
/** Owns its own expand/collapse state so toggling re-renders only this row.
* State resets on unmount which is fine — work groups start collapsed. */
/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
const WorkGroupSection = memo(function WorkGroupSection({
groupedEntries,
}: {
@@ -618,38 +679,53 @@ const WorkGroupSection = memo(function WorkGroupSection({
}) {
const { workspaceRoot } = use(TimelineRowCtx);
const [isExpanded, setIsExpanded] = useState(false);
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const nonEmptyEntries = useMemo(
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
[groupedEntries],
);
const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: groupedEntries;
const hiddenCount = groupedEntries.length - visibleEntries.length;
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
const showHeader = hasOverflow || !onlyToolEntries;
const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: nonEmptyEntries;
const hiddenCount = nonEmptyEntries.length - visibleEntries.length;
const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry));
const headerTitle = onlyToolEntries
? nonEmptyEntries.length === 1
? "1 tool call"
: `${nonEmptyEntries.length} tool calls`
: "work log";
if (nonEmptyEntries.length === 0) return null;
return (
<div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
{showHeader && (
<div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
<p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
{groupLabel} ({groupedEntries.length})
</p>
{hasOverflow && (
<button
type="button"
className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
onClick={() => setIsExpanded((v) => !v)}
>
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
</button>
)}
</div>
)}
<div className="rounded-2xl border border-input bg-background p-2 pt-3 shadow-xs/5 not-dark:bg-clip-padding dark:bg-input/32">
<div className="mb-2 flex items-center justify-between gap-2 px-2">
<p className="font-medium text-foreground text-xs">{headerTitle}</p>
{hasOverflow && (
<button
type="button"
className="inline-flex cursor-pointer items-center gap-1 text-muted-foreground text-xs transition-colors duration-150 hover:text-foreground/80"
onClick={() => setIsExpanded((v) => !v)}
>
{isExpanded ? (
<>
Show less
<ChevronUpIcon className="size-3.5 shrink-0 opacity-80" />
</>
) : (
<>
Show {hiddenCount} more
<ChevronDownIcon className="size-3.5 shrink-0 opacity-80" />
</>
)}
</button>
)}
</div>
<div className="space-y-0.5">
{visibleEntries.map((workEntry) => (
<SimpleWorkEntryRow
key={`work-row:${workEntry.id}`}
key={workEntry.id}
workEntry={workEntry}
workspaceRoot={workspaceRoot}
/>
@@ -706,18 +782,50 @@ function AssistantChangedFilesSectionInner({
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
);
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
const changedFileCountLabel = String(checkpointFiles.length);
return (
<ChangedFilesCard
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onToggleAllDirectories={() =>
setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)
}
onOpenTurnDiff={onOpenTurnDiff}
/>
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
<div className="sticky top-2 z-10 mb-1.5 flex items-center justify-between gap-2 bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:absolute before:inset-x-0 before:-top-2 before:h-2 before:bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:content-['']">
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
<span>Changed files ({changedFileCountLabel})</span>
{hasNonZeroStat(summaryStat) && (
<>
<span className="mx-1">•</span>
<DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
</>
)}
</p>
<div className="flex items-center gap-1.5">
<Button
type="button"
size="xs"
variant="outline"
data-scroll-anchor-ignore
onClick={() => setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}
>
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
</Button>
<Button
type="button"
size="xs"
variant="outline"
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
>
View diff
</Button>
</div>
</div>
<ChangedFilesTree
key={`changed-files-tree:${turnSummary.turnId}`}
turnId={turnSummary.turnId}
files={checkpointFiles}
allDirectoriesExpanded={allDirectoriesExpanded}
resolvedTheme={resolvedTheme}
onOpenTurnDiff={onOpenTurnDiff}
/>
</div>
);
}
@@ -1075,24 +1183,6 @@ function formatWorkingTimerNow(startIso: string): string {
return formatWorkingTimer(startIso, new Date().toISOString()) ?? "0s";
}
function formatLiveMessageMetaNow(
createdAt: string,
durationStart: string | null | undefined,
timestampFormat: TimestampFormat,
): string {
const elapsed = durationStart ? formatElapsed(durationStart, new Date().toISOString()) : null;
return formatMessageMeta(createdAt, elapsed, timestampFormat);
}
function formatMessageMeta(
createdAt: string,
duration: string | null,
timestampFormat: TimestampFormat,
): string {
if (!duration) return formatTimestamp(createdAt, timestampFormat);
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
}
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
icon: LucideIcon;
className: string;
@@ -1112,7 +1202,7 @@ function workToneIcon(tone: TimelineWorkEntry["tone"]): {
if (tone === "info") {
return {
icon: CheckIcon,
className: "text-foreground/92",
className: "text-muted-foreground",
};
}
return {
@@ -1121,13 +1211,6 @@ function workToneIcon(tone: TimelineWorkEntry["tone"]): {
};
}
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
if (tone === "tool") return "text-muted-foreground/70";
if (tone === "thinking") return "text-muted-foreground/50";
return "text-muted-foreground/40";
}
function workEntryPreview(
workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
workspaceRoot: string | undefined,
@@ -1153,7 +1236,30 @@ function workEntryRawCommand(
return rawCommand === workEntry.command.trim() ? null : rawCommand;
}
function buildToolCallExpandedBody(workEntry: TimelineWorkEntry): string | null {
const blocks: string[] = [];
if (workEntry.detail?.trim()) {
blocks.push(workEntry.detail.trim());
}
const raw = workEntryRawCommand(workEntry);
if (raw?.trim()) {
blocks.push(`Full command\n${raw.trim()}`);
} else if (workEntry.command?.trim()) {
blocks.push(`Command\n${workEntry.command.trim()}`);
}
if (blocks.length === 0) {
return null;
}
return blocks.join("\n\n");
}
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
if (
workEntry.sourceActivityKind === "user-input.requested" ||
workEntry.sourceActivityKind === "user-input.resolved"
) {
return MessageCircleIcon;
}
if (workEntry.requestKind === "command") return TerminalIcon;
if (workEntry.requestKind === "file-read") return EyeIcon;
if (workEntry.requestKind === "file-change") return SquarePenIcon;
@@ -1193,13 +1299,18 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
}
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
const activity = use(TimelineRowActivityCtx);
const [expanded, setExpanded] = useState(false);
const iconConfig = workToneIcon(workEntry.tone);
const EntryIcon = workEntryIcon(workEntry);
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
const EntryIcon = showWarningIndicator ? XIcon : workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
const preview =
@@ -1210,78 +1321,199 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
: rawPreview;
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const expandedBody = buildToolCallExpandedBody(workEntry);
const canExpand = expandedBody !== null;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
const showFailedIndicator = workEntryIndicatesToolFailure(workEntry);
const showDestructiveRowStyle =
showFailedIndicator &&
(workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry));
const iconWrapperClass = cn(
"flex size-5 shrink-0 items-center justify-center",
showWarningIndicator
? "text-destructive"
: showDestructiveRowStyle
? "text-destructive"
: workEntry.tone === "tool" || showFailedIndicator
? "text-muted-foreground"
: iconConfig.className,
);
const headingClass = showWarningIndicator
? "font-medium text-warning"
: showDestructiveRowStyle
? "font-medium text-destructive"
: "font-medium text-foreground";
const turnSettled = !activity.activeTurnInProgress;
const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry);
const showSuccessIndicator =
workEntryIndicatesToolSuccess(workEntry) ||
(turnSettled && workEntryIndicatesToolNeutralStatus(workEntry));
const rowToggleProps = canExpand
? {
role: "button" as const,
tabIndex: 0 as const,
onClick: () => setExpanded((v) => !v),
onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setExpanded((v) => !v);
}
},
}
: {};
return (
<div className="rounded-lg px-1 py-1">
<div
className={cn(
"flex flex-col rounded-xl border border-transparent px-2 py-2 transition-colors",
canExpand &&
"cursor-pointer hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
)}
{...rowToggleProps}
>
<div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
<span
className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
>
<EntryIcon className="size-3" />
<span className={iconWrapperClass}>
<EntryIcon className="block size-3.5 shrink-0" aria-hidden />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
{rawCommand ? (
<div className="max-w-full">
<div className="flex min-w-0 flex-1 items-center gap-2">
<div className="min-w-0 flex-1 overflow-hidden">
{rawCommand ? (
<div className="max-w-full">
<Tooltip>
<TooltipTrigger
closeDelay={0}
delay={75}
onClick={stopRowToggle}
onPointerDown={stopRowToggle}
render={
<p
className="flex min-w-0 w-full items-center gap-2 text-xs leading-5"
aria-label={displayText}
/>
}
>
<span className={cn("min-w-0 shrink truncate", headingClass)}>{heading}</span>
{preview && (
<span className="min-w-0 flex-1 cursor-default truncate text-muted-foreground transition-colors hover:text-muted-foreground/90 focus-visible:text-muted-foreground/90">
{preview}
</span>
)}
</TooltipTrigger>
<TooltipPopup
align="start"
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
side="top"
>
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
{rawCommand}
</div>
</TooltipPopup>
</Tooltip>
</div>
) : (
<Tooltip>
<TooltipTrigger
closeDelay={0}
delay={75}
render={
<p
className={cn(
"truncate rounded-sm text-xs leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
aria-label={displayText}
/>
}
className="block min-w-0 w-full text-left"
aria-label={displayText}
onClick={stopRowToggle}
onPointerDown={stopRowToggle}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
<p className="flex min-w-0 w-full items-center gap-2 text-[11px] leading-5">
<span className={cn("min-w-0 shrink truncate", headingClass)}>{heading}</span>
{preview && (
<span className="min-w-0 flex-1 truncate text-muted-foreground">
{preview}
</span>
)}
</p>
</TooltipTrigger>
<TooltipPopup
align="start"
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
side="top"
>
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
{rawCommand}
</div>
<TooltipPopup className="max-w-[min(720px,calc(100vw-2rem))]">
<p className="whitespace-pre-wrap wrap-break-word text-xs leading-5">
{displayText}
</p>
</TooltipPopup>
</Tooltip>
</div>
) : (
<Tooltip>
<TooltipTrigger className="block min-w-0 w-full text-left" aria-label={displayText}>
<p
)}
</div>
<div className="flex shrink-0 items-center gap-0.5">
<span
className="flex size-5 shrink-0 items-center justify-center"
aria-hidden={!canExpand}
>
{canExpand ? (
<ChevronDownIcon
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
"size-3.5 shrink-0 text-muted-foreground opacity-80 transition-transform duration-200",
expanded && "rotate-180",
)}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
</p>
</TooltipTrigger>
<TooltipPopup className="max-w-[min(720px,calc(100vw-2rem))]">
<p className="whitespace-pre-wrap wrap-break-word text-xs leading-5">
{displayText}
</p>
</TooltipPopup>
</Tooltip>
)}
aria-hidden
/>
) : null}
</span>
<span className="flex size-5 shrink-0 items-center justify-center">
{showFailedIndicator ? (
<Tooltip>
<TooltipTrigger
render={
<span
className="flex size-5 items-center justify-center"
aria-label="Tool call failed"
/>
}
>
<XIcon className="block size-3.5 shrink-0 text-destructive" aria-hidden />
</TooltipTrigger>
<TooltipPopup>Failed</TooltipPopup>
</Tooltip>
) : showSuccessIndicator ? (
<Tooltip>
<TooltipTrigger
render={<span className="flex size-5 items-center justify-center" />}
>
<span className="inline-flex size-5 items-center justify-center text-muted-foreground">
<CheckIcon
className="block size-3.5 shrink-0 stroke-current"
stroke="currentColor"
aria-hidden
/>
</span>
</TooltipTrigger>
<TooltipPopup>Completed</TooltipPopup>
</Tooltip>
) : showNeutralIndicator ? (
<Tooltip>
<TooltipTrigger
render={<span className="flex size-5 items-center justify-center" />}
>
<MinusIcon
className="block size-3.5 shrink-0 text-muted-foreground opacity-80"
aria-hidden
/>
</TooltipTrigger>
<TooltipPopup>Empty</TooltipPopup>
</Tooltip>
) : null}
</span>
</div>
</div>
</div>
{hasChangedFiles && !previewIsChangedFiles && (
<div className="mt-1 flex flex-wrap gap-1 pl-6">
{expanded && canExpand && expandedBody ? (
<div
className="mt-2 ms-7 border-s border-border/45 ps-3 pt-0.5"
onClick={stopRowToggle}
onPointerDown={stopRowToggle}
>
<pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground">
{expandedBody}
</pre>
</div>
) : null}
{hasChangedFiles && (
<div
className="mt-1 flex flex-wrap gap-1"
onClick={stopRowToggle}
onPointerDown={stopRowToggle}
>
{workEntry.changedFiles?.slice(0, 4).map((filePath) => {
const displayPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
return (
+218 -113
View File
@@ -8,7 +8,6 @@ import {
import { describe, expect, it } from "vite-plus/test";
import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
derivePendingApprovals,
@@ -18,8 +17,10 @@ import {
findLatestProposedPlan,
findSidebarProposedPlan,
hasActionableProposedPlan,
hasToolActivityForTurn,
isLatestTurnSettled,
workEntryIndicatesToolFailure,
workEntryIndicatesToolNeutralStatus,
workEntryIndicatesToolSuccess,
} from "./session-logic";
let nextActivityId = 0;
@@ -572,6 +573,123 @@ describe("findSidebarProposedPlan", () => {
});
});
describe("workEntryIndicatesToolFailure", () => {
const base = {
id: "w1",
createdAt: "2026-01-01T00:00:00.000Z",
label: "Read",
};
it("is true for error tone", () => {
expect(
workEntryIndicatesToolFailure({
...base,
tone: "error",
detail: "nothing special",
}),
).toBe(true);
});
it("is true when lifecycle says failed even if detail is empty", () => {
expect(
workEntryIndicatesToolFailure({
...base,
tone: "tool",
toolLifecycleStatus: "failed",
}),
).toBe(true);
});
it("detects file-not-found style tool output with completed lifecycle", () => {
expect(
workEntryIndicatesToolFailure({
...base,
tone: "tool",
toolLifecycleStatus: "completed",
detail: "File not found: C:\\foo\\nonexistent.ts",
}),
).toBe(true);
});
it("detects glob no files and PowerShell command errors", () => {
expect(
workEntryIndicatesToolFailure({
...base,
label: "Glob",
tone: "tool",
detail: "No files found",
}),
).toBe(true);
expect(
workEntryIndicatesToolFailure({
...base,
label: "Bash",
tone: "tool",
detail:
"The term 'this_is_not_a_command' is not recognized as the name of a cmdlet, function, script file, or operable program.",
}),
).toBe(true);
});
it("is false for successful completed tools", () => {
expect(
workEntryIndicatesToolFailure({
...base,
tone: "tool",
toolLifecycleStatus: "completed",
detail: "Found 3 matching files",
}),
).toBe(false);
});
it("treats successful tool rows as success candidates", () => {
expect(
workEntryIndicatesToolSuccess({
...base,
tone: "tool",
toolLifecycleStatus: "completed",
detail: "ok",
}),
).toBe(true);
expect(
workEntryIndicatesToolSuccess({
...base,
tone: "tool",
toolLifecycleStatus: "inProgress",
detail: "…",
}),
).toBe(false);
expect(workEntryIndicatesToolSuccess({ ...base, tone: "thinking", detail: "…" })).toBe(false);
expect(
workEntryIndicatesToolNeutralStatus({
...base,
tone: "tool",
toolLifecycleStatus: "inProgress",
detail: "…",
}),
).toBe(true);
expect(
workEntryIndicatesToolNeutralStatus({
...base,
tone: "tool",
toolLifecycleStatus: "completed",
detail: "ok",
}),
).toBe(false);
});
it("does not run heuristics on non-tool info rows", () => {
expect(
workEntryIndicatesToolFailure({
...base,
label: "Context compacted",
tone: "info",
detail: "File not found in conversation",
}),
).toBe(false);
});
});
describe("deriveWorkLogEntries", () => {
it("omits tool started entries and keeps completed entries", () => {
const activities: OrchestrationThreadActivity[] = [
@@ -589,7 +707,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
});
@@ -618,7 +736,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["task-progress", "task-complete"]);
});
@@ -634,7 +752,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries[0]?.label).toBe("Searching for API endpoints");
});
@@ -650,25 +768,33 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries[0]?.label).toBe("Failed to deploy changes");
expect(entries[0]?.tone).toBe("error");
});
it("filters by turn id when provided", () => {
it("keeps tool entries from every turn and tags each with its turn id", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "turn-1", turnId: "turn-1", summary: "Tool call", kind: "tool.started" }),
makeActivity({
id: "turn-2",
id: "turn-1-tool",
turnId: "turn-1",
summary: "Tool call complete",
kind: "tool.completed",
}),
makeActivity({
id: "turn-2-tool",
turnId: "turn-2",
summary: "Tool call complete",
kind: "tool.completed",
}),
makeActivity({ id: "no-turn", summary: "Checkpoint captured", tone: "info" }),
];
const entries = deriveWorkLogEntries(activities, TurnId.make("turn-2"));
expect(entries.map((entry) => entry.id)).toEqual(["turn-2"]);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["turn-1-tool", "turn-2-tool"]);
expect(entries.map((entry) => entry.turnId)).toEqual([
TurnId.make("turn-1"),
TurnId.make("turn-2"),
]);
});
it("omits checkpoint captured info entries", () => {
@@ -688,7 +814,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
});
@@ -724,7 +850,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["real-work-log"]);
});
@@ -746,7 +872,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["first", "second"]);
});
@@ -767,10 +893,47 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.command).toBe("bun run lint");
});
it("extracts failed tool lifecycle status from item payloads", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "tool-failed",
kind: "tool.updated",
summary: "Glob",
tone: "tool",
payload: {
itemType: "mcp_tool_call",
status: "failed",
detail: "No files found",
},
}),
];
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.toolLifecycleStatus).toBe("failed");
});
it("defaults tool.completed entries to completed lifecycle status", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "tool-done",
kind: "tool.completed",
summary: "Glob",
tone: "tool",
payload: {
itemType: "mcp_tool_call",
detail: "Found 3 files",
},
}),
];
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.toolLifecycleStatus).toBe("completed");
});
it("unwraps PowerShell command wrappers for displayed command text", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
@@ -788,7 +951,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.command).toBe("bun run lint");
expect(entry?.rawCommand).toBe(
"\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
@@ -812,7 +975,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.command).toBe("rg -n foo .");
expect(entry?.rawCommand).toBe(
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."',
@@ -833,7 +996,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.command).toBe('rg -n -F "new Date()" .');
expect(entry?.rawCommand).toBe(
`"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`,
@@ -857,7 +1020,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.command).toBe("bash script.sh");
expect(entry?.rawCommand).toBeUndefined();
});
@@ -886,7 +1049,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry).toMatchObject({
command: "bun run dev",
detail: '{ "dev": "vite dev --port 3000" }',
@@ -915,7 +1078,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.changedFiles).toEqual([
"apps/web/src/components/ChatView.tsx",
"apps/web/src/session-logic.ts",
@@ -936,7 +1099,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry?.toolTitle).toBe("Read File");
expect(entry?.detail).toBeUndefined();
});
@@ -980,7 +1143,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "grep-complete",
@@ -1029,7 +1192,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "read-complete",
@@ -1063,7 +1226,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
const [entry] = deriveWorkLogEntries(activities);
expect(entry).toMatchObject({
id: "cursor-command-complete",
label: "Ran command",
@@ -1105,7 +1268,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
id: "legacy-read-complete",
@@ -1157,7 +1320,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries).toHaveLength(1);
expect(entries[0]).toMatchObject({
@@ -1219,7 +1382,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries.map((entry) => entry.id)).toEqual(["tool-1-complete", "tool-2-complete"]);
});
@@ -1261,7 +1424,7 @@ describe("deriveWorkLogEntries", () => {
}),
];
const entries = deriveWorkLogEntries(activities, undefined);
const entries = deriveWorkLogEntries(activities);
expect(entries).toHaveLength(1);
expect(entries[0]?.id).toBe("a-complete-same-timestamp");
@@ -1311,105 +1474,47 @@ describe("deriveTimelineEntries", () => {
},
});
});
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
const entries = deriveTimelineEntries(
[
{
id: MessageId.make("assistant-earlier"),
role: "assistant",
text: "progress update",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.make("assistant-final"),
role: "assistant",
text: "final answer",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
],
[],
[],
);
expect(
deriveCompletionDividerBeforeEntryId(entries, {
assistantMessageId: MessageId.make("assistant-final"),
startedAt: "2026-02-23T00:00:00.000Z",
completedAt: "2026-02-23T00:00:02.000Z",
}),
).toBe("assistant-final");
});
});
describe("deriveWorkLogEntries context window handling", () => {
it("excludes context window updates from the work log", () => {
const entries = deriveWorkLogEntries(
[
makeActivity({
id: "context-1",
turnId: "turn-1",
kind: "context-window.updated",
summary: "Context window updated",
tone: "info",
}),
makeActivity({
id: "tool-1",
turnId: "turn-1",
kind: "tool.completed",
summary: "Ran command",
tone: "tool",
}),
],
TurnId.make("turn-1"),
);
const entries = deriveWorkLogEntries([
makeActivity({
id: "context-1",
turnId: "turn-1",
kind: "context-window.updated",
summary: "Context window updated",
tone: "info",
}),
makeActivity({
id: "tool-1",
turnId: "turn-1",
kind: "tool.completed",
summary: "Ran command",
tone: "tool",
}),
]);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Ran command");
});
it("keeps context compaction activities as normal work log entries", () => {
const entries = deriveWorkLogEntries(
[
makeActivity({
id: "compaction-1",
turnId: "turn-1",
kind: "context-compaction",
summary: "Context compacted",
tone: "info",
}),
],
TurnId.make("turn-1"),
);
const entries = deriveWorkLogEntries([
makeActivity({
id: "compaction-1",
turnId: "turn-1",
kind: "context-compaction",
summary: "Context compacted",
tone: "info",
}),
]);
expect(entries).toHaveLength(1);
expect(entries[0]?.label).toBe("Context compacted");
});
});
describe("hasToolActivityForTurn", () => {
it("returns false when turn id is missing", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
];
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
expect(hasToolActivityForTurn(activities, null)).toBe(false);
});
it("returns true only for matching tool activity in the target turn", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
];
expect(hasToolActivityForTurn(activities, TurnId.make("turn-1"))).toBe(true);
expect(hasToolActivityForTurn(activities, TurnId.make("turn-2"))).toBe(false);
});
});
describe("isLatestTurnSettled", () => {
const latestTurn = {
turnId: TurnId.make("turn-1"),
+168 -60
View File
@@ -53,9 +53,17 @@ export const PROVIDER_OPTIONS: Array<{
},
];
export type WorkLogToolLifecycleStatus =
| "inProgress"
| "completed"
| "failed"
| "declined"
| "stopped";
export interface WorkLogEntry {
id: string;
createdAt: string;
turnId?: TurnId | null;
label: string;
detail?: string;
command?: string;
@@ -65,6 +73,10 @@ export interface WorkLogEntry {
toolTitle?: string;
itemType?: ToolLifecycleItemType;
requestKind?: PendingApproval["requestKind"];
/** From runtime item / task payload `status` when present (e.g. tool.updated). */
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
/** Originating orchestration activity kind (e.g. `user-input.requested`) for row chrome. */
sourceActivityKind?: OrchestrationThreadActivity["kind"];
}
interface DerivedWorkLogEntry extends WorkLogEntry {
@@ -126,6 +138,129 @@ export type TimelineEntry =
entry: WorkLogEntry;
};
export 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);
}
/** Heuristic: providers often emit successful lifecycle status while error text lives in `detail` / `command`. */
function toolDetailTextLooksLikeFailure(text: string): boolean {
const t = text.toLowerCase();
if (t.includes("file not found")) {
return true;
}
if (t.includes("no files found")) {
return true;
}
if (
t.includes("enoent") ||
t.includes("no such file or directory") ||
t.includes("no such file")
) {
return true;
}
if (t.includes("cannot find path") && t.includes("because it does not exist")) {
return true;
}
if (t.includes("commandnotfoundexception")) {
return true;
}
if (t.includes("is not recognized as the name of a cmdlet")) {
return true;
}
if (t.includes("is not recognized") && t.includes("the term '")) {
return true;
}
if (t.includes("a parameter cannot be found that matches parameter name")) {
return true;
}
if (t.includes("command not found")) {
return true;
}
if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) {
return true;
}
if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) {
return true;
}
if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) {
return true;
}
return false;
}
/** True when the row should show a failure affordance (explicit status/tone or error-shaped tool output). */
export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
if (entry.tone === "error") {
return true;
}
const ls = entry.toolLifecycleStatus;
if (ls === "failed" || ls === "declined") {
return true;
}
if (!workLogEntryIsToolLike(entry)) {
return false;
}
const parts: string[] = [];
if (entry.detail) {
parts.push(entry.detail);
}
if (entry.command) {
parts.push(entry.command);
}
const blob = parts.join("\n");
if (blob.length === 0) {
return false;
}
return toolDetailTextLooksLikeFailure(blob);
}
/** Tool/command row completed without failure (blue check affordance). */
export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
if (!workLogEntryIsToolLike(entry)) {
return false;
}
if (workEntryIndicatesToolFailure(entry)) {
return false;
}
if (entry.tone === "thinking") {
return false;
}
const ls = entry.toolLifecycleStatus;
if (ls === "failed" || ls === "declined") {
return false;
}
if (ls === "inProgress") {
return false;
}
if (ls === "stopped") {
return false;
}
return true;
}
/** Tool-like row with neither clear success nor failure (empty, incomplete, in progress, etc.). */
export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
if (!workLogEntryIsToolLike(entry)) {
return false;
}
if (workEntryIndicatesToolFailure(entry)) {
return false;
}
if (workEntryIndicatesToolSuccess(entry)) {
return false;
}
return true;
}
export function formatDuration(durationMs: number): string {
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
@@ -485,12 +620,10 @@ export function hasActionableProposedPlan(
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
latestTurnId: TurnId | undefined,
): WorkLogEntry[] {
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const entries: DerivedWorkLogEntry[] = [];
for (const activity of ordered) {
if (latestTurnId && activity.turnId !== latestTurnId) continue;
if (activity.kind === "tool.started") continue;
if (activity.kind === "task.started") continue;
if (activity.kind === "context-window.updated") continue;
@@ -498,9 +631,10 @@ export function deriveWorkLogEntries(
if (isPlanBoundaryToolActivity(activity)) continue;
entries.push(toDerivedWorkLogEntry(activity));
}
return collapseDerivedWorkLogEntries(entries).map(
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
);
return collapseDerivedWorkLogEntries(entries).map((entry) => {
const { activityKind, collapseKey: _collapseKey, ...rest } = entry;
return Object.assign(rest, { sourceActivityKind: activityKind });
});
}
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
@@ -515,6 +649,25 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
}
function extractWorkLogToolLifecycleStatus(
payload: Record<string, unknown> | null,
): WorkLogToolLifecycleStatus | undefined {
if (!payload) {
return undefined;
}
const s = payload.status;
if (
s === "inProgress" ||
s === "completed" ||
s === "failed" ||
s === "declined" ||
s === "stopped"
) {
return s;
}
return undefined;
}
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
const payload =
activity.payload && typeof activity.payload === "object"
@@ -548,6 +701,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
const entry: DerivedWorkLogEntry = {
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
label: taskLabel || activity.summary,
tone:
activity.kind === "task.progress"
@@ -583,6 +737,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
if (toolCallId) {
entry.toolCallId = toolCallId;
}
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;
@@ -643,6 +804,7 @@ function mergeDerivedWorkLogEntries(
const requestKind = next.requestKind ?? previous.requestKind;
const collapseKey = next.collapseKey ?? previous.collapseKey;
const toolCallId = next.toolCallId ?? previous.toolCallId;
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
return {
...previous,
...next,
@@ -655,6 +817,7 @@ function mergeDerivedWorkLogEntries(
...(requestKind ? { requestKind } : {}),
...(collapseKey ? { collapseKey } : {}),
...(toolCallId ? { toolCallId } : {}),
...(toolLifecycleStatus !== undefined ? { toolLifecycleStatus } : {}),
};
}
@@ -1160,14 +1323,6 @@ function compareActivityLifecycleRank(kind: string): number {
return 1;
}
export function hasToolActivityForTurn(
activities: ReadonlyArray<OrchestrationThreadActivity>,
turnId: TurnId | null | undefined,
): boolean {
if (!turnId) return false;
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
}
export function deriveTimelineEntries(
messages: ChatMessage[],
proposedPlans: ProposedPlan[],
@@ -1196,53 +1351,6 @@ export function deriveTimelineEntries(
);
}
export function deriveCompletionDividerBeforeEntryId(
timelineEntries: ReadonlyArray<TimelineEntry>,
latestTurn: Pick<
OrchestrationLatestTurn,
"assistantMessageId" | "startedAt" | "completedAt"
> | null,
): string | null {
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
return null;
}
if (latestTurn.assistantMessageId) {
const exactMatch = timelineEntries.find(
(timelineEntry) =>
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
timelineEntry.message.id === latestTurn.assistantMessageId,
);
if (exactMatch) {
return exactMatch.id;
}
}
const turnStartedAt = Date.parse(latestTurn.startedAt);
const turnCompletedAt = Date.parse(latestTurn.completedAt);
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
return null;
}
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
continue;
}
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
continue;
}
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<TurnId, number> {
+34
View File
@@ -44,6 +44,40 @@ export function formatTimestamp(isoDate: string, timestampFormat: TimestampForma
return getTimestampFormatter(timestampFormat, true).format(new Date(isoDate));
}
const monthNameFormatter = new Intl.DateTimeFormat(undefined, { month: "long" });
function ordinalSuffix(day: number): string {
const lastTwo = day % 100;
if (lastTwo >= 11 && lastTwo <= 13) return "th";
switch (day % 10) {
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
/**
* Long-form tooltip label, e.g. `12:04, 4th June`.
* Renders the wall-clock time without seconds followed by the ordinal day and month name.
*/
export function formatChatTimestampTooltip(
isoDate: string,
timestampFormat: TimestampFormat,
): string {
const date = new Date(isoDate);
if (Number.isNaN(date.getTime())) return "";
const time = formatShortTimestamp(isoDate, timestampFormat);
const day = date.getDate();
const month = monthNameFormatter.format(date);
const year = date.getFullYear();
return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
}
export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
}