TypeScript
refactor(client): share tool outcome rules (#10122)
Theo Browneac11bd29b03e
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex 7286446fb2e..f0ba11a0cca 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -16,6 +16,7 @@ import { formatDuration } from "@t3tools/shared/orchestrationTiming";import {commandDetailRepeatsCommand,extractCommandOutputText,+ extractWorkLogToolLifecycleStatus,isWorktreeSetupActivity,liveActivityToolStatus,normalizeCompactToolLabel,@@ -24,7 +25,11 @@ import {summarizeToolGroup,toolGroupAction,toolGroupSummaryKind,+ workEntryIndicatesToolFailure,+ workEntryIndicatesToolSuccess,+ workLogEntryIsToolLike,type ToolGroupSummaryKind,+ type WorkLogToolLifecycleStatus,} from "@t3tools/client-runtime/work-log/presentation";import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";@@ -88,8 +93,6 @@ export interface ThreadFeedActivity {readonly live?: boolean;}-type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";-export interface WorkLogEntry {id: string;createdAt: string;@@ -989,67 +992,6 @@ function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | unreturn [itemType, normalizedLabel, detail].join("\u001f");}-function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {- if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {- return true;- }- if (entry.command !== undefined && entry.command.trim().length > 0) {- return true;- }- if (entry.requestKind !== undefined) {- return true;- }- return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);-}--function toolDetailTextLooksLikeFailure(text: string): boolean {- const normalized = text.toLowerCase();- return (- normalized.includes("file not found") ||- normalized.includes("no files found") ||- normalized.includes("enoent") ||- normalized.includes("no such file or directory") ||- normalized.includes("no such file") ||- normalized.includes("commandnotfoundexception") ||- normalized.includes("command not found") ||- (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||- (normalized.includes("is not recognized") && normalized.includes("the term '")) ||- normalized.includes("is not recognized as the name of a cmdlet") ||- normalized.includes("a parameter cannot be found that matches parameter name") ||- /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||- /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||- /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)- );-}--function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {- if (entry.tone === "error") {- return true;- }- if (entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "declined") {- return true;- }- if (!workLogEntryIsToolLike(entry)) {- return false;- }- return toolDetailTextLooksLikeFailure([entry.detail, entry.command].filter(Boolean).join("\n"));-}--function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {- if (!workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry)) {- return false;- }- if (entry.tone === "thinking") {- return false;- }- return (- entry.toolLifecycleStatus !== "inProgress" &&- entry.toolLifecycleStatus !== "stopped" &&- entry.toolLifecycleStatus !== "failed" &&- entry.toolLifecycleStatus !== "declined"- );-}-function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] {if (entry.agentSpawn) {switch (entry.toolLifecycleStatus) {@@ -1521,27 +1463,6 @@ function extractToolTitle(payload: Record<string, unknown> | null): string | nulreturn asTrimmedString(payload?.title);}-function extractWorkLogToolLifecycleStatus(- payload: Record<string, unknown> | null,-): WorkLogToolLifecycleStatus | undefined {- const status = payload?.status;- // The parent turn ended, so batch tracking is inactive. The detail explains- // that child status is unavailable; do not retain the earlier running marker.- if (status === "idle" && payload?.taskType === "subagent_batch") return "stopped";- if (status === "pending" || status === "running" || status === "waiting") return "inProgress";- if (status === "cancelled" || status === "interrupted") return "stopped";- if (- status === "inProgress" ||- status === "completed" ||- status === "failed" ||- status === "declined" ||- status === "stopped"- ) {- return status;- }- return undefined;-}-function stripTrailingExitCode(value: string): {output: string | null;exitCode?: number | undefined;diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex dfb0c49be61..f9b888fd1dd 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -23,9 +23,7 @@ import {isLatestTurnSettled,selectHandoffImageResources,selectMessageImageResources,- workEntryIndicatesToolFailure,workEntryIndicatesToolNeutralStatus,- workEntryIndicatesToolSuccess,} from "./session-logic";let nextActivityId = 0;@@ -809,121 +807,43 @@ describe("hasActionableProposedPlan", () => {});});-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);+describe("workEntryIndicatesToolNeutralStatus", () => {+ it("keeps active tools neutral and agent spawns visible", () => {+ const entry = {+ id: "work-1",+ createdAt: "2026-01-01T00:00:00.000Z",+ label: "Read",+ tone: "tool" as const,+ toolLifecycleStatus: "inProgress" as const,+ };+ expect(workEntryIndicatesToolNeutralStatus(entry)).toBe(true);expect(workEntryIndicatesToolNeutralStatus({- ...base,- tone: "tool",- toolLifecycleStatus: "completed",- detail: "ok",+ ...entry,+ agentSpawn: { workflowId: null, agentTaskIds: ["agent-1"] },}),).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",- }),+ workEntryIndicatesToolNeutralStatus({ ...entry, toolLifecycleStatus: "completed" }),).toBe(false);});++ it.each(["waiting", "cancelled", "interrupted"])(+ "keeps the status of a %s background task",+ (status) => {+ const entries = deriveWorkLogEntries([+ makeActivity({+ kind: "task.progress",+ payload: { taskId: "background-1", agentKind: "background", status },+ }),+ ]);+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({+ toolLifecycleStatus: status === "waiting" ? "inProgress" : "stopped",+ });+ expect(workEntryIndicatesToolNeutralStatus(entries[0]!)).toBe(true);+ },+ );});describe("deriveWorkLogEntries", () => {diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex b6a6eb0e634..4e56d742bc6 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -6,7 +6,12 @@ import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentimport {commandDetailRepeatsCommand,extractCommandOutputText,+ extractWorkLogToolLifecycleStatus,isWorktreeSetupActivity,+ workEntryIndicatesToolFailure,+ workEntryIndicatesToolSuccess,+ workLogEntryIsToolLike,+ type WorkLogToolLifecycleStatus,} from "@t3tools/client-runtime/work-log/presentation";import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";import {@@ -37,12 +42,12 @@ import {export { formatDuration } from "@t3tools/shared/orchestrationTiming";-export type WorkLogToolLifecycleStatus =- | "inProgress"- | "completed"- | "failed"- | "declined"- | "stopped";+export {+ workEntryDisplayIndicatesToolFailure,+ workEntryIndicatesToolSuccess,+ workLogEntryIsToolLike,+ type WorkLogToolLifecycleStatus,+} from "@t3tools/client-runtime/work-log/presentation";export interface WorkLogEntry {id: string;@@ -167,103 +172,6 @@ export interface TimelineEntriesProjection {readonly entries: TimelineEntry[];}-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;-}--function workEntryIndicatesToolFailureFromOutput(- entry: WorkLogEntry,- includeCommand: boolean,-): 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 (includeCommand && entry.command) {- parts.push(entry.command);- }- const blob = parts.join("\n");- if (blob.length === 0) {- return false;- }- return toolDetailTextLooksLikeFailure(blob);-}--/** True when a tool failed, including providers that put error output in `command`. */-export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {- return workEntryIndicatesToolFailureFromOutput(entry, true);-}--/** True when the rendered result indicates failure. The command itself is user intent, not output. */-export function workEntryDisplayIndicatesToolFailure(entry: WorkLogEntry): boolean {- return workEntryIndicatesToolFailureFromOutput(entry, false);-}-/** Severe failures keep the red treatment ordinary tool failures lost: runtime* errors and orchestration `*.failed` activities (provider.turn.start.failed,* checkpoint.capture.failed, ...) mean the turn or a core side effect broke,@@ -275,30 +183,6 @@ export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean {);}-/** 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 {// Spawn CTA rows are never neutral-hidden: mid-run they derive from@@ -827,25 +711,6 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolreturn 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 cachedEntry = derivedWorkLogEntryByActivity.get(activity);if (cachedEntry) {diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.tsindex f3febf5e756..e056e92afe5 100644--- a/packages/client-runtime/src/work-log/presentation.test.ts+++ b/packages/client-runtime/src/work-log/presentation.test.ts@@ -12,8 +12,130 @@ import {toolGroupSummaryKind,type WorkLogPresentationEntry,workEntryViewedImagePath,+ workEntryIndicatesToolFailure,+ workEntryDisplayIndicatesToolFailure,+ workEntryIndicatesToolSuccess,} from "./presentation.js";+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("does not treat error text in a command as rendered failure", () => {+ const entry = {+ label: "Ran command",+ tone: "tool",+ toolLifecycleStatus: "completed",+ command: 'rg "file not found"',+ detail: "Found 3 matches",+ } satisfies WorkLogPresentationEntry;++ expect(workEntryDisplayIndicatesToolFailure(entry)).toBe(false);+ // Older activities can store output in this field, so that path stays separate.+ expect(workEntryIndicatesToolFailure(entry)).toBe(true);+ expect(workEntryDisplayIndicatesToolFailure({ ...entry, detail: "File not found" })).toBe(true);+ });++ 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(+ workEntryIndicatesToolSuccess({ ...base, tone: "tool", toolLifecycleStatus: "stopped" }),+ ).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("summarizeToolGroup", () => {it.each(["command", "file-read", "file-change"])("keeps %s approvals out of tool execution counts",diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.tsindex 050bb7145d4..2e1ef3bbf00 100644--- a/packages/client-runtime/src/work-log/presentation.ts+++ b/packages/client-runtime/src/work-log/presentation.ts@@ -1,6 +1,7 @@import {isToolLifecycleItemType,type AssetResource,+ type RuntimeItemStatus,type ThreadId,type ToolActivitySource,type ToolLifecycleItemType,@@ -13,6 +14,8 @@ export function isWorktreeSetupActivity(kind: string): boolean {return kind === "setup-script.requested" || kind === "setup-script.started";}+export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped";+export interface WorkLogPresentationEntry {readonly label: string;readonly toolTitle?: string;@@ -298,13 +301,100 @@ export function commandDetailRepeatsCommand(input: {);}-function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {+export function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): 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);}+/** Maps item and task status to the status shown on a work-log row. */+export function extractWorkLogToolLifecycleStatus(+ payloadValue: unknown,+): WorkLogToolLifecycleStatus | undefined {+ const payload = asRecord(payloadValue);+ switch (payload?.status) {+ case "pending":+ case "running":+ case "waiting":+ return "inProgress";+ case "cancelled":+ case "interrupted":+ return "stopped";+ case "idle":+ // A batch becomes idle when its parent turn ends. Other idle tasks can resume.+ return payload.taskType === "subagent_batch" ? "stopped" : undefined;+ case "inProgress":+ case "completed":+ case "failed":+ case "declined":+ case "stopped":+ return payload.status;+ default:+ return undefined;+ }+}++// Some providers report completion even when the output describes a failure.+function toolDetailTextLooksLikeFailure(text: string): boolean {+ const normalized = text.toLowerCase();+ return (+ normalized.includes("file not found") ||+ normalized.includes("no files found") ||+ normalized.includes("enoent") ||+ normalized.includes("no such file or directory") ||+ normalized.includes("no such file") ||+ normalized.includes("commandnotfoundexception") ||+ normalized.includes("command not found") ||+ (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||+ (normalized.includes("is not recognized") && normalized.includes("the term '")) ||+ normalized.includes("is not recognized as the name of a cmdlet") ||+ normalized.includes("a parameter cannot be found that matches parameter name") ||+ /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||+ /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||+ /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)+ );+}++function workEntryIndicatesToolFailureFromOutput(+ entry: WorkLogPresentationEntry,+ includeCommand: boolean,+): boolean {+ if (+ entry.tone === "error" ||+ entry.toolLifecycleStatus === "failed" ||+ entry.toolLifecycleStatus === "declined"+ ) {+ return true;+ }+ if (!workLogEntryIsToolLike(entry)) return false;+ const output = includeCommand+ ? [entry.detail, entry.command].filter(Boolean).join("\n")+ : (entry.detail ?? "");+ return output.length > 0 && toolDetailTextLooksLikeFailure(output);+}++/** Includes legacy activities that stored error output in the command field. */+export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {+ return workEntryIndicatesToolFailureFromOutput(entry, true);+}++/** Checks rendered output without treating the user's command as an error. */+export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {+ return workEntryIndicatesToolFailureFromOutput(entry, false);+}++/** Decides whether the row can show a success marker. */+export function workEntryIndicatesToolSuccess(entry: WorkLogPresentationEntry): boolean {+ return (+ workLogEntryIsToolLike(entry) &&+ !workEntryIndicatesToolFailure(entry) &&+ entry.tone !== "thinking" &&+ entry.toolLifecycleStatus !== "inProgress" &&+ entry.toolLifecycleStatus !== "stopped"+ );+}+function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {return (entry.itemType === "web_search" &&