From fe568271241e39dee179b7be3aa0054b55f240d7 Mon Sep 17 00:00:00 2001 From: Akash Date: Thu, 19 Nov 2026 06:37:43 +0100 Subject: [PATCH 1/2] feat(client): web search sources collapse into one row in chat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tool groups that searched the web now get a "Sources · N" row under them, built like the viewed-images row. It stays visible while the group is collapsed and expands to a deduped list of the pages the search returned, opening each in the browser. Web, desktop and mobile share the derivation in client-runtime; providers that send no result URLs get no row. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 13 ++++ .../src/features/threads/thread-work-log.tsx | 56 ++++++++++++++++ apps/mobile/src/i18n/translations/de.json | 3 +- apps/mobile/src/i18n/translations/en.json | 3 +- apps/mobile/src/i18n/translations/es.json | 3 +- apps/mobile/src/i18n/translations/fr.json | 3 +- apps/mobile/src/i18n/translations/ja.json | 3 +- apps/mobile/src/i18n/translations/ko.json | 3 +- apps/mobile/src/i18n/translations/pt-BR.json | 3 +- apps/mobile/src/i18n/translations/ru.json | 3 +- apps/mobile/src/i18n/translations/sv.json | 3 +- apps/mobile/src/i18n/translations/zh.json | 3 +- apps/mobile/src/lib/openExternalUrl.ts | 1 + apps/mobile/src/lib/threadActivity.ts | 35 ++++++++-- .../components/chat/MessagesTimeline.logic.ts | 64 ++++++++++++++++--- .../src/components/chat/MessagesTimeline.tsx | 6 +- .../components/chat/TimelineWorkEntryRow.tsx | 49 +++++++++++++- apps/web/src/i18n/translations/de.json | 3 +- apps/web/src/i18n/translations/en.json | 3 +- apps/web/src/i18n/translations/es.json | 3 +- apps/web/src/i18n/translations/fr.json | 3 +- apps/web/src/i18n/translations/ja.json | 3 +- apps/web/src/i18n/translations/ko.json | 3 +- apps/web/src/i18n/translations/pt-BR.json | 3 +- apps/web/src/i18n/translations/ru.json | 3 +- apps/web/src/i18n/translations/sv.json | 3 +- apps/web/src/i18n/translations/zh.json | 3 +- .../src/work-log/presentation.test.ts | 43 +++++++++++++ .../src/work-log/presentation.ts | 37 +++++++++++ 29 files changed, 327 insertions(+), 37 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index b81aa7aec59aa..668b0d00f82c2 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -255,6 +255,7 @@ import { ThreadDisclosureChevron, THREAD_DISCLOSURE_TRANSITION_MS, ThreadWorkGroupToggle, + ThreadWebSources, ThreadThinkingRow, ThreadWorkLog, WORK_GROUP_TOGGLE_HEIGHT, @@ -2151,6 +2152,18 @@ function renderFeedEntry( ); } + if (entry.type === "web-sources") { + return ( + props.onToggleWorkGroup(entry.id, entry.id)} + /> + ); + } + if (entry.type === "mcp-app") { return ( ; + readonly iconSubtleColor: ColorValue; + readonly sources: ReadonlyArray; + readonly expanded: boolean; + readonly onToggle: () => void; +}) { + const gt = useGT(); + return ( + + { + void Haptics.selectionAsync(); + props.onToggle(); + }} + rowSizing={props.rowSizing} + > + + + + {gt("Sources · {count}", { count: props.sources.length })} + + + {props.expanded ? ( + + {props.sources.map((source) => ( + void tryOpenExternalUrl(source.url, "web-source")} + className="flex-row items-baseline gap-2 rounded-md px-0.5 py-1 active:bg-subtle" + > + + {source.title} + + + {source.host} + + + ))} + + ) : null} + + ); +} + export function ThreadThinkingRow(props: { readonly rowSizing: ReturnType; readonly iconSubtleColor: ColorValue; diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index e75c87010d88f..b9285d9fa8236 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5264,5 +5264,6 @@ "ad208e3e32c85029": "Alle ausblenden", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool-Aufrufe im Chat", - "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt." + "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", + "98e8f91616613574": "Quellen · {count}" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 39a8cd4d9401b..106b56b893014 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5265,5 +5265,6 @@ "ad208e3e32c85029": "Hide all", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool calls in chat", - "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show." + "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", + "98e8f91616613574": "Sources · {count}" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index a10de0b05a3e5..bdc0b9a06d227 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5258,5 +5258,6 @@ "ad208e3e32c85029": "Ocultar todo", "3328503592789bed": "Zen", "856812e7e1fc445e": "Llamadas a herramientas en el chat", - "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran." + "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", + "98e8f91616613574": "Fuentes · {count}" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 32698d32a9111..28a5a76909d24 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5258,5 +5258,6 @@ "ad208e3e32c85029": "Tout masquer", "3328503592789bed": "Zen", "856812e7e1fc445e": "Appels d’outils dans la discussion", - "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours." + "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", + "98e8f91616613574": "Sources · {count}" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index dbd171818bcdd..de74c21479850 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5240,5 +5240,6 @@ "ad208e3e32c85029": "すべて非表示", "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", - "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。" + "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", + "98e8f91616613574": "ソース · {count}" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b84f6efb68005..384482ad0699a 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5244,5 +5244,6 @@ "ad208e3e32c85029": "모두 숨기기", "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", - "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다." + "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", + "98e8f91616613574": "출처 · {count}" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e806ac68f3715..0906e7f58ecb8 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5258,5 +5258,6 @@ "ad208e3e32c85029": "Ocultar todas", "3328503592789bed": "Zen", "856812e7e1fc445e": "Chamadas de ferramentas no chat", - "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem." + "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", + "98e8f91616613574": "Fontes · {count}" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 345781ca01d5a..23fc3802bf3c1 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5338,5 +5338,6 @@ "ad208e3e32c85029": "Скрывать все", "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", - "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда." + "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", + "98e8f91616613574": "Источники · {count}" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6f2ccdee856b3..081735e34eb05 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5264,5 +5264,6 @@ "ad208e3e32c85029": "Dölj alla", "3328503592789bed": "Zen", "856812e7e1fc445e": "Verktygsanrop i chatten", - "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid." + "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", + "98e8f91616613574": "Källor · {count}" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index e01c9bf7289f3..f93315232f77d 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5249,5 +5249,6 @@ "ad208e3e32c85029": "全部隐藏", "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", - "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。" + "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", + "98e8f91616613574": "来源 · {count}" } diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index ed8946f53d82e..8f21b140a08aa 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -9,6 +9,7 @@ const ExternalUrlTarget = Schema.Literals([ "html-render", "mcp-app", "secret-request", + "web-source", ]); export type ExternalUrlTarget = typeof ExternalUrlTarget.Type; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 4254404a39a99..2c7ffe6a2d61f 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -31,6 +31,8 @@ import { summarizeToolGroup, toolGroupSummaryKind, workEntriesViewedImagePaths, + workEntriesWebSources, + type WebSource, type ToolGroupSummaryKind, type WorkLogPresentationEntry, type WorkLogToolLifecycleStatus, @@ -241,6 +243,15 @@ type ThreadFeedEntryContent = readonly shimmer: boolean; readonly thought?: string; } + | { + /** Pages the tool group above found on the web, kept visible while the group is collapsed. */ + readonly type: "web-sources"; + readonly id: string; + readonly createdAt: string; + readonly runId: RunId | null; + readonly sources: ReadonlyArray; + readonly expanded: boolean; + } | { /** Images the agent opened in the tool group above, kept visible while the group is collapsed. */ readonly type: "viewed-images"; @@ -1422,7 +1433,7 @@ const trailingReasoningGroups = new WeakMap, tail: boolean, ) { @@ -1728,7 +1739,7 @@ export function deriveThreadFeedPresentation( const retainedFeed: Array< Exclude< ThreadFeedEntry, - { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" } + { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" | "web-sources" } > > = []; const retainedFeedIndices: number[] = []; @@ -1746,7 +1757,8 @@ export function deriveThreadFeedPresentation( entry.type === "run-fold" || entry.type === "work-toggle" || entry.type === "thinking" || - entry.type === "viewed-images" + entry.type === "viewed-images" || + entry.type === "web-sources" ) continue; const runId = feedEntryRunId(entry); @@ -2127,7 +2139,7 @@ function appendPresentedFeedEntry( result: ThreadFeedEntry[], entry: Exclude< ThreadFeedEntry, - { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" } + { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" | "web-sources" } >, expandedWorkGroupIds: ReadonlySet, activeRunId: RunId | null, @@ -2223,7 +2235,8 @@ function appendActivityGroupRows( activeTail && isTrailingRun, resolve, ); - const paths = workEntriesViewedImagePaths(groupableRun.map((activity) => activity.workEntry)); + const workEntries = groupableRun.map((activity) => activity.workEntry); + const paths = workEntriesViewedImagePaths(workEntries); if (paths.length > 0) { result.push({ type: "viewed-images", @@ -2233,6 +2246,18 @@ function appendActivityGroupRows( paths, }); } + const sources = workEntriesWebSources(workEntries); + if (sources.length > 0) { + const sourcesId = `${groupId}:web-sources`; + result.push({ + type: "web-sources", + id: sourcesId, + createdAt: groupableRun[0]!.createdAt, + runId: groupableRun[0]!.runId, + sources, + expanded: expandedWorkGroupIds.has(sourcesId), + }); + } groupableRun = []; }; for (const activity of activities) { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 8d282aff42689..31a21832effe3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -28,6 +28,8 @@ import { toolGroupSummaryKind, contextCompactionTokenCounts, workEntriesViewedImagePaths, + workEntriesWebSources, + type WebSource, type ToolGroupSummaryKind, liveThoughtLine, workEntryHiddenByToolCallVisibility, @@ -587,6 +589,14 @@ type MessagesTimelineRowContent = toolIcon?: WorkLogEntry["toolIcon"]; hasFailure: boolean; } + | { + /** Pages the tool group above found on the web, kept visible while the group is collapsed. */ + kind: "web-sources"; + id: string; + createdAt: string; + sources: ReadonlyArray; + expanded: boolean; + } | { /** Images the agent opened in the tool group above, kept visible while the group is collapsed. */ kind: "viewed-images"; @@ -715,15 +725,31 @@ function expandedWorkGroupRow( }; } -function viewedImagesRows( +function groupFindingsRows( groupId: string, createdAt: string, groupedEntries: ReadonlyArray, -): Array> { + expandedWorkGroupIds: ReadonlySet | undefined, +): Array> { const paths = workEntriesViewedImagePaths(groupedEntries); - return paths.length === 0 - ? [] - : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, paths }]; + const sources = workEntriesWebSources(groupedEntries); + const sourcesId = `${groupId}:web-sources`; + return [ + ...(paths.length === 0 + ? [] + : [{ kind: "viewed-images" as const, id: `${groupId}:viewed-images`, createdAt, paths }]), + ...(sources.length === 0 + ? [] + : [ + { + kind: "web-sources" as const, + id: sourcesId, + createdAt, + sources, + expanded: expandedWorkGroupIds?.has(sourcesId) ?? false, + }, + ]), + ]; } export function resolveAssistantMessageCopyState({ @@ -1904,10 +1930,11 @@ export function deriveMessagesTimelineRows( ); } nextRows.push( - ...viewedImagesRows( + ...groupFindingsRows( activeWorkRow.groupId, activeWorkRow.createdAt, activeWorkRow.groupedEntries, + input.expandedWorkGroupIds, ), ); }; @@ -2178,10 +2205,11 @@ export function deriveMessagesTimelineRows( } } nextRows.push( - ...viewedImagesRows( + ...groupFindingsRows( workGroupId(timelineEntry.id), timelineEntry.createdAt, visibleGroupedEntries, + input.expandedWorkGroupIds, ), ); } @@ -2388,7 +2416,14 @@ export function deriveMessagesTimelineRows( if (expanded) { nextRows.push(expandedWorkGroupRow(groupId, failedGroupAnchor.createdAt, groupedEntries)); } - nextRows.push(...viewedImagesRows(groupId, failedGroupAnchor.createdAt, groupedEntries)); + nextRows.push( + ...groupFindingsRows( + groupId, + failedGroupAnchor.createdAt, + groupedEntries, + input.expandedWorkGroupIds, + ), + ); } else { const waitingOn = unsettledRunId === null @@ -2809,6 +2844,19 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; + case "web-sources": { + const bw = b as typeof a; + return ( + a.createdAt === bw.createdAt && + a.expanded === bw.expanded && + a.sources.length === bw.sources.length && + a.sources.every( + (source, index) => + source.url === bw.sources[index]!.url && source.title === bw.sources[index]!.title, + ) + ); + } + case "viewed-images": { const bv = b as typeof a; return ( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index c730075b9d8c7..52827eb30ea45 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -121,7 +121,7 @@ import { LiveWorkEntryTimelineRow, WorkGroupToggleTimelineRow, } from "./TimelineWorkGroupRows"; -import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; +import { ViewedImagesTimelineRow, WebSourcesTimelineRow } from "./TimelineWorkEntryRow"; import { UserMessageRow } from "./TimelineUserMessageRow"; import { AssistantTimelineRow, @@ -1649,7 +1649,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time row.kind === "html-render" || row.kind === "sent-message" || row.kind === "mcp-app" || - row.kind === "viewed-images" + row.kind === "viewed-images" || + row.kind === "web-sources" ? "pb-2" : "pb-4", (row.kind === "message" && row.message.role === "assistant") || @@ -1700,6 +1701,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "html-render" ? : null} {row.kind === "sent-message" ? : null} {row.kind === "viewed-images" ? : null} + {row.kind === "web-sources" ? : null} {row.kind === "mcp-app" ? : null} {row.kind === "working" ? : null} {row.kind === "worktree-setup" ? : null} diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 385123fb21b43..36f04852459d7 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -1,5 +1,5 @@ import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; -import { WorkLogDetails, WorkLogRow } from "./WorkLog"; +import { WorkLogButton, WorkLogDetails, WorkLogRow } from "./WorkLog"; import { getQuestionAnswerPreview, getQuestionAnswerText, @@ -37,7 +37,7 @@ import ChatMarkdown from "../ChatMarkdown"; import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; import { workGroupImageGallery } from "./markdownImageGallery"; -import { ChevronRightIcon, CircleAlertIcon, XIcon, RotateCcwIcon } from "lucide-react"; +import { ChevronRightIcon, CircleAlertIcon, GlobeIcon, XIcon, RotateCcwIcon } from "lucide-react"; import { Button, InlineButton } from "../ui/button"; import { useAssetUrls } from "../../assets/assetUrls"; import { useThreadShell } from "../../state/entities"; @@ -278,6 +278,51 @@ export function ViewedImagesTimelineRow({ ); } +export function WebSourcesTimelineRow({ + row, +}: { + row: Extract; +}) { + const { onToggleWorkGroup } = use(TimelineRowCtx); + const gt = useGT(); + return ( +
+ onToggleWorkGroup(row.id, row.id)} + icon={} + label={gt("Sources · {count}", { count: row.sources.length })} + trailing={ + + } + /> + {row.expanded ? ( + + ) : null} +
+ ); +} + function WorkEntryLogRow(props: WorkEntryRowProps) { const { workEntry, workspaceRoot, displayLabel } = props; const ctx = use(TimelineRowCtx); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 1c890e574a679..d14f0e6cd1e9b 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12105,5 +12105,6 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "98e8f91616613574": "Quellen · {count}" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2e625d71847db..33b397b39a6ed 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12114,5 +12114,6 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "98e8f91616613574": "Sources · {count}" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 9b66ebfd3d698..28c06d4ed3eb4 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12100,5 +12100,6 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "98e8f91616613574": "Fuentes · {count}" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 7d711f2aee72c..c20ed796e8a53 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12105,5 +12105,6 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "98e8f91616613574": "Sources · {count}" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 51dbe52eff841..7d8dd2bc2eb8c 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12053,5 +12053,6 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "98e8f91616613574": "ソース · {count}" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index a8e4420475211..b050ff082817a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12049,5 +12049,6 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "98e8f91616613574": "출처 · {count}" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 7774a31c9acc9..53befa16258aa 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12104,5 +12104,6 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "98e8f91616613574": "Fontes · {count}" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5badc3992e1c6..b45b99dd8ba56 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12104,5 +12104,6 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "98e8f91616613574": "Источники · {count}" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c989d45dccd1e..9495e82a9fb38 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12112,5 +12112,6 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "98e8f91616613574": "Källor · {count}" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index b74a6631969c1..9dd2f92809a1e 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12130,5 +12130,6 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "98e8f91616613574": "来源 · {count}" } diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.ts index f79cd14c91981..30421dae5da7f 100644 --- a/packages/client-runtime/src/work-log/presentation.test.ts +++ b/packages/client-runtime/src/work-log/presentation.test.ts @@ -9,6 +9,7 @@ import { type WorkLogPresentationEntry, workEntryIndicatesToolFailure, workEntryDisplayIndicatesToolFailure, + workEntriesWebSources, } from "./presentation.js"; function commandItem( @@ -204,3 +205,45 @@ describe("resolveWorkEntryToolPresentation", () => { ).toBeNull(); }); }); + +describe("workEntriesWebSources", () => { + it("keeps distinct web pages across a group's searches", () => { + const search = ( + results: NonNullable["results"]>, + ): WorkLogPresentationEntry => { + const { input: _input, ...base } = commandItem() as Extract< + OrchestrationV2TurnItem, + { type: "command_execution" } + >; + return { + id: "search", + createdAt: "2026-09-08T00:00:00.000Z", + label: "Searched the web", + tone: "tool", + itemType: "web_search", + structuredPayload: { ...base, type: "web_search", results }, + }; + }; + + expect( + workEntriesWebSources([ + search([ + { title: " Node.js releases ", url: "https://nodejs.org/en/about/previous-releases" }, + { url: "https://www.example.com/post#section" }, + { title: "Local file", url: "file:///etc/passwd" }, + { title: "Not a URL", url: "nodejs.org" }, + { title: "No URL" }, + ]), + { id: "command", createdAt: "2026-09-08T00:00:00.000Z", label: "ls", tone: "tool" }, + search([{ title: "Same page", url: "https://www.example.com/post#other" }]), + ]), + ).toEqual([ + { + url: "https://nodejs.org/en/about/previous-releases", + title: "Node.js releases", + host: "nodejs.org", + }, + { url: "https://www.example.com/post", title: "example.com", host: "example.com" }, + ]); + }); +}); diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index a838bc9794c65..d585464a8523c 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -454,6 +454,43 @@ export function workEntriesViewedImagePaths( return [...new Set(entries.flatMap((entry) => workEntryViewedImagePath(entry) ?? []))]; } +export interface WebSource { + readonly url: string; + readonly title: string; + readonly host: string; +} + +/** Distinct http(s) pages a tool group's web searches returned, in result order. */ +export function workEntriesWebSources( + entries: ReadonlyArray, +): WebSource[] { + const sources = new Map(); + for (const entry of entries) { + const item = entry.structuredPayload; + if (item?.type !== "web_search") continue; + for (const result of item.results ?? []) { + const source = webSource(result.url, result.title); + if (source && !sources.has(source.url)) sources.set(source.url, source); + } + } + return [...sources.values()]; +} + +function webSource(rawUrl: string | undefined, title: string | undefined): WebSource | null { + if (!rawUrl) return null; + let url: URL; + try { + url = new URL(rawUrl); + } catch { + return null; + } + if (url.protocol !== "https:" && url.protocol !== "http:") return null; + const host = url.hostname.replace(/^www\./, ""); + // Anchors into one page are one source. + const href = url.href.split("#")[0]!; + return { url: href, title: title?.trim() || host, host }; +} + export interface ViewedImageAsset { readonly resource: Extract; readonly alt: string; From b7dd48726210f0988cf32278e648055d7d4fcd24 Mon Sep 17 00:00:00 2001 From: Akash Date: Thu, 19 Nov 2026 06:50:28 +0100 Subject: [PATCH 2/2] fix(client): keep web sources under the turn's answer The per-group Sources row folded away with the turn's work once the turn finished, so readers never saw it next to the answer. Sources now gather from every search in the run and sit under its final answer, outside the fold. The list renders through each client's chat markdown, so links follow the user's link-target preference and context menu. Parsed sources are cached per search so streaming rebuilds stay cheap. Co-Authored-By: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 13 +++- .../src/features/threads/thread-work-log.tsx | 28 +------ apps/mobile/src/lib/openExternalUrl.ts | 1 - apps/mobile/src/lib/threadActivity.ts | 63 +++++++++++---- .../chat/MessagesTimeline.logic.test.ts | 76 ++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 78 +++++++++++-------- .../components/chat/TimelineWorkEntryRow.tsx | 26 +++---- .../src/work-log/presentation.test.ts | 9 +++ .../src/work-log/presentation.ts | 32 ++++++-- 9 files changed, 229 insertions(+), 97 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 668b0d00f82c2..6ce5c299d6324 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -111,6 +111,7 @@ import { import { contextCompactionTokenCounts, resolveViewedImageAsset, + webSourcesMarkdown, } from "@t3tools/client-runtime/work-log/presentation"; import { renderCodexInlineDirectivesAsMarkdown, @@ -2157,10 +2158,18 @@ function renderFeedEntry( props.onToggleWorkGroup(entry.id, entry.id)} - /> + > + + ); } diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 4bf420e212eaf..5ea5b40afc293 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -64,7 +64,6 @@ import { } from "@t3tools/client-runtime/work-log/command-label"; import { AppText as Text } from "../../components/ui/AppText"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { T3Wordmark } from "../../components/T3Wordmark"; import { BrowserAppIcon } from "./BrowserAppIcon"; import { useAppActive, useReduceMotionEnabled } from "../../lib/appState"; @@ -91,7 +90,6 @@ import { toolGroupAction, type ToolGroupSummaryKind, workEntryViewedImagePath, - type WebSource, } from "@t3tools/client-runtime/work-log/presentation"; import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution"; import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText"; @@ -1450,9 +1448,10 @@ export function ThreadWorkGroupToggle(props: { export function ThreadWebSources(props: { readonly rowSizing: ReturnType; readonly iconSubtleColor: ColorValue; - readonly sources: ReadonlyArray; + readonly count: number; readonly expanded: boolean; readonly onToggle: () => void; + readonly children: ReactNode; }) { const gt = useGT(); return ( @@ -1469,7 +1468,7 @@ export function ThreadWebSources(props: { - {gt("Sources · {count}", { count: props.sources.length })} + {gt("Sources · {count}", { count: props.count })} - {props.expanded ? ( - - {props.sources.map((source) => ( - void tryOpenExternalUrl(source.url, "web-source")} - className="flex-row items-baseline gap-2 rounded-md px-0.5 py-1 active:bg-subtle" - > - - {source.title} - - - {source.host} - - - ))} - - ) : null} + {props.expanded ? {props.children} : null} ); } diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index 8f21b140a08aa..ed8946f53d82e 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -9,7 +9,6 @@ const ExternalUrlTarget = Schema.Literals([ "html-render", "mcp-app", "secret-request", - "web-source", ]); export type ExternalUrlTarget = typeof ExternalUrlTarget.Type; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 2c7ffe6a2d61f..a61f89a3861f7 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -244,7 +244,7 @@ type ThreadFeedEntryContent = readonly thought?: string; } | { - /** Pages the tool group above found on the web, kept visible while the group is collapsed. */ + /** Pages the turn's web searches found, shown under its answer so the run fold keeps them. */ readonly type: "web-sources"; readonly id: string; readonly createdAt: string; @@ -1699,6 +1699,35 @@ const DEFAULT_THREAD_FEED_DISPLAY: ThreadFeedDisplay = { revealedMessageId: null, }; +// Keyed by each run's last assistant message; every search in the run counts, folded or hidden. +function deriveAnswerWebSources( + feed: ReadonlyArray, +): ReadonlyMap> { + const lastAnswerIdByRun = new Map(); + const searchesByRun = new Map(); + for (const entry of feed) { + if (entry.type === "message") { + if (entry.message.role === "assistant" && entry.message.runId !== null) { + lastAnswerIdByRun.set(entry.message.runId, entry.message.id); + } + } else if (entry.type === "activity-group" && entry.runId !== null) { + for (const activity of entry.activities) { + if (activity.workEntry.itemType !== "web_search") continue; + const searches = searchesByRun.get(entry.runId) ?? []; + searches.push(activity.workEntry); + searchesByRun.set(entry.runId, searches); + } + } + } + const sourcesByAnswerId = new Map>(); + for (const [runId, searches] of searchesByRun) { + const answerId = lastAnswerIdByRun.get(runId); + const sources = workEntriesWebSources(searches); + if (answerId !== undefined && sources.length > 0) sourcesByAnswerId.set(answerId, sources); + } + return sourcesByAnswerId; +} + export function deriveThreadFeedPresentation( feed: ReadonlyArray, latestRun: ThreadFeedLatestRun | null, @@ -1807,6 +1836,7 @@ export function deriveThreadFeedPresentation( compactionItemRunIds.add(entry.runId); } } + const answerSources = deriveAnswerWebSources(feed); const foldsByAnchorId = zen ? new Map() : deriveThreadFeedRunFolds( @@ -1940,6 +1970,22 @@ export function deriveThreadFeedPresentation( resolve, locale, ); + const sources = entry.type === "message" ? answerSources.get(entry.message.id) : undefined; + if ( + entry.type === "message" && + sources && + !(isWorking && entry.message.runId === activeRunId) + ) { + const id = `web-sources:${entry.message.id}`; + result.push({ + type: "web-sources", + id, + createdAt: entry.createdAt, + runId: entry.message.runId, + sources, + expanded: expandedWorkGroupIds.has(id), + }); + } } } if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); @@ -2235,8 +2281,7 @@ function appendActivityGroupRows( activeTail && isTrailingRun, resolve, ); - const workEntries = groupableRun.map((activity) => activity.workEntry); - const paths = workEntriesViewedImagePaths(workEntries); + const paths = workEntriesViewedImagePaths(groupableRun.map((activity) => activity.workEntry)); if (paths.length > 0) { result.push({ type: "viewed-images", @@ -2246,18 +2291,6 @@ function appendActivityGroupRows( paths, }); } - const sources = workEntriesWebSources(workEntries); - if (sources.length > 0) { - const sourcesId = `${groupId}:web-sources`; - result.push({ - type: "web-sources", - id: sourcesId, - createdAt: groupableRun[0]!.createdAt, - runId: groupableRun[0]!.runId, - sources, - expanded: expandedWorkGroupIds.has(sourcesId), - }); - } groupableRun = []; }; for (const activity of activities) { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index f834c7cc355b9..da37134665d5b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1246,6 +1246,82 @@ describe("deriveMessagesTimelineRows", () => { ).toBeDefined(); }); + it("keeps the turn's web sources under its answer when the work folds", () => { + const runId = RunId.make("turn-1"); + const search = (id: string, url: string) => ({ + id: `${id}-entry`, + kind: "work" as const, + createdAt: "2026-01-01T00:00:01Z", + entry: { + id, + createdAt: "2026-01-01T00:00:01Z", + runId, + label: "Searched the web", + tone: "tool" as const, + itemType: "web_search" as const, + toolLifecycleStatus: "completed" as const, + structuredPayload: { type: "web_search", results: [{ title: "Docs", url }] } as never, + }, + }); + const timelineEntries = [ + search("search-1", "https://nodejs.org/en"), + search("search-2", "https://nodejs.org/en#latest"), + { + id: "assistant-final-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant-final" as never, + role: "assistant" as const, + text: "Node 26 is current.", + runId, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: false, + }, + }, + ]; + const input = { + timelineEntries, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaries: [], + supportsConversationRollback: false, + }; + + const rows = deriveMessagesTimelineRows({ + ...input, + latestRun: { + runId, + status: "completed" as const, + startedAt: "2026-01-01T00:00:00Z", + completedAt: "2026-01-01T00:00:10Z", + }, + }); + expect(rows.map((row) => row.id)).toEqual([ + "turn-fold:turn-1", + "assistant-final-entry", + "web-sources:assistant-final", + ]); + expect(rows.at(-1)).toMatchObject({ + sources: [{ url: "https://nodejs.org/en", title: "Docs", host: "nodejs.org" }], + expanded: false, + }); + + const working = deriveMessagesTimelineRows({ + ...input, + isWorking: true, + activeTurnStartedAt: "2026-01-01T00:00:00Z", + latestRun: { + runId, + status: "running" as const, + startedAt: "2026-01-01T00:00:00Z", + completedAt: null, + }, + }); + expect(working.some((row) => row.kind === "web-sources")).toBe(false); + }); + it.each([1, 2, 3])("folds %i completed activities after the terminal response", (count) => { const runId = RunId.make("turn-1"); const timelineEntries = [ diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 31a21832effe3..4076597ffa28d 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -590,7 +590,7 @@ type MessagesTimelineRowContent = hasFailure: boolean; } | { - /** Pages the tool group above found on the web, kept visible while the group is collapsed. */ + /** Pages the turn's web searches found, shown under its answer so the work fold keeps them. */ kind: "web-sources"; id: string; createdAt: string; @@ -725,31 +725,15 @@ function expandedWorkGroupRow( }; } -function groupFindingsRows( +function viewedImagesRows( groupId: string, createdAt: string, groupedEntries: ReadonlyArray, - expandedWorkGroupIds: ReadonlySet | undefined, -): Array> { +): Array> { const paths = workEntriesViewedImagePaths(groupedEntries); - const sources = workEntriesWebSources(groupedEntries); - const sourcesId = `${groupId}:web-sources`; - return [ - ...(paths.length === 0 - ? [] - : [{ kind: "viewed-images" as const, id: `${groupId}:viewed-images`, createdAt, paths }]), - ...(sources.length === 0 - ? [] - : [ - { - kind: "web-sources" as const, - id: sourcesId, - createdAt, - sources, - expanded: expandedWorkGroupIds?.has(sourcesId) ?? false, - }, - ]), - ]; + return paths.length === 0 + ? [] + : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, paths }]; } export function resolveAssistantMessageCopyState({ @@ -769,6 +753,25 @@ export function resolveAssistantMessageCopyState({ }; } +// Every search in the run counts, including ones the work fold or tool visibility hides. +function deriveWebSourcesByRunId(timelineEntries: ReadonlyArray) { + const searchesByRunId = new Map(); + for (const entry of timelineEntries) { + if (entry.kind !== "work" || entry.entry.itemType !== "web_search" || !entry.entry.runId) { + continue; + } + const searches = searchesByRunId.get(entry.entry.runId) ?? []; + searches.push(entry.entry); + searchesByRunId.set(entry.entry.runId, searches); + } + const sourcesByRunId = new Map>(); + for (const [runId, searches] of searchesByRunId) { + const sources = workEntriesWebSources(searches); + if (sources.length > 0) sourcesByRunId.set(runId, sources); + } + return sourcesByRunId; +} + function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray) { const lastAssistantMessageIdByResponseKey = new Map(); let nullTurnResponseIndex = 0; @@ -1673,6 +1676,7 @@ export function deriveMessagesTimelineRows( : new Map(); const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); + const webSourcesByRunId = deriveWebSourcesByRunId(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); @@ -1930,11 +1934,10 @@ export function deriveMessagesTimelineRows( ); } nextRows.push( - ...groupFindingsRows( + ...viewedImagesRows( activeWorkRow.groupId, activeWorkRow.createdAt, activeWorkRow.groupedEntries, - input.expandedWorkGroupIds, ), ); }; @@ -2205,11 +2208,10 @@ export function deriveMessagesTimelineRows( } } nextRows.push( - ...groupFindingsRows( + ...viewedImagesRows( workGroupId(timelineEntry.id), timelineEntry.createdAt, visibleGroupedEntries, - input.expandedWorkGroupIds, ), ); } @@ -2320,6 +2322,11 @@ export function deriveMessagesTimelineRows( terminalAssistantMessageIds.has(timelineEntry.message.id) && !assistantResponseStillInProgress; + const answerSources = + showAssistantMeta && timelineEntry.message.runId != null + ? webSourcesByRunId.get(timelineEntry.message.runId) + : undefined; + nextRows.push({ kind: "message", id: timelineEntry.id, @@ -2344,6 +2351,16 @@ export function deriveMessagesTimelineRows( ? revertTurnCountByUserMessageId.get(timelineEntry.message.id) : undefined, }); + if (answerSources) { + const id = `web-sources:${timelineEntry.message.id}`; + nextRows.push({ + kind: "web-sources", + id, + createdAt: timelineEntry.createdAt, + sources: answerSources, + expanded: input.expandedWorkGroupIds?.has(id) ?? false, + }); + } } const setupHandedOff = @@ -2416,14 +2433,7 @@ export function deriveMessagesTimelineRows( if (expanded) { nextRows.push(expandedWorkGroupRow(groupId, failedGroupAnchor.createdAt, groupedEntries)); } - nextRows.push( - ...groupFindingsRows( - groupId, - failedGroupAnchor.createdAt, - groupedEntries, - input.expandedWorkGroupIds, - ), - ); + nextRows.push(...viewedImagesRows(groupId, failedGroupAnchor.createdAt, groupedEntries)); } else { const waitingOn = unsettledRunId === null diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 36f04852459d7..0213d3ffbf947 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -18,6 +18,7 @@ import { resolveViewedImageAsset, resolveWorkEntryToolPresentation, toolGroupAction, + webSourcesMarkdown, workEntryViewedImagePath, } from "@t3tools/client-runtime/work-log/presentation"; import { t3ToolResultIndicatesFailure } from "@t3tools/client-runtime/t3ToolSummary"; @@ -283,7 +284,7 @@ export function WebSourcesTimelineRow({ }: { row: Extract; }) { - const { onToggleWorkGroup } = use(TimelineRowCtx); + const { onToggleWorkGroup, markdownCwd, threadRef } = use(TimelineRowCtx); const gt = useGT(); return (
@@ -303,21 +304,14 @@ export function WebSourcesTimelineRow({ } /> {row.expanded ? ( - +
+ +
) : null}
); diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.ts index 30421dae5da7f..aed3177dfe965 100644 --- a/packages/client-runtime/src/work-log/presentation.test.ts +++ b/packages/client-runtime/src/work-log/presentation.test.ts @@ -9,6 +9,7 @@ import { type WorkLogPresentationEntry, workEntryIndicatesToolFailure, workEntryDisplayIndicatesToolFailure, + webSourcesMarkdown, workEntriesWebSources, } from "./presentation.js"; @@ -246,4 +247,12 @@ describe("workEntriesWebSources", () => { { url: "https://www.example.com/post", title: "example.com", host: "example.com" }, ]); }); + + it("renders titles as literal link text", () => { + expect( + webSourcesMarkdown([ + { url: "https://a.dev/x_(y)", title: "[Guide] *new* `v2`", host: "a.dev" }, + ]), + ).toBe(String.raw`- [\[Guide\] \*new\* \`v2\`]() · a\.dev`); + }); }); diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index d585464a8523c..1e1f714d6dc63 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -460,7 +460,9 @@ export interface WebSource { readonly host: string; } -/** Distinct http(s) pages a tool group's web searches returned, in result order. */ +const webSourcesByItem = new WeakMap>(); + +/** Distinct http(s) pages the entries' web searches returned, in result order. */ export function workEntriesWebSources( entries: ReadonlyArray, ): WebSource[] { @@ -468,14 +470,34 @@ export function workEntriesWebSources( for (const entry of entries) { const item = entry.structuredPayload; if (item?.type !== "web_search") continue; - for (const result of item.results ?? []) { - const source = webSource(result.url, result.title); - if (source && !sources.has(source.url)) sources.set(source.url, source); + let itemSources = webSourcesByItem.get(item); + if (itemSources === undefined) { + itemSources = (item.results ?? []).flatMap( + (result) => webSource(result.url, result.title) ?? [], + ); + webSourcesByItem.set(item, itemSources); + } + for (const source of itemSources) { + if (!sources.has(source.url)) sources.set(source.url, source); } } return [...sources.values()]; } +/** One linked line per source, for the clients' markdown renderers. */ +export function webSourcesMarkdown(sources: ReadonlyArray): string { + return sources + .map( + (source) => + `- [${escapeMarkdownText(source.title)}](<${source.url}>) · ${escapeMarkdownText(source.host)}`, + ) + .join("\n"); +} + +function escapeMarkdownText(text: string): string { + return text.replace(/[\\`*_{}[\]()#+\-.!|<>~&]/g, "\\$&"); +} + function webSource(rawUrl: string | undefined, title: string | undefined): WebSource | null { if (!rawUrl) return null; let url: URL; @@ -488,7 +510,7 @@ function webSource(rawUrl: string | undefined, title: string | undefined): WebSo const host = url.hostname.replace(/^www\./, ""); // Anchors into one page are one source. const href = url.href.split("#")[0]!; - return { url: href, title: title?.trim() || host, host }; + return { url: href, title: title?.replace(/\s+/g, " ").trim() || host, host }; } export interface ViewedImageAsset {