diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 51c3d31daae8..71f0793ea60d 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -33,6 +33,7 @@ const clientSettings: ClientSettings = { confirmThreadArchive: true, confirmThreadDelete: false, confirmThreadUnpin: false, + toolCallCards: false, contextWindowMeterEnabled: false, composerCollapseOnScroll: true, dismissedProviderUpdateNotificationKeys: [], diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 9f2e601afa38..f954130dfaa9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8663,6 +8663,87 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("records a failed Bash command's exit code", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const attemptId = RunAttemptId.make("attempt-claude-bash-exit-code"); + const bashToolUseId = "toolu_01BashExitCode"; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId, + text: "Run it.", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_bash_exit_code", + type: "message", + role: "assistant", + content: [ + { type: "tool_use", id: bashToolUseId, name: "Bash", input: { command: "exit 3" } }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000793", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: bashToolUseId, + content: "Error: Exit code 3", + is_error: true, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000794", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000795", result: "Done." }), + ); + yield* harness.awaitTerminal(1); + + const bash = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === bashToolUseId, + ); + assert.equal( + bash?.type === "turn_item.updated" && bash.turnItem.type === "command_execution" + ? bash.turnItem.exitCode + : undefined, + 3, + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + it.effect("answers an approval a held wake turn raises without waiting for the echo", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 295e52bed6fb..c010da6591ba 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2966,6 +2966,14 @@ function claudeCommandOutputText(output: ClaudeNativeToolOutput): string { return claudeNativeToolOutputText(output); } +// Claude reports a failed Bash command only as text that starts "Error: Exit code N". +const CLAUDE_BASH_EXIT_CODE = /^Error: Exit code (\d+)\b/; + +function claudeBashExitCode(outputText: string): { exitCode?: number } { + const match = CLAUDE_BASH_EXIT_CODE.exec(outputText); + return match ? { exitCode: Number(match[1]) } : {}; +} + function claudeSubagentResultText(output: ClaudeNativeToolOutput): string { const value = claudeNativeToolOutputValue(output); const content = Array.isArray(value) @@ -5489,6 +5497,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( type: "command_execution", input: commandInputFromClaudeTool(input.toolName, input.toolInput), ...(outputText.length === 0 ? {} : { output: outputText }), + ...claudeBashExitCode(outputText), } : itemType === "file_change" ? { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 169acd8630d0..c48c3cb4aa3f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -2276,6 +2276,60 @@ describe("deriveMessagesTimelineRows", () => { ]); }); + it("keeps a working run's calls in one card below its text with tool call cards", () => { + const command = (id: string, second: number, status: "completed" | "inProgress") => ({ + id: `${id}-entry`, + kind: "work" as const, + createdAt: `2026-01-01T00:00:0${second}Z`, + entry: { + id, + createdAt: `2026-01-01T00:00:0${second}Z`, + runId: "turn-1" as never, + label: `Ran ${id}`, + command: id, + requestKind: "command" as const, + tone: "tool" as const, + toolLifecycleStatus: status, + }, + }); + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + command("pwd", 5, "completed"), + { + id: "assistant-commentary-entry", + kind: "message", + createdAt: "2026-01-01T00:00:06Z", + message: { + id: "assistant-commentary" as never, + role: "assistant", + text: "Next, a short sleep.", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:06Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: false, + }, + }, + command("sleep", 7, "inProgress"), + ], + latestRun: { + runId: "turn-1" as never, + status: "running", + startedAt: "2026-01-01T00:00:00Z", + completedAt: null, + }, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + turnDiffSummaries: [], + supportsConversationRollback: false, + toolCallCards: true, + }); + + expect(rows.map((row) => row.kind)).toEqual(["working", "message", "work-live"]); + expect( + rows.find((row) => row.kind === "work-live")?.groupedEntries.map((entry) => entry.id), + ).toEqual(["pwd", "sleep"]); + }); + it("does not revive stale in-progress tools before a fresh send has a turn id", () => { const rows = deriveMessagesTimelineRows({ timelineEntries: [ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 0648d1832f07..0c676d146d45 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -563,6 +563,7 @@ type MessagesTimelineRowContent = toolIcon?: WorkLogEntry["toolIcon"]; summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request"; hasFailure: boolean; + groupedEntries: WorkLogEntry[]; } | { kind: "turn-fold"; @@ -1396,6 +1397,8 @@ export function deriveMessagesTimelineRows(input: { availableRevertTurnCounts?: ReadonlySet | undefined; liveAgentTaskIds?: ReadonlySet | undefined; worktreeSetup?: WorktreeSetupSnapshot | null; + /** Beta tool call cards: the working run's calls share one card below its text. */ + toolCallCards?: boolean; }): MessagesTimelineRow[] { const timelineEntries = timelineRowEntries(input.timelineEntries); const turnDiffSummaryByAssistantMessageId = new Map(); @@ -1479,6 +1482,14 @@ export function deriveMessagesTimelineRows(input: { let tailAttemptId: string | null | undefined; for (let index = timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) { const entry = timelineEntries[index]!; + if ( + input.toolCallCards && + entry.kind === "message" && + entry.message.role === "assistant" && + runIdIsActiveResponse(entry.message.runId) + ) { + continue; + } if ( entry.kind !== "work" || entry.entry.tone === "error" || @@ -1516,7 +1527,9 @@ export function deriveMessagesTimelineRows(input: { latestRunningToolEntry !== undefined || (latestVisibleToolEntry !== undefined && workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry)); + // A card keeps showing its failed call; the old rows swap it for a thinking row. const latestToolFailed = + input.toolCallCards !== true && latestRunningToolEntry === undefined && latestVisibleToolEntry !== undefined && latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" && @@ -1660,7 +1673,7 @@ export function deriveMessagesTimelineRows(input: { appendWorkingRow(); } - if (timelineEntry.id === activeWorkPlacementEntryId) { + if (timelineEntry.id === activeWorkPlacementEntryId && !input.toolCallCards) { appendActiveWorkRows(); } @@ -1892,6 +1905,7 @@ export function deriveMessagesTimelineRows(input: { hasFailure: latestToolEntry !== undefined && workEntryDisplayIndicatesToolFailure(latestToolEntry), + groupedEntries: visibleGroupedEntries, }); if (expanded) { nextRows.push( @@ -2022,6 +2036,8 @@ export function deriveMessagesTimelineRows(input: { : undefined, }); } + // Only the run's own text can follow its calls, so the end is the bottom of the run. + if (input.toolCallCards) appendActiveWorkRows(); const setupHandedOff = input.worktreeSetup !== null && @@ -2444,7 +2460,8 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.summaryKind === bw.summaryKind && a.toolSurface === bw.toolSurface && Equal.equals(a.toolIcon, bw.toolIcon) && - a.hasFailure === bw.hasFailure + a.hasFailure === bw.hasFailure && + Equal.equals(a.groupedEntries, bw.groupedEntries) ); } diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 07bc698e02ce..678f22ccd1a5 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -20,6 +20,7 @@ import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/s import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { useClientSettings } from "~/hooks/useSettings"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {}; @@ -657,6 +658,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId) : paintedExpandedAttemptIds; + const toolCallCards = useClientSettings((settings) => settings.toolCallCards); const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, { timelineEntries, latestRun, @@ -672,6 +674,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ threadStartCheckpointReady, availableRevertTurnCounts, worktreeSetup, + toolCallCards, }); const rows = useStableRows(rawRows, listIdentityKey); // Run status/timestamps change per stream event; keep them out of shared row context. @@ -1309,7 +1312,11 @@ const ConversationTimeline = memo(function ConversationTimeline({ fullscreenAppRowId !== null || disclosureToggleSettling ? false - : isWorking && !prefersReducedMotion && settlingListIdentity === null + : // Text lands above a live tool card, so an eased follow drops the card, then lifts it. + isWorking && + !prefersReducedMotion && + !toolCallCards && + settlingListIdentity === null ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH : TIMELINE_MAINTAIN_SCROLL_AT_END } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 76daf03c1067..d037f6e84850 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -24,6 +24,7 @@ import { import { claudeSkillInvocation } from "@t3tools/shared/toolActivity"; import { memo, use, useState, type KeyboardEvent } from "react"; import { + formatDuration, workEntryDisplayIndicatesToolFailure, workEntrySignalsSevereFailure, workLogEntryIsToolLike, @@ -45,6 +46,14 @@ import { import { cn } from "~/lib/utils"; import { formatUpcomingTimestamp } from "../../timestampFormat"; import { FetchedToolOutput, V2ItemInspector } from "./V2ItemInspector"; +import { ToolCallMeta, useToolCallState } from "./ToolCallMeta"; +import { + toolCallDurationMs, + toolCallResultNote, + withoutLeadingCd, + withoutWorkspaceRoot, +} from "./ToolCallCard.logic"; +import { useClientSettings } from "../../hooks/useSettings"; import { SubagentNotificationLink } from "./V2LifecycleRow"; import { TimelineRowCtx, @@ -183,6 +192,9 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { ? notificationChildThreadId(workEntry.projectedItem.item.source) : undefined; const groupView = use(WorkGroupViewCtx); + const toolCallCards = useClientSettings((settings) => settings.toolCallCards); + const callState = useToolCallState(workEntry); + const cardState = toolCallCards ? callState : "none"; const [expanded, setExpanded] = useState( () => groupView?.state.expandedEntries.has(workEntry.id) ?? false, ); @@ -280,7 +292,13 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { ? workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought" - : questionHeading || (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot)); + : questionHeading || + (toolCallCards && workEntry.command + ? withoutWorkspaceRoot( + withoutLeadingCd(displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot)), + workspaceRoot, + ) + : (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot))); const answerPreview = workEntry.questionAnswer && hasQuestionAnswer(workEntry.questionAnswer) ? getQuestionAnswerPreview(workEntry.questionAnswer) @@ -348,7 +366,9 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { : showDestructiveRowStyle ? "text-destructive" : showFailedIndicator - ? failedToolIconClassName + ? cardState === "failed" + ? "text-icon-muted" + : failedToolIconClassName : workEntry.tone === "tool" ? "text-icon-muted" : iconConfig.className, @@ -357,16 +377,33 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { ? "font-medium text-warning" : showDestructiveRowStyle ? "font-medium text-destructive" - : workLogEntryIsToolLike(workEntry) - ? "text-secondary-label" - : "text-foreground/80"; + : cardState !== "none" + ? "text-foreground/90" + : toolCallCards && isReasoning + ? "text-muted-foreground" + : workLogEntryIsToolLike(workEntry) + ? "text-secondary-label" + : "text-foreground/80"; const threadLabel = isReasoning ? null : threadReadLabel(previewText, threadTarget); const accessiblePreview = [threadLabel?.text ?? previewText, answerPreview] .filter(Boolean) .join(": "); + const callDurationMs = cardState === "done" ? toolCallDurationMs(workEntry) : null; + const failedNote = cardState === "failed" ? toolCallResultNote(workEntry) : null; + const failedDurationMs = cardState === "failed" ? toolCallDurationMs(workEntry) : null; const accessibleDisplayText = showFailedIndicator - ? `${accessiblePreview}, tool call failed` - : accessiblePreview; + ? [ + `${accessiblePreview}, tool call failed`, + failedNote, + failedDurationMs !== null ? formatDuration(failedDurationMs) : null, + ] + .filter(Boolean) + .join(", ") + : cardState === "running" || cardState === "stopped" + ? `${accessiblePreview}, ${cardState}` + : cardState === "done" + ? `${accessiblePreview}, completed${callDurationMs !== null ? ` in ${formatDuration(callDurationMs)}` : ""}` + : accessiblePreview; const rowToggleProps = canExpandProjectedItem ? { role: "button" as const, @@ -387,12 +424,13 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { -

+

@@ -476,12 +520,21 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { Open subagent ) : null} - {showFailedIndicator && - !showDestructiveRowStyle && - !toolIconAcceptsTint(entryToolIcon) ? ( - - ) : null} - + {toolCallCards ? ( + + ) : ( + <> + {showFailedIndicator && + !showDestructiveRowStyle && + !toolIconAcceptsTint(entryToolIcon) ? ( + + ) : null} + + + )} diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 27bdf77a871b..af3e4ef12676 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -57,6 +57,8 @@ import { workEntryIconName, } from "./TimelineWorkEntryRow.logic"; import { formatWorkingTimerNow } from "./TimelineWorkGroupRows.logic"; +import { useClientSettings } from "../../hooks/useSettings"; +import { LiveToolCard, ToolCardBody, ToolGroupLine, groupHasTools } from "./ToolCallCard"; export const WorkGroupSection = memo(function WorkGroupSection({ anchorKey, @@ -72,6 +74,7 @@ export const WorkGroupSection = memo(function WorkGroupSection({ displayLabel?: string | undefined; }) { const { workspaceRoot, routeThreadKey, onToggleWorkEntry } = use(TimelineRowCtx); + const toolCallCards = useClientSettings((settings) => settings.toolCallCards); const onToggleStandaloneEntry = (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed); const nonEmptyEntries = groupedEntries.filter((entry) => @@ -83,15 +86,18 @@ export const WorkGroupSection = memo(function WorkGroupSection({ return ; } if (isExpandedToolGroup) { - return ( + const inCard = toolCallCards && groupHasTools(nonEmptyEntries); + const entries = ( ); + return inCard ? {entries} : entries; } return ( @@ -118,19 +124,22 @@ function WorkingTimer({ createdAt }: { createdAt: string }) { ); } -const compactWorkEntryHeight = 24; +const compactWorkEntryHeight = { grouped: 24, card: 28 } as const; function ExpandedWorkGroupEntries({ anchorKey, disclosureAnchorKey, entries, workspaceRoot, + density, }: { anchorKey: string; disclosureAnchorKey: string; entries: TimelineWorkEntry[]; workspaceRoot: string | undefined; + density: "grouped" | "card"; }) { + const rowHeight = compactWorkEntryHeight[density]; const { workGroupViewState: viewState, onToggleWorkEntry } = use(TimelineRowCtx); const [initialScrollIndex] = useState(() => resolveWorkGroupScrollIndex(entries, viewState.scrollPositions.get(anchorKey)), @@ -218,10 +227,7 @@ function ExpandedWorkGroupEntries({ let height = 0; for (const entryId of viewState.expandedEntries) { if (state?.indexByKey(entryId) === undefined) continue; - height += Math.max( - 0, - (state.sizes.get(entryId) ?? compactWorkEntryHeight) - compactWorkEntryHeight, - ); + height += Math.max(0, (state.sizes.get(entryId) ?? rowHeight) - rowHeight); } setExpandedContentHeight(height); }; @@ -231,14 +237,14 @@ function ExpandedWorkGroupEntries({ return ( - + @@ -478,6 +486,43 @@ export function LiveWorkEntryTimelineRow({ }: { row: Extract; }) { + const toolCallCards = useClientSettings((settings) => settings.toolCallCards); + // Thoughts show as rows inside the card, so its height never changes as they come and go. + if (!toolCallCards || !groupHasTools(row.groupedEntries)) return ; + return ; +} + +function LiveThoughtLine({ text }: { text: string }) { + const ctx = use(TimelineRowCtx); + return ( + + + + } + label={ + + + + } + wrapLabel + /> + ); +} + +function LiveWorkEntryLine({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); const threadTarget = useThreadReadTarget(row.entry, ctx.activeThreadEnvironmentId); const questionHeading = row.entry.questionAnswer @@ -505,32 +550,7 @@ export function LiveWorkEntryTimelineRow({ aria-expanded={row.expanded} onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)} > - {thoughtLine ? ( - - - - } - label={ - - - - } - wrapLabel - /> - ) : null} + {thoughtLine ? : null} ; }) { const ctx = use(TimelineRowCtx); + const toolCallCards = useClientSettings((settings) => settings.toolCallCards); + if (toolCallCards && groupHasTools(row.groupedEntries)) return ; return ( DateTime.makeUnsafe(new Date(Date.UTC(2026, 9, 27, 12, 0, 0, ms))); + +function commandEntry(id: string, startMs: number, endMs: number, exitCode = 0): WorkLogEntry { + return { + id, + createdAt: at(startMs).toString(), + label: "Ran command", + tone: "tool", + command: `cat ${id}`, + itemType: "command_execution", + toolLifecycleStatus: "completed", + structuredPayload: { + id: TurnItemId.make(id), + threadId: ThreadId.make("thread"), + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: at(startMs), + completedAt: at(endMs), + updatedAt: at(endMs), + type: "command_execution", + input: `cat ${id}`, + exitCode, + }, + }; +} + +describe("toolGroupStats", () => { + it("spans from the first start to the last end and counts failures", () => { + const stats = toolGroupStats([ + commandEntry("a", 0, 400), + commandEntry("b", 900, 3_000, 1), + { + id: "thought", + createdAt: at(0).toString(), + label: "Thought", + tone: "thinking", + itemType: "reasoning", + }, + ]); + expect(stats).toEqual({ toolCount: 2, failedCount: 1, durationMs: 3_000 }); + }); +}); + +describe("withoutLeadingCd", () => { + it("drops a leading cd so the row names the command that did the work", () => { + expect(withoutLeadingCd("cd /repo/worktree; gh pr view 1")).toBe("gh pr view 1"); + expect(withoutLeadingCd('cd "/my repo" && vp test run')).toBe("vp test run"); + }); + + it("keeps a bare cd and commands that do not start with cd", () => { + expect(withoutLeadingCd("cd /repo")).toBe("cd /repo"); + expect(withoutLeadingCd("ls; cd /repo; ls")).toBe("ls; cd /repo; ls"); + }); +}); + +describe("withoutWorkspaceRoot", () => { + it("shows workspace paths as relative and leaves other paths alone", () => { + expect(withoutWorkspaceRoot("cat /repo/src/a.ts /etc/hosts", "/repo/")).toBe( + "cat src/a.ts /etc/hosts", + ); + expect(withoutWorkspaceRoot("cat /repository/a.ts", "/repo")).toBe("cat /repository/a.ts"); + expect(withoutWorkspaceRoot('grep -rn "tool" /repo --exclude-dir=.git', "/repo")).toBe( + 'grep -rn "tool" . --exclude-dir=.git', + ); + }); +}); + +describe("toolCallState", () => { + it("marks an unfinished call outside the working run as stopped, not done", () => { + const entry = { ...commandEntry("a", 0, 400), toolLifecycleStatus: "inProgress" as const }; + expect(toolCallState(entry, true)).toBe("running"); + expect(toolCallState(entry, false)).toBe("stopped"); + }); +}); diff --git a/apps/web/src/components/chat/ToolCallCard.logic.ts b/apps/web/src/components/chat/ToolCallCard.logic.ts new file mode 100644 index 000000000000..842a10019826 --- /dev/null +++ b/apps/web/src/components/chat/ToolCallCard.logic.ts @@ -0,0 +1,99 @@ +import { workLogEntryIsToolLike, workEntryDisplayIndicatesToolFailure } from "../../session-logic"; +import type { WorkLogEntry } from "../../session-logic"; +import * as DateTime from "effect/DateTime"; + +export type ToolCallState = "running" | "done" | "failed" | "stopped" | "none"; + +function entryItem(entry: WorkLogEntry) { + return entry.projectedItem?.item ?? entry.structuredPayload; +} + +function epochMillis(value: DateTime.Utc | null | undefined) { + return value ? DateTime.toEpochMillis(value) : null; +} + +/** Wall time of one finished call, or null while it runs or when the provider sent no times. */ +export function toolCallDurationMs(entry: WorkLogEntry): number | null { + const item = entryItem(entry); + const start = epochMillis(item?.startedAt); + const end = epochMillis(item?.completedAt); + return start !== null && end !== null ? Math.max(0, end - start) : null; +} + +/** When a call started, for the running timer. Falls back to when the row was created. */ +export function toolCallStartedAt(entry: WorkLogEntry): string { + const startedAt = entryItem(entry)?.startedAt; + return startedAt ? DateTime.formatIso(startedAt) : entry.createdAt; +} + +/** `live` is true only for entries in the run that is still working. */ +export function toolCallState(entry: WorkLogEntry, live: boolean): ToolCallState { + if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") return "none"; + if (workEntryDisplayIndicatesToolFailure(entry)) return "failed"; + // An unfinished call outside the working run was interrupted; it must not read as done. + if (entry.toolLifecycleStatus === "inProgress" || entry.toolLifecycleStatus === "stopped") { + return live && entry.toolLifecycleStatus === "inProgress" ? "running" : "stopped"; + } + return "done"; +} + +/** Short result note for the row, such as a failed command's exit code. */ +export function toolCallResultNote(entry: WorkLogEntry): string | null { + const item = entryItem(entry); + if (item?.type === "command_execution" && item.exitCode !== undefined && item.exitCode !== 0) { + return `exit ${item.exitCode}`; + } + return null; +} + +export interface ToolGroupStats { + toolCount: number; + failedCount: number; + /** From the first call's start to the last call's end. */ + durationMs: number | null; +} + +export function toolGroupStats(entries: ReadonlyArray): ToolGroupStats { + let toolCount = 0; + let failedCount = 0; + let start = Infinity; + let end = -Infinity; + for (const entry of entries) { + if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") continue; + toolCount += 1; + if (workEntryDisplayIndicatesToolFailure(entry)) failedCount += 1; + const item = entryItem(entry); + const itemStart = epochMillis(item?.startedAt); + const itemEnd = epochMillis(item?.completedAt); + if (itemStart !== null) start = Math.min(start, itemStart); + if (itemEnd !== null) end = Math.max(end, itemEnd); + } + return { + toolCount, + failedCount, + durationMs: Number.isFinite(start) && Number.isFinite(end) && end >= start ? end - start : null, + }; +} + +/** Newest entries for the live card's tail, oldest first. */ +export function liveToolCardTail(entries: ReadonlyArray, limit: number): ReadonlyArray { + return entries.length > limit ? entries.slice(-limit) : entries; +} + +const LEADING_CD = /^\s*cd\s+(?:"[^"]*"|'[^']*'|[^\s;&|]+)\s*(?:&&|;)\s*/; + +/** Drops a leading `cd

&&` or `cd ;` so the row shows the command that did the work. */ +export function withoutLeadingCd(command: string): string { + const rest = command.replace(LEADING_CD, ""); + return rest.trim().length > 0 ? rest : command; +} + +/** Shows paths inside the workspace as relative, so a row shows what the command touched. */ +export function withoutWorkspaceRoot(command: string, workspaceRoot: string | undefined): string { + const root = workspaceRoot?.replace(/\/+$/, ""); + if (!root) return command; + const escaped = root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return command + .replaceAll(`${root}/`, "") + .replace(new RegExp(`${escaped}(?=$|[\\s'";&|)])`, "g"), "."); +} diff --git a/apps/web/src/components/chat/ToolCallCard.tsx b/apps/web/src/components/chat/ToolCallCard.tsx new file mode 100644 index 000000000000..18511db12802 --- /dev/null +++ b/apps/web/src/components/chat/ToolCallCard.tsx @@ -0,0 +1,230 @@ +import { ChevronDownIcon } from "lucide-react"; +import { use, type ReactNode } from "react"; +import { formatDuration, type WorkLogEntry } from "../../session-logic"; +import { cn } from "~/lib/utils"; +import { WorkLogList } from "./WorkLog"; +import { TimelineRowCtx, type TimelineRow, type TimelineWorkEntry } from "./timelineRowContext"; +import { ToolActivityIconView } from "./TimelineToolActivityIcon"; +import { workEntryIconName } from "./TimelineWorkEntryRow.logic"; +import { SimpleWorkEntryRow } from "./TimelineWorkEntryRow"; +import { liveToolCardTail, toolGroupStats } from "./ToolCallCard.logic"; +import { TimelineRowTimestamp } from "./TimelineRowParts"; + +const LIVE_TAIL_ROWS = 4; +const STACK_LIMIT = 4; + +const cardFrame = "border-border bg-foreground/[0.025]"; +const toolCardClassName = { + whole: cn(cardFrame, "mt-1.5 rounded-xl border"), + top: cn(cardFrame, "mt-1.5 rounded-t-xl border border-b-0"), + bottom: cn(cardFrame, "mb-2 rounded-b-xl border border-t-0"), +}; + +function entryIconKey(entry: TimelineWorkEntry) { + const icon = entry.toolIcon ?? entry.toolSource?.icon; + if (!icon) return workEntryIconName(entry); + return icon._tag === "website" + ? `website:${icon.pageUrl}` + : icon._tag === "themed-logo" + ? `logo:${icon.logoUrl}` + : `app:${JSON.stringify(icon.app)}`; +} + +/** Overlapping icons for the distinct tools in a group, first use first. */ +function ToolStack({ entries }: { entries: ReadonlyArray }) { + const seen = new Map(); + for (const entry of entries) { + if (entry.itemType === "reasoning") continue; + const key = entryIconKey(entry); + if (!seen.has(key)) seen.set(key, entry); + if (seen.size === STACK_LIMIT) break; + } + return ( + + {[...seen].map(([key, entry]) => ( + + + + ))} + + ); +} + +function Chevron({ open }: { open: boolean }) { + return ( + + ); +} + +function CardHeader(props: { + entries: ReadonlyArray; + label: ReactNode; + accessibleLabel: string; + failedCount: number; + trailing?: ReactNode; + expanded: boolean; + className: string; + /** Absent for a card with nothing more to open; it keeps the chevron's space. */ + onToggle?: () => void; +}) { + const Root = props.onToggle ? "button" : "div"; + return ( + + + {props.label} + {props.failedCount > 0 ? ( + + {props.failedCount} failed + + ) : null} + + {props.trailing} + {/* Lines the header time up with the row durations, left of the status column. */} + + {props.onToggle ? ( + + ) : ( + + )} + + + ); +} + +/** The newest calls and thoughts. Rows only append, so the card grows to 4 rows and stops. */ +function ToolCardTail({ entries }: { entries: ReadonlyArray }) { + const { workspaceRoot } = use(TimelineRowCtx); + return ( +
+ + {entries.map((entry) => ( + + ))} + +
+ ); +} + +function toolNoun(count: number) { + return count === 1 ? "tool" : "tools"; +} + +/** The working run's calls in one card, so progress is visible without a click. */ +export function LiveToolCard({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const stats = toolGroupStats(row.groupedEntries); + const tail = liveToolCardTail(row.groupedEntries, LIVE_TAIL_ROWS); + const hiddenCount = row.expanded + ? 0 + : stats.toolCount - tail.filter((entry) => entry.itemType !== "reasoning").length; + const label = `Using ${stats.toolCount} ${toolNoun(stats.toolCount)}`; + return ( +
+ 0 ? `${stats.failedCount} failed` : null, + hiddenCount > 0 + ? `${hiddenCount} earlier ${hiddenCount === 1 ? "call" : "calls"} hidden` + : null, + ] + .filter(Boolean) + .join(", ")} + failedCount={stats.failedCount} + trailing={hiddenCount > 0 ? `+${hiddenCount} earlier` : null} + expanded={row.expanded} + className="rounded-t-xl" + onToggle={() => ctx.onToggleWorkGroup(row.groupId, row.id)} + /> + {row.expanded ? null : } +
+ ); +} + +/** Finished tools: one quiet line that opens into the card. */ +export function ToolGroupLine({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const stats = toolGroupStats(row.groupedEntries); + const duration = stats.durationMs !== null ? formatDuration(stats.durationMs) : null; + return ( +
+ + {row.summary} + + Used {stats.toolCount} {toolNoun(stats.toolCount)} + + + } + accessibleLabel={[ + row.summary, + stats.failedCount > 0 ? `${stats.failedCount} failed` : null, + duration, + ] + .filter(Boolean) + .join(", ")} + failedCount={stats.failedCount} + trailing={ + <> + + {duration} + + } + expanded={row.expanded} + className={row.expanded ? "rounded-t-xl" : "rounded-md"} + onToggle={() => ctx.onToggleWorkGroup(row.groupId, row.id)} + /> +
+ ); +} + +/** Bottom of an open card: the full list of calls. */ +export function ToolCardBody({ children }: { children: ReactNode }) { + return ( +
+
{children}
+
+ ); +} + +export function groupHasTools(entries: ReadonlyArray) { + return toolGroupStats(entries).toolCount > 0; +} diff --git a/apps/web/src/components/chat/ToolCallMeta.tsx b/apps/web/src/components/chat/ToolCallMeta.tsx new file mode 100644 index 000000000000..167cbcc7fb8e --- /dev/null +++ b/apps/web/src/components/chat/ToolCallMeta.tsx @@ -0,0 +1,71 @@ +import { CheckIcon, CircleDashedIcon, MinusIcon, XIcon } from "lucide-react"; +import { use } from "react"; +import { formatDuration, type WorkLogEntry } from "../../session-logic"; +import { cn } from "~/lib/utils"; +import { tickTextContent } from "~/lib/tickTextContent"; +import { TimelineRowActivityCtx, TimelineRowCtx } from "./timelineRowContext"; +import { TimelineRowTimestamp } from "./TimelineRowParts"; +import { formatWorkingTimerNow } from "./TimelineWorkGroupRows.logic"; +import { + toolCallDurationMs, + toolCallResultNote, + toolCallStartedAt, + toolCallState, + type ToolCallState, +} from "./ToolCallCard.logic"; + +/** A call's state in the timeline; only calls in the run that is working now can be running. */ +export function useToolCallState(entry: WorkLogEntry): ToolCallState { + const { isWorking, latestRunId } = use(TimelineRowActivityCtx); + return toolCallState(entry, isWorking && entry.runId != null && entry.runId === latestRunId); +} + +function StatusGlyph({ state }: { state: ToolCallState }) { + if (state === "done") { + return ( + + ); + } + if (state === "failed") { + return ; + } + if (state === "stopped") { + return ; + } + return ; +} + +/** Trailing result note, duration, and status for one call. Running calls tick their elapsed time. */ +export function ToolCallMeta({ entry, state }: { entry: WorkLogEntry; state: ToolCallState }) { + const { timestampFormat } = use(TimelineRowCtx); + if (state === "none") { + return ; + } + const durationMs = state === "done" || state === "failed" ? toolCallDurationMs(entry) : null; + const note = state === "failed" ? toolCallResultNote(entry) : null; + const startedAt = toolCallStartedAt(entry); + return ( + + + {note ? {note} : null} + {state === "running" ? ( + formatWorkingTimerNow(startedAt), true)} + className="text-foreground/80" + /> + ) : durationMs !== null ? ( + {formatDuration(durationMs)} + ) : null} + + {state === "done" ? "completed" : state} + + ); +} diff --git a/apps/web/src/components/chat/WorkLog.tsx b/apps/web/src/components/chat/WorkLog.tsx index 006e08f04f66..12e5ccf98a83 100644 --- a/apps/web/src/components/chat/WorkLog.tsx +++ b/apps/web/src/components/chat/WorkLog.tsx @@ -8,7 +8,8 @@ import { } from "react"; import { cn } from "../../lib/utils"; -const GroupedRows = createContext(false); +/** Rows in a list sit flush; rows in a tool card get room to scan. */ +const GroupedRows = createContext<"standalone" | "grouped" | "card">("standalone"); /** Groups may span virtualized timeline items. Each part owns its trailing space. */ export function WorkLogBlock({ @@ -35,9 +36,15 @@ export function WorkLogBlock({ ); } -export function WorkLogList({ children }: { children: ReactNode }) { +export function WorkLogList({ + density = "grouped", + children, +}: { + density?: "grouped" | "card"; + children: ReactNode; +}) { return ( - +
{children}
); @@ -84,10 +91,11 @@ const interactionClassName = "cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"; function useRowClassName(interactive: boolean) { - const grouped = use(GroupedRows); + const density = use(GroupedRows); return cn( - "group/timeline-row relative w-full min-w-0 rounded-md px-0.5 text-left transition-colors", - grouped ? "py-0" : "py-0.5", + "group/timeline-row relative w-full min-w-0 rounded-md px-0.5 text-left transition-colors data-running:bg-foreground/[0.05]", + density === "grouped" ? "py-0" : "py-0.5", + density === "card" && "px-2 hover:bg-foreground/[0.03]", interactive && interactionClassName, ); } diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index b06f7b04c4fb..1081575f8743 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -4,6 +4,7 @@ import { Link } from "@tanstack/react-router"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { Button } from "../ui/button"; +import { Switch } from "../ui/switch"; import { ScopedSwitch } from "./ScopedSwitch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -18,6 +19,7 @@ export function LabsSettingsPanel() { {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } + @@ -104,3 +106,21 @@ function LinkedEnvironmentsRow() { /> ); } + +function ToolCallCardsRow() { + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + return ( + updateSettings({ toolCallCards: Boolean(checked) })} + aria-label="Tool call cards" + /> + } + /> + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 9e51c1fe67cf..17e205e93ca1 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -418,6 +418,12 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment", searchTerms: ["beta share guest invite link teammate watch t3 connect tunnel"], }, + { + id: "tool-call-cards", + title: "Tool call cards", + to: "/settings/labs", + searchTerms: ["beta tool calls card status duration work log activity"], + }, { id: "linked-environments-beta", title: "Linked environments", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 87f6c43439ff..79e983817ae7 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -382,6 +382,8 @@ export const ClientSettingsSchema = Schema.Struct({ confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** Beta: tool calls render as a live card that settles to one summary line. */ + toolCallCards: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe( Schema.withDecodingDefault(Effect.succeed([])), ), @@ -1643,6 +1645,7 @@ export const ClientSettingsPatch = Schema.Struct({ confirmThreadArchive: Schema.optionalKey(Schema.Boolean), confirmThreadDelete: Schema.optionalKey(Schema.Boolean), confirmThreadUnpin: Schema.optionalKey(Schema.Boolean), + toolCallCards: Schema.optionalKey(Schema.Boolean), diffFilesCollapsed: Schema.optionalKey(Schema.Boolean), diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean), diffLayout: Schema.optionalKey(DiffLayout),