fix: fold every settled-turn activity behind "Worked for …"
After a Hermes turn settled, some activity rows rendered below the final assistant message instead of collapsing into the fold above it. An entry can only be hidden if `deriveTurnFolds` can attribute it to a turn: grouping skips entries whose `turnId` resolves null, so an unattributed row can never be folded. Three paths produced them. Ingestion never backfilled the turn. Provider activities take `toTurnId(event.turnId) ?? null` at every call site, and a tool-hook frame that lands after `turn.completed` carries no turn id — its activity was committed permanently orphaned. The obvious fix, reading the thread's `latestTurn`, does not work: `ProjectionPipeline` writes `latestTurnId` from `session.activeTurnId`, which turn completion sets to null, so the value is already gone in exactly the window a late frame arrives in. Ingestion now keeps its own short-lived per-thread memo of the turn a session just left, cleared when a new turn opens and on session exit, and stamps it onto activities that arrive without one. Frames that name a turn keep it, and the turn-conflict gate is untouched. Collapsing a work-log row dropped the turn. `mergeDerivedWorkLogEntries` spreads `next` over `previous`, so a lifecycle frame with a null `turnId` overwrote a good one — `turnId` was missing from the `??`-guarded field list its neighbours already use. The fold trusted attribution completely. It now adopts an unattributed work entry into a settled turn when that turn's span is the only one containing it. A running turn gets an open-ended window, so it blocks an ambiguous adoption without ever claiming one — its entries are supposed to render inline. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
a4000b86da
commit
5bfb90db61
6 files changed
+659
-23
No files matched your search
@@ -3343,6 +3343,137 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("attributes a late turn-less item frame to the turn that just completed", async () => {
|
||||
// Plugin tool hooks run on worker threads, so a post_tool_call →
|
||||
// item.completed frame can land after turn.completed and carry no turn id.
|
||||
// Without a fallback the activity projects with turnId null, which the
|
||||
// timeline can never fold behind the turn's "Worked for …" row.
|
||||
const harness = await createHarness();
|
||||
const turnId = asTurnId("turn-late-frame");
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-late-frame-turn-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
turnId,
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.activeTurnId === "turn-late-frame",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-late-frame-turn-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:10.000Z",
|
||||
turnId,
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
await waitForThread(harness.readModel, (entry) => entry.session?.activeTurnId === null);
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-late-frame-item"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:10.002Z",
|
||||
itemId: asItemId("item-late-frame"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-late-frame-item",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-late-frame-item",
|
||||
);
|
||||
|
||||
expect(activity?.kind).toBe("tool.completed");
|
||||
expect(activity?.turnId).toBe("turn-late-frame");
|
||||
});
|
||||
|
||||
it("leaves an item frame unattributed when no turn has ever run on the thread", async () => {
|
||||
const harness = await createHarness();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-orphan-frame-item"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
itemId: asItemId("item-orphan-frame"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-orphan-frame-item",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-orphan-frame-item",
|
||||
);
|
||||
|
||||
expect(activity?.turnId).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps an explicit turn id on a frame naming a turn other than the active one", async () => {
|
||||
const harness = await createHarness();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-conflict-turn-started"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
turnId: asTurnId("turn-active"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) => entry.session?.activeTurnId === "turn-active",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-conflict-item"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
turnId: asTurnId("turn-other"),
|
||||
itemId: asItemId("item-conflict"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-conflict-item",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-conflict-item",
|
||||
);
|
||||
|
||||
expect(activity?.turnId).toBe("turn-other");
|
||||
});
|
||||
|
||||
it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -114,6 +114,47 @@ function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
|
||||
return value === undefined ? undefined : TurnId.make(String(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* How long after a turn settles a turn-less provider frame is still treated as
|
||||
* belonging to that turn. Plugin tool hooks run on worker threads, so a
|
||||
* `post_tool_call` → `item.completed` frame can land after `turn.completed`;
|
||||
* without attribution such an activity can never be folded behind the turn's
|
||||
* "Worked for …" row and renders below the final answer instead.
|
||||
*/
|
||||
const LATE_ACTIVITY_TURN_ATTRIBUTION_GRACE_MS = 30_000;
|
||||
|
||||
export interface RecentlySettledTurn {
|
||||
readonly turnId: TurnId;
|
||||
readonly settledAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn id to stamp on activities produced by a frame that carries none. The
|
||||
* session's active turn wins; once the turn has closed, the turn that just
|
||||
* settled still claims frames landing inside a short trailing window.
|
||||
*/
|
||||
export function resolveActivityFallbackTurnId(input: {
|
||||
readonly activeTurnId: TurnId | null;
|
||||
readonly recentlySettledTurn: RecentlySettledTurn | null;
|
||||
readonly at: string;
|
||||
}): TurnId | null {
|
||||
if (input.activeTurnId !== null) {
|
||||
return input.activeTurnId;
|
||||
}
|
||||
const settled = input.recentlySettledTurn;
|
||||
if (!settled) {
|
||||
return null;
|
||||
}
|
||||
const atMs = Date.parse(input.at);
|
||||
const settledAtMs = Date.parse(settled.settledAt);
|
||||
if (!Number.isFinite(atMs) || !Number.isFinite(settledAtMs)) {
|
||||
return null;
|
||||
}
|
||||
// Frames stamped before the turn closed always belong to it; frames stamped
|
||||
// after it only within the grace window.
|
||||
return atMs - settledAtMs <= LATE_ACTIVITY_TURN_ATTRIBUTION_GRACE_MS ? settled.turnId : null;
|
||||
}
|
||||
|
||||
function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
|
||||
return value === undefined ? undefined : ApprovalRequestId.make(value);
|
||||
}
|
||||
@@ -784,6 +825,16 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed(""),
|
||||
});
|
||||
|
||||
// The projection nulls the thread's latest turn id the moment the session
|
||||
// stops running, so a frame arriving right after turn.completed can no
|
||||
// longer see the turn it belongs to. Remember the turn that just settled
|
||||
// per thread so late frames can still be attributed to it.
|
||||
const recentlySettledTurnByThreadId = yield* Cache.make<ThreadId, RecentlySettledTurn | null>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
||||
lookup: () => Effect.succeed(null),
|
||||
});
|
||||
|
||||
const rememberTaskDescription = (threadId: ThreadId, taskId: string, description: string) =>
|
||||
Cache.set(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId), description);
|
||||
|
||||
@@ -1266,6 +1317,7 @@ const make = Effect.gen(function* () {
|
||||
key.startsWith(prefix) ? Cache.invalidate(taskDescriptionByTaskKey, key) : Effect.void,
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Cache.invalidate(recentlySettledTurnByThreadId, threadId);
|
||||
});
|
||||
|
||||
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
|
||||
@@ -1372,6 +1424,11 @@ const make = Effect.gen(function* () {
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
||||
|
||||
const getRecentlySettledTurn = () =>
|
||||
Cache.getOption(recentlySettledTurnByThreadId, thread.id).pipe(
|
||||
Effect.map(Option.getOrNull),
|
||||
);
|
||||
|
||||
// A turn.started that conflicts with the active turn is legitimate when
|
||||
// the server itself has a turn start pending for this thread AND the
|
||||
// provider session already tracks the event's turn as its active turn:
|
||||
@@ -1510,6 +1567,19 @@ const make = Effect.gen(function* () {
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
// Record the turn the session is leaving so frames that land after
|
||||
// it (tool-hook completions on provider worker threads) can still be
|
||||
// attributed to it. A new turn opening clears the memo.
|
||||
const settlingTurnId = activeTurnId ?? eventTurnId ?? null;
|
||||
if (nextActiveTurnId !== null) {
|
||||
yield* Cache.set(recentlySettledTurnByThreadId, thread.id, null);
|
||||
} else if (settlingTurnId !== null) {
|
||||
yield* Cache.set(recentlySettledTurnByThreadId, thread.id, {
|
||||
turnId: settlingTurnId,
|
||||
settledAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1875,7 +1945,25 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const activities = runtimeEventToActivities(event, taskTitle);
|
||||
// Frames that carry no turn id (late tool-hook completions, generic
|
||||
// status items emitted around turn boundaries) would otherwise project
|
||||
// an unattributed activity, which the timeline can never fold behind the
|
||||
// turn's "Worked for …" row. Attribute them to the thread's active turn,
|
||||
// or to the turn that just settled. Frames that do name a turn keep it —
|
||||
// the turn-conflict gate above governs lifecycle, not attribution.
|
||||
const fallbackActivityTurnId = resolveActivityFallbackTurnId({
|
||||
activeTurnId,
|
||||
// With a turn start pending, an unattributed frame is at least as
|
||||
// likely to belong to the turn about to open as to the one that just
|
||||
// closed — leave it unattributed rather than folding it into history.
|
||||
recentlySettledTurn: hasPendingTurnStart ? null : yield* getRecentlySettledTurn(),
|
||||
at: now,
|
||||
});
|
||||
const activities = runtimeEventToActivities(event, taskTitle).map((activity) =>
|
||||
activity.turnId === null && fallbackActivityTurnId !== null
|
||||
? { ...activity, turnId: fallbackActivityTurnId }
|
||||
: activity,
|
||||
);
|
||||
yield* Effect.forEach(activities, (activity) =>
|
||||
providerCommandId(event, "thread-activity-append").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
|
||||
@@ -855,6 +855,278 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(rows.map((row) => row.id)).toContain("running-work-entry");
|
||||
});
|
||||
|
||||
it("folds a late unattributed work entry that lands after a settled turn's answer", () => {
|
||||
// Replay of a settled Hermes turn: user message → commentary → work rows →
|
||||
// terminal assistant message, plus a tool-hook frame that landed after
|
||||
// turn.completed and lost its turn attribution. Every work row belongs
|
||||
// above the final answer, behind the fold.
|
||||
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: "check the deploy",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-commentary-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
message: {
|
||||
id: "assistant-commentary" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Looking at it now.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
updatedAt: "2026-01-01T00:00:04Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:06Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:06Z",
|
||||
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:18Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Deploy is green.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:18Z",
|
||||
updatedAt: "2026-01-01T00:00:20Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "late-work-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:21Z",
|
||||
entry: {
|
||||
id: "late-work",
|
||||
createdAt: "2026-01-01T00:00:21Z",
|
||||
turnId: null,
|
||||
label: "Hermes activity is running…",
|
||||
tone: "info" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
const latestTurn = {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed" as const,
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:20Z",
|
||||
};
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"user-entry",
|
||||
"turn-fold:turn-1",
|
||||
"assistant-final-entry",
|
||||
]);
|
||||
|
||||
const terminalIndex = rows.findIndex((row) => row.id === "assistant-final-entry");
|
||||
const trailingWorkRows = rows
|
||||
.slice(terminalIndex + 1)
|
||||
.filter((row) => row.kind === "work" || row.kind === "work-toggle");
|
||||
expect(trailingWorkRows).toEqual([]);
|
||||
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
// Expanding the fold still reveals the adopted entry.
|
||||
expect(expandedRows.map((row) => row.id)).toContain("late-work-entry");
|
||||
});
|
||||
|
||||
it("renders an unattributed work entry outside every settled turn's 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:10Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:12Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "orphan-work-entry",
|
||||
kind: "work",
|
||||
// Far past the settled turn's trailing grace window — this is a
|
||||
// standalone notification-style row, not a late turn frame.
|
||||
createdAt: "2026-01-01T00:10:00Z",
|
||||
entry: {
|
||||
id: "orphan-work",
|
||||
createdAt: "2026-01-01T00:10:00Z",
|
||||
turnId: null,
|
||||
label: "Background sync finished",
|
||||
tone: "info" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:12Z",
|
||||
},
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-final-entry",
|
||||
"orphan-work-entry",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not adopt an unattributed work entry into a still-running turn", () => {
|
||||
// turn-1 has settled; turn-2 is running. An unattributed entry stamped
|
||||
// inside turn-2's span must stay visible — a running turn has no end, so
|
||||
// adopting into it would hide live work behind a fold that isn't there.
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "settled-work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
entry: {
|
||||
id: "settled-work",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Read files",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-final-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user-followup-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
message: {
|
||||
id: "user-followup" as never,
|
||||
role: "user",
|
||||
text: "keep going",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
updatedAt: "2026-01-01T00:01:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "running-work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:01:05Z",
|
||||
entry: {
|
||||
id: "running-work",
|
||||
createdAt: "2026-01-01T00:01:05Z",
|
||||
turnId: "turn-2" as never,
|
||||
label: "Searched files",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "unattributed-work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:01:07Z",
|
||||
entry: {
|
||||
id: "unattributed-work",
|
||||
createdAt: "2026-01-01T00:01:07Z",
|
||||
turnId: null,
|
||||
label: "Hermes activity is running…",
|
||||
tone: "info" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:01:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: true,
|
||||
activeTurnStartedAt: "2026-01-01T00:01:00Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.turnId)).toEqual([
|
||||
"turn-1",
|
||||
]);
|
||||
// Neither of turn-2's rows is hidden: they are grouped for overflow, but
|
||||
// both the running-turn entry and the unattributed entry remain rendered.
|
||||
const workRowEntryIds = rows.flatMap((row) =>
|
||||
row.kind === "work" ? row.groupedEntries.map((entry) => entry.id) : [],
|
||||
);
|
||||
expect(workRowEntryIds).toContain("unattributed-work");
|
||||
expect(rows.some((row) => row.kind === "work-toggle")).toBe(true);
|
||||
});
|
||||
|
||||
it("only shows assistant metadata on the terminal assistant message", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
|
||||
@@ -282,24 +282,31 @@ function deriveUnsettledTurnId(
|
||||
* "Worked for ..." row anchored at the turn's first foldable entry; the
|
||||
* terminal assistant message stays visible below the fold.
|
||||
*/
|
||||
function deriveTurnFolds(input: {
|
||||
interface TurnGroup {
|
||||
entries: Array<TimelineEntry>;
|
||||
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
|
||||
hasStreamingMessage: boolean;
|
||||
/**
|
||||
* The user message that kicked the turn off. Entry timestamps alone
|
||||
* undercount the duration (the first entry appears only once the
|
||||
* provider starts producing output), and a turn cut short by a steer may
|
||||
* hold a single instantaneous commentary message.
|
||||
*/
|
||||
startBoundary: string | null;
|
||||
}
|
||||
|
||||
function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
|
||||
if (entry.kind === "message") {
|
||||
return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
|
||||
}
|
||||
return entry.kind === "work" ? (entry.entry.turnId ?? null) : null;
|
||||
}
|
||||
|
||||
function groupTimelineEntriesByTurn(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;
|
||||
/**
|
||||
* The user message that kicked the turn off. Entry timestamps alone
|
||||
* undercount the duration (the first entry appears only once the
|
||||
* provider starts producing output), and a turn cut short by a steer may
|
||||
* hold a single instantaneous commentary message.
|
||||
*/
|
||||
startBoundary: string | null;
|
||||
}
|
||||
adoptedTurnIdByEntryId: ReadonlyMap<string, TurnId>;
|
||||
}): Map<TurnId, TurnGroup> {
|
||||
const groupsByTurnId = new Map<TurnId, TurnGroup>();
|
||||
|
||||
let pendingUserBoundary: string | null = null;
|
||||
@@ -308,12 +315,7 @@ function deriveTurnFolds(input: {
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
const turnId =
|
||||
entry.kind === "message" && entry.message.role === "assistant"
|
||||
? (entry.message.turnId ?? null)
|
||||
: entry.kind === "work"
|
||||
? (entry.entry.turnId ?? null)
|
||||
: null;
|
||||
const turnId = timelineEntryTurnId(entry) ?? input.adoptedTurnIdByEntryId.get(entry.id) ?? null;
|
||||
if (!turnId) {
|
||||
continue;
|
||||
}
|
||||
@@ -342,6 +344,108 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
}
|
||||
|
||||
return groupsByTurnId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trailing window after a settled turn's last output in which an
|
||||
* unattributed work entry is still read as that turn's own late frame.
|
||||
*/
|
||||
const UNATTRIBUTED_WORK_ADOPTION_GRACE_MS = 10_000;
|
||||
|
||||
function timelineEntryEndTimestamp(entry: TimelineEntry): string {
|
||||
return entry.kind === "message" ? entry.message.updatedAt : entry.createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attribution can fail upstream (a provider frame that lands after its turn
|
||||
* closed carries no turn id), and an unattributed entry can never be hidden by
|
||||
* a fold — it renders below the settled turn's final answer instead. Claim
|
||||
* such an entry for a settled turn when it falls inside exactly that turn's
|
||||
* span and no other turn could own it. A running turn never adopts: its
|
||||
* entries are supposed to render inline, and an entry that could belong to it
|
||||
* is ambiguous rather than foldable.
|
||||
*/
|
||||
function deriveAdoptedTurnIdsForUnattributedWork(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
groupsByTurnId: ReadonlyMap<TurnId, TurnGroup>;
|
||||
unsettledTurnId: TurnId | null;
|
||||
}): ReadonlyMap<string, TurnId> {
|
||||
const adoptedTurnIdByEntryId = new Map<string, TurnId>();
|
||||
const unattributedEntries = input.timelineEntries.filter(
|
||||
(entry) => entry.kind === "work" && timelineEntryTurnId(entry) === null,
|
||||
);
|
||||
if (unattributedEntries.length === 0) {
|
||||
return adoptedTurnIdByEntryId;
|
||||
}
|
||||
|
||||
const windows: Array<{ turnId: TurnId; startMs: number; endMs: number; foldable: boolean }> = [];
|
||||
for (const [turnId, group] of input.groupsByTurnId) {
|
||||
const firstEntry = group.entries[0];
|
||||
if (!firstEntry) {
|
||||
continue;
|
||||
}
|
||||
const startMs = Date.parse(firstEntry.createdAt);
|
||||
if (!Number.isFinite(startMs)) {
|
||||
continue;
|
||||
}
|
||||
const foldable = turnId !== input.unsettledTurnId && !group.hasStreamingMessage;
|
||||
if (!foldable) {
|
||||
// An unsettled turn has no end yet, so everything after it starts is
|
||||
// potentially its own work and must stay unadopted.
|
||||
windows.push({ turnId, startMs, endMs: Number.POSITIVE_INFINITY, foldable });
|
||||
continue;
|
||||
}
|
||||
let endMs = startMs;
|
||||
for (const entry of group.entries) {
|
||||
const entryEndMs = Date.parse(timelineEntryEndTimestamp(entry));
|
||||
if (Number.isFinite(entryEndMs) && entryEndMs > endMs) {
|
||||
endMs = entryEndMs;
|
||||
}
|
||||
}
|
||||
windows.push({ turnId, startMs, endMs: endMs + UNATTRIBUTED_WORK_ADOPTION_GRACE_MS, foldable });
|
||||
}
|
||||
|
||||
for (const entry of unattributedEntries) {
|
||||
const atMs = Date.parse(entry.createdAt);
|
||||
if (!Number.isFinite(atMs)) {
|
||||
continue;
|
||||
}
|
||||
const claimants = windows.filter((window) => atMs >= window.startMs && atMs <= window.endMs);
|
||||
const claimant = claimants[0];
|
||||
if (claimants.length !== 1 || !claimant || !claimant.foldable) {
|
||||
continue;
|
||||
}
|
||||
adoptedTurnIdByEntryId.set(entry.id, claimant.turnId);
|
||||
}
|
||||
|
||||
return adoptedTurnIdByEntryId;
|
||||
}
|
||||
|
||||
function deriveTurnFolds(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
unsettledTurnId: TurnId | null;
|
||||
}): ReadonlyMap<string, TurnFold> {
|
||||
let groupsByTurnId = groupTimelineEntriesByTurn({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds: input.terminalAssistantMessageIds,
|
||||
adoptedTurnIdByEntryId: new Map(),
|
||||
});
|
||||
const adoptedTurnIdByEntryId = deriveAdoptedTurnIdsForUnattributedWork({
|
||||
timelineEntries: input.timelineEntries,
|
||||
groupsByTurnId,
|
||||
unsettledTurnId: input.unsettledTurnId,
|
||||
});
|
||||
if (adoptedTurnIdByEntryId.size > 0) {
|
||||
groupsByTurnId = groupTimelineEntriesByTurn({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds: input.terminalAssistantMessageIds,
|
||||
adoptedTurnIdByEntryId,
|
||||
});
|
||||
}
|
||||
|
||||
const foldsByAnchorEntryId = new Map<string, TurnFold>();
|
||||
for (const [turnId, group] of groupsByTurnId) {
|
||||
if (turnId === input.unsettledTurnId) {
|
||||
|
||||
@@ -1395,6 +1395,43 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the turn attribution when a collapsed lifecycle frame lost its turnId", () => {
|
||||
// A post_tool_call frame can land after turn.completed with no turn id.
|
||||
// Collapsing it into the prior row must not strip the row's turn, or the
|
||||
// row escapes its turn's "Worked for …" fold and renders below the answer.
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "tool-update-attributed",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "tool.updated",
|
||||
summary: "Tool call",
|
||||
turnId: "turn-1",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-complete-unattributed",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool call completed",
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
title: "Tool call",
|
||||
detail: 'Read: {"file_path":"/tmp/app.ts"}',
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.id).toBe("tool-complete-unattributed");
|
||||
expect(entries[0]?.turnId).toBe("turn-1");
|
||||
});
|
||||
|
||||
it("keeps separate tool entries when an identical call starts after the prior one completed", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
|
||||
@@ -818,9 +818,13 @@ function mergeDerivedWorkLogEntries(
|
||||
const toolCallId = next.toolCallId ?? previous.toolCallId;
|
||||
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
|
||||
const toolData = next.toolData ?? previous.toolData;
|
||||
// A lifecycle frame that lost its turn attribution must not strip it from
|
||||
// the collapsed row, or the row escapes its turn's "Worked for …" fold.
|
||||
const turnId = previous.turnId ?? next.turnId;
|
||||
return {
|
||||
...previous,
|
||||
...next,
|
||||
...(turnId ? { turnId } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
|
||||
Reference in new issue
Block a user