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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ import {
import {
contextCompactionTokenCounts,
resolveViewedImageAsset,
webSourcesMarkdown,
} from "@t3tools/client-runtime/work-log/presentation";
import {
renderCodexInlineDirectivesAsMarkdown,
Expand Down Expand Up @@ -255,6 +256,7 @@ import {
ThreadDisclosureChevron,
THREAD_DISCLOSURE_TRANSITION_MS,
ThreadWorkGroupToggle,
ThreadWebSources,
ThreadThinkingRow,
ThreadWorkLog,
WORK_GROUP_TOGGLE_HEIGHT,
Expand Down Expand Up @@ -2151,6 +2153,26 @@ function renderFeedEntry(
);
}

if (entry.type === "web-sources") {
return (
<ThreadWebSources
rowSizing={props.workRowSizing}
iconSubtleColor={iconSubtleColor}
count={entry.sources.length}
expanded={entry.expanded}
onToggle={() => props.onToggleWorkGroup(entry.id, entry.id)}
>
<AssistantMarkdownContent
markdown={webSourcesMarkdown(entry.sources)}
environmentId={props.environmentId}
markdownStyles={markdownStyles.assistant}
linkHandlers={props.markdownLinkHandlers}
renderImage={props.renderMarkdownImage}
/>
</ThreadWebSources>
);
}

if (entry.type === "mcp-app") {
return (
<ThreadMcpApp
Expand Down
36 changes: 36 additions & 0 deletions apps/mobile/src/features/threads/thread-work-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1445,6 +1445,42 @@ export function ThreadWorkGroupToggle(props: {
);
}

export function ThreadWebSources(props: {
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
readonly iconSubtleColor: ColorValue;
readonly count: number;
readonly expanded: boolean;
readonly onToggle: () => void;
readonly children: ReactNode;
}) {
const gt = useGT();
return (
<WorkLogBlock>
<WorkLogPressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
onPress={() => {
void Haptics.selectionAsync();
props.onToggle();
}}
rowSizing={props.rowSizing}
>
<WorkLogIconSlot>
<WorkLogIcon icon="browser" color={props.iconSubtleColor} />
</WorkLogIconSlot>
<WorkLogLabel>{gt("Sources · {count}", { count: props.count })}</WorkLogLabel>
<ThreadDisclosureChevron
expanded={props.expanded}
collapsedDirection="right"
size={11}
tintColor={props.iconSubtleColor}
/>
</WorkLogPressable>
{props.expanded ? <View className="ms-8 pb-1">{props.children}</View> : null}
</WorkLogBlock>
);
}

export function ThreadThinkingRow(props: {
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
readonly iconSubtleColor: ColorValue;
Expand Down
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -5240,5 +5240,6 @@
"ad208e3e32c85029": "すべて非表示",
"3328503592789bed": "Zen",
"856812e7e1fc445e": "チャット内のツール呼び出し",
"8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。"
"8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。",
"98e8f91616613574": "ソース · {count}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -5244,5 +5244,6 @@
"ad208e3e32c85029": "모두 숨기기",
"3328503592789bed": "Zen",
"856812e7e1fc445e": "채팅의 도구 호출",
"8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다."
"8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.",
"98e8f91616613574": "출처 · {count}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -5338,5 +5338,6 @@
"ad208e3e32c85029": "Скрывать все",
"3328503592789bed": "Дзен",
"856812e7e1fc445e": "Вызовы инструментов в чате",
"8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда."
"8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.",
"98e8f91616613574": "Источники · {count}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
}
3 changes: 2 additions & 1 deletion apps/mobile/src/i18n/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -5249,5 +5249,6 @@
"ad208e3e32c85029": "全部隐藏",
"3328503592789bed": "专注模式",
"856812e7e1fc445e": "聊天中的工具调用",
"8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。"
"8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。",
"98e8f91616613574": "来源 · {count}"
}
66 changes: 62 additions & 4 deletions apps/mobile/src/lib/threadActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
summarizeToolGroup,
toolGroupSummaryKind,
workEntriesViewedImagePaths,
workEntriesWebSources,
type WebSource,
type ToolGroupSummaryKind,
type WorkLogPresentationEntry,
type WorkLogToolLifecycleStatus,
Expand Down Expand Up @@ -241,6 +243,15 @@ type ThreadFeedEntryContent =
readonly shimmer: boolean;
readonly thought?: string;
}
| {
/** 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;
readonly runId: RunId | null;
readonly sources: ReadonlyArray<WebSource>;
readonly expanded: boolean;
}
| {
/** Images the agent opened in the tool group above, kept visible while the group is collapsed. */
readonly type: "viewed-images";
Expand Down Expand Up @@ -1422,7 +1433,7 @@ const trailingReasoningGroups = new WeakMap<ThreadFeedActivityGroup, ThreadFeedA
function settleSupersededReasoning(
entry: Exclude<
ThreadFeedEntry,
{ readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" }
{ readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" | "web-sources" }
>,
tail: boolean,
) {
Expand Down Expand Up @@ -1688,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<ThreadFeedEntry>,
): ReadonlyMap<string, ReadonlyArray<WebSource>> {
const lastAnswerIdByRun = new Map<RunId, string>();
const searchesByRun = new Map<RunId, WorkLogPresentationEntry[]>();
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<string, ReadonlyArray<WebSource>>();
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<ThreadFeedEntry>,
latestRun: ThreadFeedLatestRun | null,
Expand Down Expand Up @@ -1728,7 +1768,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[] = [];
Expand All @@ -1746,7 +1786,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);
Expand Down Expand Up @@ -1795,6 +1836,7 @@ export function deriveThreadFeedPresentation(
compactionItemRunIds.add(entry.runId);
}
}
const answerSources = deriveAnswerWebSources(feed);
const foldsByAnchorId = zen
? new Map<string, ThreadFeedRunFold>()
: deriveThreadFeedRunFolds(
Expand Down Expand Up @@ -1928,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);
Expand Down Expand Up @@ -2127,7 +2185,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<string>,
activeRunId: RunId | null,
Expand Down
76 changes: 76 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
Loading
Loading