Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions apps/mobile/src/features/threads/pending-thread-feed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,69 @@ describe("pending timeline messages", () => {
expect(folded.map(({ id }) => id)).toContain("founder-decision");
});

describe("work-toggle failure recovery", () => {
const run = RunId.make("tool-run");
const tool = (id: string, status: "failed" | "completed", extra: object = {}) =>
({
type: "activity-group",
id: `group-${id}`,
createdAt: "2026-09-06T10:00:01.000Z",
runId: run,
activities: [
{
createdAt: "2026-09-06T10:00:01.000Z",
projectedItem: {
item: { id, runId: run, type: "command_execution", status, ...extra },
} as unknown as OrchestrationV2ProjectedTurnItem,
},
],
}) as unknown as ThreadFeedEntry;
const attentionFor = (tools: ReadonlyArray<ThreadFeedEntry>) => {
const input = appendPendingThreadMessages([], [], [pending("agent-input")])[0];
if (input?.type !== "message") throw new Error("Expected message");
const message = {
...input,
message: { ...input.message, runId: run, createdBy: "agent" as const },
};
const toggle = {
type: "work-toggle",
id: "toggle",
createdAt: "2026-09-06T10:00:01.000Z",
runId: run,
hasFailure: true,
} as unknown as ThreadFeedEntry;
const folded = foldThreadFeedActivity([message, toggle], [message, ...tools], {
open: {},
dismissed: new Map(),
revealedMessageId: null,
latestRun: null,
});
const fold = folded.find((row) => row.type === "activity-fold");
if (fold?.type !== "activity-fold") throw new Error("Expected activity fold");
return fold.attention;
};

it("clears a failed toggle once a later call in the run succeeded", () => {
expect(attentionFor([tool("fail", "failed"), tool("ok", "completed")])).toBeNull();
expect(
attentionFor([tool("fail", "completed", { exitCode: 1 }), tool("ok", "completed")]),
).toBeNull();
});

it("keeps a failed toggle when a trailing call fails again", () => {
expect(
attentionFor([tool("fail", "failed"), tool("ok", "completed"), tool("late", "failed")]),
).not.toBeNull();
expect(
attentionFor([
tool("fail", "failed"),
tool("ok", "completed"),
tool("late", "completed", { exitCode: 2 }),
]),
).not.toBeNull();
});
});

it("keeps unchanged row identities while text streams and updates adjacent grouping", () => {
const group = createThreadFeedGrouping();
const [first, second, third] = appendPendingThreadMessages(
Expand Down
13 changes: 11 additions & 2 deletions apps/mobile/src/features/threads/pending-thread-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,21 @@ export function foldThreadFeedActivity(
row.type === "work-toggle" || row.type === "run-fold" ? (row.settledTaskIds ?? []) : [],
);
const attentionIds = new Set(
items.filter(activityItemNeedsAttention).map(({ id }) => String(id)),
items
.filter(
(item) => activityItemNeedsAttention(item) && !context.recoveredItemIds.has(item.id),
)
.map(({ id }) => String(id)),
);
for (const row of group.rows) {
const runId = row.type === "message" ? row.message.runId : "runId" in row ? row.runId : null;
if (runId) for (const id of context.attentionByRun.get(runId) ?? []) attentionIds.add(id);
if (row.type === "work-toggle" && row.hasFailure) attentionIds.add(row.id);
if (
row.type === "work-toggle" &&
row.hasFailure &&
!(row.runId && context.recoveredRuns.has(row.runId))
)
attentionIds.add(row.id);
}
const attention = attentionIds.size > 0 ? JSON.stringify([...attentionIds].sort()) : null;
const expanded =
Expand Down
82 changes: 81 additions & 1 deletion apps/web/src/components/chat/MessagesTimeline.logic.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import type { ChatActivityContext } from "@t3tools/client-runtime/chat-activity";
import {
chatActivityContext,
type ChatActivityContext,
} from "@t3tools/client-runtime/chat-activity";
import { ScheduledTaskId, ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
import {
CheckpointRef,
Expand Down Expand Up @@ -5649,6 +5652,83 @@ describe("collapsing non-human activity", () => {
]);
});

describe("failed tool calls", () => {
const toolEvent = (
id: string,
second: number,
status: "failed" | "completed",
): Extract<MessagesTimelineRow, { kind: "event" }> => ({
kind: "event",
id,
createdAt: time(second),
projectedItem: {
item: { id, runId, type: "command_execution", status, input: "pnpm test" },
} as unknown as OrchestrationV2ProjectedTurnItem,
});
const pillFor = (tools: ReadonlyArray<Extract<MessagesTimelineRow, { kind: "event" }>>) => {
const relay = messageRow("agent-start", 0, { createdBy: "agent" });
if (relay.kind !== "message") throw new Error("Expected a message");
const all = [relay, ...tools];
const context = chatActivityContext(
[
{ createdAt: relay.createdAt, runId, message: relay.message },
...tools.map((tool) => ({
createdAt: tool.createdAt,
runId,
item: tool.projectedItem.item,
})),
],
[],
false,
);
return collapseTimelineActivity(all, new Set(), context)[0];
};

it("does not badge a failure that a later call in the turn recovered", () => {
expect(
pillFor([toolEvent("fail", 1, "failed"), toolEvent("retry", 2, "completed")]),
).toMatchObject({ kind: "activity", attention: false });
});

it("badges a failure that ends the turn", () => {
expect(
pillFor([toolEvent("ok", 1, "completed"), toolEvent("fail", 2, "failed")]),
).toMatchObject({ kind: "activity", attention: true });
});

it("badges only while some failure is still unrecovered", () => {
const recovered = [
toolEvent("fail-1", 1, "failed"),
toolEvent("ok-1", 2, "completed"),
toolEvent("fail-2", 3, "failed"),
toolEvent("ok-2", 4, "completed"),
];
expect(pillFor(recovered)).toMatchObject({ attention: false });
expect(pillFor(recovered.slice(0, 3))).toMatchObject({ attention: true });
});

it("badges a recovered failure when the run itself failed", () => {
const relay = messageRow("agent-start", 0, { createdBy: "agent" });
if (relay.kind !== "message") throw new Error("Expected a message");
const tools = [toolEvent("fail", 1, "failed"), toolEvent("retry", 2, "completed")];
const context = chatActivityContext(
[
{ createdAt: relay.createdAt, runId, message: relay.message },
...tools.map((tool) => ({
createdAt: tool.createdAt,
runId,
item: tool.projectedItem.item,
})),
],
[{ id: runId, status: "failed" }],
false,
);
expect(collapseTimelineActivity([relay, ...tools], new Set(), context)[0]).toMatchObject({
attention: true,
});
});
});

it("reveals a failed bot run and keeps the reply that raises a founder decision visible", () => {
const botRun = RunId.make("bot-decision");
const relay = messageRow("relay", 0, { createdBy: "agent", runId: botRun });
Expand Down
15 changes: 8 additions & 7 deletions apps/web/src/components/chat/MessagesTimeline.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
type OrchestrationV2IdleCompaction,
type WorktreeSetupSnapshot,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2TurnItem,
type RunAttemptId,
type RuntimeRequestId,
RunId,
Expand Down Expand Up @@ -2673,18 +2674,18 @@ export function collapseTimelineActivity(
for (const runId of activityRowRunIds(row)) {
for (const key of context?.attentionByRun.get(runId) ?? []) attentionIds.add(key);
}
const unrecovered = (item: OrchestrationV2TurnItem) =>
activityItemNeedsAttention(item) && !context?.recoveredItemIds.has(item.id);
if (
(row.kind === "work-toggle" && row.hasFailure) ||
(row.kind === "work-toggle" &&
row.hasFailure &&
!(row.runId && context?.recoveredRuns.has(row.runId))) ||
(row.kind === "context-compaction" && row.failed) ||
(row.kind === "event" &&
(row.subagents ?? [row.projectedItem]).some(({ item }) =>
activityItemNeedsAttention(item),
)) ||
(row.subagents ?? [row.projectedItem]).some(({ item }) => unrecovered(item))) ||
((row.kind === "work" || row.kind === "work-live") &&
row.groupedEntries.some((entry) =>
entry.projectedItem
? activityItemNeedsAttention(entry.projectedItem.item)
: entry.tone === "error",
entry.projectedItem ? unrecovered(entry.projectedItem.item) : entry.tone === "error",
))
)
attentionIds.add(row.id);
Expand Down
141 changes: 140 additions & 1 deletion packages/client-runtime/src/chatActivity.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { RunId } from "@t3tools/contracts";
import { RunId, type OrchestrationV2TurnItem } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";

import {
activityItemNeedsAttention,
chatActivityContext,
combineTimelineVisibilityStamps,
isChatActivityMessage,
Expand Down Expand Up @@ -64,3 +65,141 @@ describe("combineTimelineVisibilityStamps", () => {
expect(combineTimelineVisibilityStamps(stamps)).toBe(expected);
});
});

describe("chatActivityContext failed tool calls", () => {
const run = RunId.make("tool-run");
const otherRun = RunId.make("other-run");
const toolItem = (
id: string,
status: "failed" | "completed" | "running",
extra: Record<string, unknown> = {},
runId: RunId = run,
) =>
({
id,
runId,
type: "command_execution",
status,
input: "pnpm test",
...extra,
}) as unknown as OrchestrationV2TurnItem;
const entries = (items: ReadonlyArray<OrchestrationV2TurnItem>) =>
items.map((item, index) => ({
createdAt: `2026-01-01T00:00:0${index}.000Z`,
runId: item.runId,
item,
}));
const attention = (
items: ReadonlyArray<OrchestrationV2TurnItem>,
runs: Parameters<typeof chatActivityContext>[1] = [],
) => chatActivityContext(entries(items), runs, false);

it("clears a failure that the next call in the same run retried successfully", () => {
const ctx = attention([toolItem("fail", "failed"), toolItem("retry", "completed")]);
expect(ctx.attentionByRun.size).toBe(0);
expect([...ctx.recoveredItemIds]).toEqual(["fail"]);
expect(ctx.recoveredRuns.has(run)).toBe(true);
});

it("recovers across tool kinds, since the agent moved on with a clean call", () => {
const ctx = attention([
toolItem("fail", "failed"),
{ ...toolItem("edit", "completed"), type: "file_change" } as OrchestrationV2TurnItem,
]);
expect(ctx.attentionByRun.size).toBe(0);
});

it("keeps a failure that is the last tool call of the run", () => {
const ctx = attention([toolItem("ok", "completed"), toolItem("fail", "failed")]);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual(["fail"]);
expect(ctx.recoveredItemIds.size).toBe(0);
});

it("does not count a call that is still running or finished with a failing result", () => {
for (const later of [
toolItem("later", "running"),
toolItem("later", "completed", { exitCode: 1 }),
toolItem("later", "completed", { outputIndicatesFailure: true }),
toolItem("later", "failed"),
]) {
const ctx = attention([toolItem("fail", "failed"), later]);
expect(ctx.attentionByRun.get(run)?.has("fail")).toBe(true);
}
});

it("does not recover a failure through a success in another run", () => {
const ctx = attention([
toolItem("fail", "failed"),
toolItem("elsewhere", "completed", {}, otherRun),
]);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual(["fail"]);
});

it("clears every failure before a success and keeps the ones after it", () => {
const ctx = attention([
toolItem("fail-1", "failed"),
toolItem("fail-2", "failed"),
toolItem("ok", "completed"),
toolItem("fail-3", "failed"),
]);
expect([...ctx.recoveredItemIds].sort()).toEqual(["fail-1", "fail-2"]);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual(["fail-3"]);
});

it("clears the run's attention only when all of its failures recover", () => {
const all = attention([
toolItem("fail-1", "failed"),
toolItem("ok-1", "completed"),
toolItem("fail-2", "failed"),
toolItem("ok-2", "completed"),
]);
expect(all.attentionByRun.size).toBe(0);
const some = attention([
toolItem("fail-1", "failed"),
toolItem("ok-1", "completed"),
toolItem("fail-2", "failed"),
]);
expect([...(some.attentionByRun.get(run) ?? [])]).toEqual(["fail-2"]);
});

it("still flags a recovered failure when the run itself failed", () => {
const ctx = attention(
[toolItem("fail", "failed"), toolItem("retry", "completed")],
[{ id: run, status: "failed" }],
);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual([run]);
});

it("treats a completed command with a failing exit code as a failure in both directions", () => {
for (const failing of [{ exitCode: 1 }, { outputIndicatesFailure: true }]) {
const recovered = attention([
toolItem("fail", "completed", failing),
toolItem("ok", "completed"),
]);
expect(recovered.attentionByRun.size).toBe(0);
expect([...recovered.recoveredItemIds]).toEqual(["fail"]);
const trailing = attention([
toolItem("fail", "failed"),
toolItem("ok", "completed"),
toolItem("late", "completed", failing),
]);
expect([...(trailing.attentionByRun.get(run) ?? [])]).toEqual(["late"]);
expect(trailing.recoveredRuns.has(run)).toBe(false);
}
});

it("flags an unrecovered exit-code failure on its own", () => {
const ctx = attention([toolItem("fail", "completed", { exitCode: 1 })]);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual(["fail"]);
});

it("never recovers errors, which are not tool calls", () => {
const error = { id: "err", runId: run, type: "error", status: "completed" };
const ctx = attention([
error as unknown as OrchestrationV2TurnItem,
toolItem("retry", "completed"),
]);
expect(activityItemNeedsAttention(error as unknown as OrchestrationV2TurnItem)).toBe(true);
expect([...(ctx.attentionByRun.get(run) ?? [])]).toEqual(["err"]);
});
});
Loading
Loading