feat(app): show a turn's web sources behind the Sources experiment (#58307)

This commit is contained in:
Kit Langton
2026-10-24 13:03:57 -07:00
committed by GitHub
Unverified
parent 33ffc3e58d
commit 0f379f0a33
26 changed files with 1710 additions and 36 deletions
@@ -1,3 +1,4 @@
import type { SessionMessageInfo } from "@opencode/client/promise"
import { DialogProvider } from "@opencode/ui/context/dialog"
import {
Panel,
@@ -389,7 +390,12 @@ function RealHost(props: ParentProps<{ definitions: readonly Definition[]; captu
* does: a new session object each time, delivered through the same reactive inputs, while the one screen object
* `ctx.screen` returns follows the route. Its composer records which session each attachment reached.
*/
export function mountSessionRegion(input: { definitions: readonly Definition[]; active: string }) {
export function mountSessionRegion(input: {
definitions: readonly Definition[]
active: string
/** The routed session's messages, as its server holds them. */
messages?: readonly SessionMessageInfo[]
}) {
const container = document.createElement("div")
document.body.appendChild(container)
const hosts: ExtensionHost[] = []
@@ -397,9 +403,18 @@ export function mountSessionRegion(input: { definitions: readonly Definition[];
const attached: string[] = []
const object = (id: string) => {
const value = { key: `fixture\n${id}`, id, tab: id, pending: false, location: { directory: "/repo" }, visit: {} }
const value = {
key: `fixture\n${id}`,
id,
tab: id,
pending: false,
location: { directory: "/repo" },
visit: {},
server: { data: { session: { message: { list: () => input.messages ?? [] } } } },
}
// SAFETY: the region and slot pass the object through; the test's extension reads only `key` and `id`.
// SAFETY: the region and slot pass the object through; the test's extensions read only `key`, `id` and the
// server's message list.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above
return value as unknown as MountedSession
}
@@ -0,0 +1,98 @@
import type { SessionMessageInfo } from "@opencode/client/promise"
import type { MotionKnob } from "@opencode/ui/motion-tuning"
import { expect, sourceURL, story } from "../../stories/playwright/story"
const source = (path: string) => sourceURL(new URL(path, import.meta.url))
const modules = {
fixture: source("./extension-host.fixture.tsx"),
definition: source("../../gui-extensions/src/sources/index.ts"),
renderer: source("../../gui-extensions/src/sources/renderer.tsx"),
tuning: source("../../ui/src/motion-tuning.ts"),
}
// One turn: the user message the panel's tab is keyed by, and a reply that searched the web.
const messages: SessionMessageInfo[] = [
{ id: "main", type: "user", text: "Who made One Million Checkboxes?", time: { created: 1 } },
{
id: "msg_reply",
type: "assistant",
agent: "build",
model: { id: "claude-sonnet-4", providerID: "anthropic" },
time: { created: 2, completed: 3 },
content: [
{
type: "tool",
id: "call_search",
name: "websearch",
state: {
status: "completed",
input: { query: "one million checkboxes" },
content: [
{ type: "text", text: "## [One Million Checkboxes](https://eieio.games/blog/one-million-checkboxes)" },
],
},
time: { created: 2, ran: 2, completed: 3 },
},
],
},
]
story.beforeEach(async ({ mount }) => {
// Any story loads the app; the fixture mounts the real host beside it.
await mount("ui-line-comment--editor")
})
story("turning the Sources experiment off closes its open panel and loads no more site icons", async ({ page }) => {
// Site icons stay off the network, and load, so each stays an image until the experiment turns off.
await page.route("**/favicon.ico", (route) =>
route.fulfill({
contentType: "image/png",
body: Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
),
}),
)
const result = await page.evaluate(
async (input) => {
const [{ mountSessionRegion, until }, { default: definition }, { default: renderer }, { motionTuning }] =
await Promise.all([
import(input.modules.fixture),
import(input.modules.definition),
import(input.modules.renderer),
import(input.modules.tuning),
])
const knob = (id: string) => motionTuning.list().find((item: MotionKnob) => item.id === id)
motionTuning.set(knob("sources.enabled"), true)
motionTuning.set(knob("sources.icons"), "site")
const host: { container: HTMLElement; unmount: () => void } = mountSessionRegion({
active: "sources:main",
messages: JSON.parse(input.messages),
definitions: [{ ...definition, renderer: async () => ({ default: renderer }) }],
})
const panel = () => host.container.querySelector('[data-slot="session-sources-panel"]')
const icons = () => host.container.querySelectorAll('[data-slot="site-icon-image"]').length
await until(() => !!panel()?.querySelector('[data-slot="sources-step-row"]'))
panel()?.querySelector<HTMLButtonElement>('[data-slot="sources-step-row"]')?.click()
await until(() => icons() > 0)
const open = { panel: !!panel(), icons: icons() }
motionTuning.set(knob("sources.enabled"), false)
await until(() => !panel())
const off = { panel: !!panel(), icons: icons() }
host.unmount()
return { open, off }
},
// As JSON: the messages' type is too deep for `evaluate`'s serializable argument check.
{ modules, messages: JSON.stringify(messages) },
)
expect(result).toEqual({ open: { panel: true, icons: 1 }, off: { panel: false, icons: 0 } })
})
+13 -2
View File
@@ -1,6 +1,8 @@
import { createMemo, ErrorBoundary, For, onMount, Show, untrack, type JSX, type ParentProps } from "solid-js"
import { Portal } from "solid-js/web"
import { MarkdownProvider, useMarkdown } from "@opencode/session-ui/context/markdown"
import { SourcesProvider } from "@opencode/session-ui/context/sources"
import { sourcesExperiment } from "@opencode/session-ui/sources/experiment"
import { ExtensionContext, Slot, Style, type MountedSession, type SlotMap } from "@opencode/gui-extensions/sdk"
import { useExtensionHost } from "./host"
@@ -64,7 +66,10 @@ export function ExtensionStyles() {
)
}
/** Routes local markdown links in the session to extension LinkHandler contributions, keeping image loading. */
/**
* Routes local markdown links in the session to extension LinkHandler contributions, keeping image loading. A turn's
* sources chip opens its turn through the Sources extension's handler.
*/
export function ExtensionLinks(props: ParentProps<{ session: MountedSession }>) {
const host = useExtensionHost()
const markdown = useMarkdown()
@@ -76,7 +81,13 @@ export function ExtensionLinks(props: ParentProps<{ session: MountedSession }>)
// Untracked: markdown calls this inside its render effect, which must not follow the routed session.
localFileExists={(href) => untrack(() => host.links.exists({ href, session: props.session }))}
>
{props.children}
<SourcesProvider
enabled={sourcesExperiment.enabled}
icons={sourcesExperiment.icons}
onOpen={(from) => void host.links.open({ href: from, origin: "sources", session: props.session })}
>
{props.children}
</SourcesProvider>
</MarkdownProvider>
)
}
+10 -2
View File
@@ -20,7 +20,7 @@ import type { ComposerPersistedState } from "@/composer/types"
import { Button } from "@opencode/ui/button"
import { Icon } from "@opencode/ui/icon"
import { QueryClient, QueryClientProvider } from "@tanstack/solid-query"
import { Show, type ComponentProps } from "solid-js"
import { children, Show, type ComponentProps, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import type { WebSearchRequestModel } from "./requests/websearch"
@@ -96,6 +96,8 @@ export type SessionPreviewProps = {
onStop?: (item: SessionActivityItem) => void
}
timelineDetail?: TimelineDetail
/** Content for the side panel, shown beside the timeline while present. */
side?: JSX.Element
}
export function SessionPreview(props: SessionPreviewProps) {
@@ -183,6 +185,7 @@ export function createPromptController(input: {
function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void }) {
const language = useLanguage()
const side = children(() => props.side)
const [state, setState] = createStore<{
activity: string
@@ -316,7 +319,12 @@ function SessionSurfaceState(props: SessionPreviewProps & { onReset: () => void
composer={<Composer model={prompt.controller} borderUnderlay />}
/>
</section>
<Show when={state.reviewOpened}>
<Show when={side()}>
<aside class="flex w-[400px] min-w-0 flex-none flex-col border-l border-v2-border-border-base">
{side()}
</aside>
</Show>
<Show when={!side() && state.reviewOpened}>
<aside
id="review-panel"
class="min-w-0 flex-1 flex flex-col gap-2 border-l border-v2-border-border-base md:max-w-[52%]"
@@ -0,0 +1,339 @@
import type { SessionMessageAssistant, SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise"
import { SourcesProvider } from "@opencode/session-ui/context/sources"
import type { SessionDocument } from "@opencode/session-ui/document"
import { turnMessages, turnSources } from "@opencode/session-ui/sources"
import type { SiteIconMode } from "@opencode/session-ui/sources/experiment"
import { SourcesPanel } from "@opencode/session-ui/sources/panel"
import { SourcesTitle } from "@opencode/session-ui/sources/title"
import { CURRENT_SESSION_ID, STORY_MODEL, STORY_TIME } from "@opencode/session-ui/storybook"
import { timelinePresets } from "@opencode/session-ui/timeline/detail"
import { Icon } from "@opencode/ui/icon"
import { IconButton } from "@opencode/ui/icon-button"
import { Tabs } from "@opencode/ui/tabs"
import { createEffect, createMemo, on, onMount, Show, type ParentProps } from "solid-js"
import { createStore } from "solid-js/store"
import { useLanguage } from "@/runtime/i18n/language"
import { SessionPreview } from "@/session/story-model"
const timelineDetail = timelinePresets[2].value
type Turn = "three" | "research" | "fetch" | "empty" | "failed" | "streaming"
type SourcesArgs = { turn: Turn; icons: SiteIconMode; panel: boolean; expand: boolean }
const user = "msg_sources_user"
// Results as the websearch tool writes them into its text content (packages/core/src/tool/plugin/websearch.ts).
const searchText = (results: readonly Result[]) =>
results.length
? results.map((result) => `## [${result.title}](${result.url})\n\n${result.title}.`).join("\n\n")
: "No search results found. Please try a different query."
type Result = { url: string; title: string }
let clock = 0
const time = () => {
clock += 1_000
return { created: STORY_TIME + clock, ran: STORY_TIME + clock + 100, completed: STORY_TIME + clock + 900 }
}
const search = (id: string, query: string, results: readonly Result[]): SessionMessageAssistantTool => ({
type: "tool",
id,
name: "websearch",
state: {
status: "completed",
input: { query },
content: [{ type: "text", text: searchText(results) }],
metadata: { provider: "exa" },
},
time: time(),
})
const failedSearch = (id: string, query: string, message: string): SessionMessageAssistantTool => ({
type: "tool",
id,
name: "websearch",
state: { status: "error", input: { query }, error: { type: "ToolExecutionError", message } },
time: time(),
})
const fetch = (id: string, url: string): SessionMessageAssistantTool => ({
type: "tool",
id,
name: "webfetch",
state: {
status: "completed",
input: { url, format: "markdown" },
content: [{ type: "text", text: "# Page" }],
},
time: time(),
})
const three = [
{ url: "https://eieio.games/blog/one-million-checkboxes", title: "One Million Checkboxes – eieio.games" },
{
url: "https://www.theverge.com/2024/7/2/24190811/one-million-checkboxes-website",
title: "One Million Checkboxes is the internet’s newest shared toy",
},
{
url: "https://www.nytimes.com/2024/07/03/technology/one-million-checkboxes-game.html",
title: "The Website With One Million Checkboxes",
},
]
const sites = [
"eieio.games",
"github.com",
"news.ycombinator.com",
"theverge.com",
"nytimes.com",
"washingtonpost.com",
"rockpapershotgun.com",
"itseieio.substack.com",
"youtube.com",
"x.com",
"reddit.com",
"wikipedia.org",
"arstechnica.com",
"pcgamer.com",
"polygon.com",
"techcrunch.com",
]
const queries = [
"10,000 checkboxes massively multiplayer",
'"10000 checkboxes" OR "10,000 checkboxes" game',
"live updating shared components website viral",
"Nolen Royalty eieio.games games",
"Nolen Royalty One Million Chessboards",
'"Nolen Royalty" OR itseieio games OR projects',
"one million checkboxes scaling redis writeup",
"one million chessboards architecture rust",
"GLOBAL CAPS LOCK website",
"Solitaire Alone Together windows 98",
"snakes.run multiplayer snake ssh",
"Faviconic pong browser tabs",
]
const topics = [
"One Million Checkboxes",
"10,000 Checkboxes",
"Shared live websites",
"eieio games",
"One Million Chessboards",
"Nolen Royalty",
"Scaling One Million Checkboxes",
"A million realtime chessboards",
"GLOBAL CAPS LOCK",
"Solitaire Alone Together",
"snakes.run",
"Faviconic",
]
const titles = [
(topic: string) => topic,
(topic: string) => `${topic}: the story behind the viral site`,
(topic: string) => `Show HN: ${topic}`,
(topic: string) => `What happened to ${topic}?`,
(topic: string) => `${topic} is the internet’s newest shared toy`,
(topic: string) => `How ${topic} handled a million players`,
(topic: string) => `${topic} — a technical writeup`,
(topic: string) => `I played ${topic} for a week`,
]
// Twelve searches with 97 results between them, some repeating a page another search found.
const research = queries.map((query, index) =>
search(
`call_research_${index}`,
query,
Array.from({ length: index === 0 ? 15 : index % 3 === 0 ? 6 : 8 }, (_, item) => {
const site = sites[(index * 5 + item) % sites.length]!
const slug = query
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
return {
url: `https://${item % 4 === 0 ? "www." : ""}${site}/${item % 5 === 0 ? "about" : `${slug}-${item}`}`,
title: titles[(index + item) % titles.length]!(topics[index]!),
}
}),
),
)
const answer = (text: string) => ({ type: "text" as const, text })
function document(turn: Turn): SessionDocument {
clock = 0
const busy = turn === "streaming"
const content: SessionMessageAssistant["content"] =
turn === "three" || turn === "streaming"
? [
search("call_three", "one million checkboxes creator", three),
answer(
busy
? "The project you’re thinking of is **One Million Checkboxes**, made by Nolen Royalty"
: "The project you’re thinking of is **One Million Checkboxes**, made by Nolen Royalty (eieio) in June 2024. Checking a box checked it for everyone on the site at once, and it went viral within days.",
),
]
: turn === "research"
? [
...research.slice(0, 6),
fetch("call_fetch_home", "https://eieio.games/"),
...research.slice(6),
fetch("call_fetch_chess", "https://eieio.games/blog/a-million-realtime-chessboards-in-a-single-process"),
answer(
"Nolen Royalty (eieio) makes massively multiplayer toys: **One Million Checkboxes** (2024), **One Million Chessboards** (2025), GLOBAL CAPS LOCK, Solitaire Alone Together and snakes.run. His blog has the technical writeups for each.",
),
]
: turn === "fetch"
? [
fetch("call_fetch_post", "https://eieio.games/blog/one-million-checkboxes"),
fetch("call_fetch_repo", "https://github.com/nolenroyalty/one-million-checkboxes"),
answer("The post covers the launch, and the repository has the Flask and Redis server it ran on."),
]
: turn === "empty"
? [
search("call_empty", "nolen royalty 10,000 checkboxes 2019 prototype", []),
answer(
"I couldn’t find an earlier 10,000-checkbox prototype; the first version was One Million Checkboxes.",
),
]
: [
failedSearch("call_failed", "one million checkboxes creator", "Web search rate limited (HTTP 429)"),
answer("The search was rate limited, so this comes from what I already know: it was Nolen Royalty."),
]
const messages: SessionMessageInfo[] = [
{
id: user,
type: "user",
text: "Who makes the 10,000 checkboxes thing, and what else have they built?",
time: { created: STORY_TIME },
metadata: { agent: "build", model: STORY_MODEL },
},
{
id: "msg_sources_assistant",
type: "assistant",
agent: "build",
model: STORY_MODEL,
content,
time: { created: STORY_TIME + 500, completed: busy ? undefined : STORY_TIME + 60_000 },
},
]
return { sessionID: CURRENT_SESSION_ID, messages, status: { type: busy ? "busy" : "idle" }, diffs: [] }
}
function Sources(props: SourcesArgs) {
const [state, setState] = createStore({ panel: props.panel })
const value = createMemo(() => document(props.turn))
const sources = createMemo(() => turnSources(turnMessages(value().messages, user)))
createEffect(
on(
() => props.panel,
(panel) => setState("panel", panel),
{ defer: true },
),
)
return (
<SourcesProvider enabled icons={props.icons} onOpen={() => setState("panel", true)}>
<SessionPreview
title="Who makes the 10,000 checkboxes thing?"
description="opencode · sources"
document={value()}
timelineDetail={timelineDetail}
side={
<Show when={state.panel}>
<Side expand={props.expand} count={sources().sources.length} onClose={() => setState("panel", false)}>
<SourcesPanel sources={sources()} icons={props.icons} onOpen={() => {}} />
</Side>
</Show>
}
/>
</SourcesProvider>
)
}
// The side panel's frame around the real panel: the strip with the real tab title, as the side region draws it.
// `expand` opens the first search with results once it shows.
function Side(props: ParentProps<{ expand: boolean; count: number; onClose: () => void }>) {
const language = useLanguage()
let el: HTMLDivElement | undefined
onMount(() => {
if (!props.expand) return
requestAnimationFrame(() =>
el?.querySelector<HTMLButtonElement>('[data-slot="sources-step-row"][aria-expanded="false"]')?.click(),
)
})
return (
<Tabs value="sources" class="flex h-full min-h-0 flex-col bg-v2-background-bg-base">
<div class="session-review-v2-tabs-bar sticky top-0 shrink-0 flex items-center">
<Tabs.List>
<Tabs.Trigger
value="sources"
closeButton={
<IconButton
size="small"
variant="ghost-muted"
icon={<Icon name="xmark-small" />}
aria-label={language.t("common.closeTab")}
onClick={() => props.onClose()}
/>
}
hideCloseButton
>
<SourcesTitle count={props.count} />
</Tabs.Trigger>
</Tabs.List>
</div>
<div ref={el} class="flex min-h-0 flex-1 flex-col">
<div class="min-h-0 flex-1 overflow-y-auto" data-scrollable>
{props.children}
</div>
</div>
</Tabs>
)
}
export default {
title: "OpenCode/Session/Sources",
id: "session-sources",
render: (args: SourcesArgs) => <Sources {...args} />,
args: { turn: "three", icons: "letters", panel: false, expand: false },
argTypes: {
turn: { options: ["three", "research", "fetch", "empty", "failed", "streaming"] },
icons: { options: ["letters", "site"] },
},
parameters: {
layout: "fullscreen",
motion: ["Sources"],
},
}
export const ThreeSources = { args: { turn: "three", panel: false } }
export const LongResearch = { args: { turn: "research", panel: false } }
export const LongResearchPanel = { args: { turn: "research", panel: true, expand: true } }
export const FetchOnly = { args: { turn: "fetch", panel: true } }
export const NoResults = { args: { turn: "empty", panel: true } }
export const FailedSearch = { args: { turn: "failed", panel: true } }
export const Streaming = { args: { turn: "streaming", panel: false } }
export const LetterIcons = { args: { turn: "research", panel: true, icons: "letters" } }
export const SiteIcons = { args: { turn: "research", panel: true, icons: "site" } }
+2
View File
@@ -671,6 +671,7 @@ export const builtins = Extension.compose(
{ ...ssh, main: () => import("./ssh/main") },
{ ...wsl, main: () => import("./wsl/main") },
microsoftOffice,
sources,
)
```
@@ -697,6 +698,7 @@ export const builtins = Extension.compose(
{ ...ssh, renderer: eager(sshRenderer) },
{ ...wsl, renderer: eager(wslRenderer) },
{ ...microsoftOffice, renderer: eager(microsoftOfficeRenderer) },
{ ...sources, renderer: eager(sourcesRenderer) },
)
```
+2
View File
@@ -12,6 +12,7 @@ import updater from "./updater"
import ssh from "./ssh"
import wsl from "./wsl"
import microsoftOffice from "./microsoft-office"
import sources from "./sources"
/**
* Built-in extensions with their main entries. Lists every built-in so their ids stay reserved. `builtins.typecheck.ts`
@@ -31,4 +32,5 @@ export const builtins = Extension.compose(
{ ...ssh, main: () => import("./ssh/main") },
{ ...wsl, main: () => import("./wsl/main") },
microsoftOffice,
sources,
)
+3
View File
@@ -25,6 +25,8 @@ import wsl from "./wsl"
import wslRenderer from "./wsl/renderer"
import microsoftOffice from "./microsoft-office"
import microsoftOfficeRenderer from "./microsoft-office/renderer"
import sources from "./sources"
import sourcesRenderer from "./sources/renderer"
// The window renders once every built-in is active, so the small renderer entries load with the app, like the
// features they replaced. Heavy UI stays behind `lazy()` inside them.
@@ -49,4 +51,5 @@ export const builtins = Extension.compose(
{ ...ssh, renderer: eager(sshRenderer) },
{ ...wsl, renderer: eager(wslRenderer) },
{ ...microsoftOffice, renderer: eager(microsoftOfficeRenderer) },
{ ...sources, renderer: eager(sourcesRenderer) },
)
@@ -0,0 +1,3 @@
export default {
"tab.count": "Sources · {{count}}",
}
@@ -0,0 +1,10 @@
import { Browser } from "../browser/contract"
import { Extension } from "../sdk"
import en from "./i18n/en"
export default Extension.define({
id: "sources",
// Results open in the desktop browser pane when there is one, else in the system browser.
uses: { browser: Browser },
i18n: { en },
})
@@ -0,0 +1,29 @@
import { createMemo } from "solid-js"
import { turnMessages, turnSources } from "@opencode/session-ui/sources"
import { sourcesExperiment } from "@opencode/session-ui/sources/experiment"
import { SourcesPanel } from "@opencode/session-ui/sources/panel"
import { useExtension, type MountedSession } from "../sdk"
import type Sources from "./index"
export default function SourcesTab(props: { session: MountedSession; from: string }) {
const ctx = useExtension<typeof Sources>()
const sources = createMemo(() =>
turnSources(turnMessages(props.session.server.data.session.message.list(props.session.id), props.from)),
)
const open = (url: string) => {
const pane = ctx.uses.browser()
if (pane.status === "active" && pane.value.canOpen(props.session)) return pane.value.open(props.session, url)
ctx.system.openExternal(url)
}
return (
<div class="flex h-full min-h-0 flex-col bg-v2-background-bg-base" data-slot="session-sources-panel">
<div class="min-h-0 flex-1 overflow-y-auto" data-scrollable>
<SourcesPanel sources={sources()} icons={sourcesExperiment.icons} onOpen={open} />
</div>
</div>
)
}
@@ -0,0 +1,94 @@
import { createMemo, lazy, onCleanup, Show, Suspense } from "solid-js"
import { turnMessages, turnSources } from "@opencode/session-ui/sources"
import { sourcesExperiment } from "@opencode/session-ui/sources/experiment"
import { SourcesTitle } from "@opencode/session-ui/sources/title"
import { createKeyed, LinkHandler, onIdle, Panel, type MountedSession, type PanelTab, type Setup } from "../sdk"
import type Sources from "./index"
/**
* The Sources experiment's side panel: one transient tab per turn, keyed by the user message that opened it. The
* timeline's sources chip opens it with a link whose origin is this extension and whose href is that message's ID.
* Turning the experiment off stops listing the tabs, which closes them.
*/
const setup: Setup<typeof Sources> = (ctx) => {
const SourcesTab = lazy(() => import("./panel"))
onCleanup(
onIdle(() => {
if (sourcesExperiment.enabled) void SourcesTab.preload()
}),
)
// Tab objects per session, reused so strip updates and session switches do not rebuild a trigger.
const tabs = new Map<string, Map<string, PanelTab>>()
// Drops the tab objects of sessions whose shell tab closed.
createKeyed(
() => [...ctx.sessions.list().map((session) => session.key), ctx.sessions.current()?.key].join("\u0000"),
() => {
const keep = new Set([...ctx.sessions.list().map((session) => session.key), ctx.sessions.current()?.key])
tabs.forEach((_cache, key) => {
if (!keep.has(key)) tabs.delete(key)
})
},
)
const count = (session: MountedSession, id: string) =>
turnSources(turnMessages(session.server.data.session.message.list(session.id), id)).sources.length
ctx.add(LinkHandler, {
match: (link) => sourcesExperiment.enabled && link.origin === ctx.id && !!link.session,
open(link) {
if (link.session) ctx.layout.open(`${ctx.id}:${link.href}`, link.session, { tab: "select" })
},
})
ctx.add(Panel, {
id: "turn",
region: "side",
transient: true,
list: (input) => {
if (!sourcesExperiment.enabled) {
tabs.delete(input.session.key)
return []
}
const cache = tabs.get(input.session.key) ?? new Map<string, PanelTab>()
tabs.set(input.session.key, cache)
return input.open.map((id) => {
const existing = cache.get(id)
if (existing) return existing
const tab: PanelTab = {
id,
get title() {
return ctx.t("tab.count", { count: count(input.session, id) })
},
label: (state) => {
const total = createMemo(() => count(state.session, id))
return <SourcesTitle count={total()} />
},
}
cache.set(id, tab)
return tab
})
},
render: (props) => (
<Show when={sourcesExperiment.enabled}>
<Suspense>
<SourcesTab session={props.session} from={props.tab.id} />
</Suspense>
</Show>
),
close: (input) => {
tabs.get(input.session.key)?.delete(input.tab.id)
},
})
}
export default setup
+4
View File
@@ -40,6 +40,10 @@
"./pierre/*": "./src/pierre/*.ts",
"./context": "./src/context/index.ts",
"./context/*": "./src/context/*.tsx",
"./sources": "./src/sources/sources.ts",
"./sources/experiment": "./src/sources/experiment.ts",
"./sources/panel": "./src/sources/sources-panel.tsx",
"./sources/title": "./src/sources/sources-title.tsx",
"./styles": "./src/styles/index.css",
"./storybook": "./src/storybook/index.ts",
"./v2/*.css": "./src/v2/components/*.css",
@@ -0,0 +1,34 @@
import { createContext, useContext, type ParentProps } from "solid-js"
import type { SiteIconMode } from "../sources/experiment"
const context = createContext<{
readonly enabled: boolean
readonly icons: SiteIconMode
readonly open: (from: string) => void
}>()
/**
* Shows a turn's sources chip, which opens the turn's searches and fetches. `open` receives the ID of the user message
* that opened the turn. Without this provider no chip shows.
*/
export function SourcesProvider(
props: ParentProps<{ enabled: boolean; icons: SiteIconMode; onOpen: (from: string) => void }>,
) {
return (
<context.Provider
value={{
get enabled() {
return props.enabled
},
get icons() {
return props.icons
},
open: (from) => props.onOpen(from),
}}
>
{props.children}
</context.Provider>
)
}
export const useSources = () => useContext(context)
@@ -12,6 +12,7 @@ import {
import { currentToolError, currentToolInput, currentToolMetadata, currentToolOutput } from "./current-tool-state"
import { currentStreamingInput } from "./streaming-input"
import type { UserRun } from "../timeline/user-runs"
import type { TurnSources } from "../sources/sources"
// Registers the genui_render renderer with the tool registry.
import "../genui/tool"
@@ -55,6 +56,8 @@ export function SessionAssistantContent(props: {
contentID: string
showAssistantCopyPartID?: string | null
turnDurationMs?: number | null
sources?: TurnSources
onOpenSources?: () => void
defaultOpen?: boolean
reasoningDefaultOpen?: boolean
toolOpen?: boolean
@@ -71,6 +74,8 @@ export function SessionAssistantContent(props: {
message={props.message}
showCopy={props.showAssistantCopyPartID === props.contentID}
turnDurationMs={props.turnDurationMs}
sources={props.sources}
onOpenSources={props.onOpenSources}
/>
)}
</Match>
@@ -6,6 +6,7 @@ import {
Index,
on,
onCleanup,
onMount,
Show,
untrack,
type ComponentProps,
@@ -21,6 +22,9 @@ import { linkSegments } from "../components/link-segments"
import { sessionReferenceText, setupSessionLinks } from "../components/markdown-session-links"
import { useMarkdown } from "../context/markdown"
import { useMessageMenu } from "../context/message-menu"
import { useSources } from "../context/sources"
import { SourcesChip } from "../sources/sources-chip"
import type { TurnSources } from "../sources/sources"
import { ImagePreview } from "@opencode/ui/image-preview"
import { getFilename } from "@opencode/util/path"
import { AttachmentCard } from "./attachment-card"
@@ -897,11 +901,19 @@ export function AssistantTextContent(props: {
message: SessionMessageAssistant
showCopy: boolean
turnDurationMs?: number | null
/** The finished turn's web searches and fetches, shown as a chip in its footer. */
sources?: TurnSources
onOpenSources?: () => void
}) {
const data = useData()
const i18n = useI18n()
const menu = useMessageMenu()
const sourcesHost = useSources()
const numfmt = createMemo(() => new Intl.NumberFormat(i18n.locale()))
// A footer that arrives after the reply rendered belongs to a turn that just finished, so its chip fades in.
let rendered = false
onMount(() => (rendered = true))
const sources = () => (props.showCopy && sourcesHost?.enabled ? props.sources : undefined)
const interrupted = () => {
const type = props.message.error?.type.toLowerCase()
@@ -971,39 +983,55 @@ export function AssistantTextContent(props: {
<Menu.Item onSelect={() => void copy()}>{i18n.t("ui.message.copyResponse")}</Menu.Item>
</MessageOptions>
</Show>
<Show when={!menu() && props.showCopy}>
<div data-slot="text-part-copy-wrapper" data-interrupted={interrupted() ? "" : undefined}>
<MessageActionButton
icon={copied() ? "check" : "copy"}
size="small"
label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
onMouseDown={(event) => event.preventDefault()}
onClick={copy}
aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
/>
<Show when={meta().length > 0}>
<span data-slot="text-part-meta">
<For each={meta()}>
{(label, index) => (
<>
<Show when={index() > 0}>
<span data-slot="text-part-meta-separator" aria-hidden="true">
{"\u00B7"}
</span>
</Show>
<span data-slot="text-part-meta-item" dir="auto">
{label}
</span>
</>
)}
</For>
</span>
</Show>
</div>
<Show when={sources()} fallback={<Show when={!menu() && props.showCopy}>{copyFooter()}</Show>}>
{(value) => (
<div data-slot="text-part-footer">
<SourcesChip
sources={value()}
icons={sourcesHost?.icons ?? "letters"}
appear={rendered}
onOpen={() => props.onOpenSources?.()}
/>
<Show when={!menu()}>{copyFooter()}</Show>
</div>
)}
</Show>
</div>
</Show>
)
function copyFooter() {
return (
<div data-slot="text-part-copy-wrapper" data-interrupted={interrupted() ? "" : undefined}>
<MessageActionButton
icon={copied() ? "check" : "copy"}
size="small"
label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
onMouseDown={(event) => event.preventDefault()}
onClick={copy}
aria-label={copied() ? i18n.t("ui.message.copied") : i18n.t("ui.message.copyResponse")}
/>
<Show when={meta().length > 0}>
<span data-slot="text-part-meta">
<For each={meta()}>
{(label, index) => (
<>
<Show when={index() > 0}>
<span data-slot="text-part-meta-separator" aria-hidden="true">
{"\u00B7"}
</span>
</Show>
<span data-slot="text-part-meta-item" dir="auto">
{label}
</span>
</>
)}
</For>
</span>
</Show>
</div>
)
}
}
export function AssistantReasoningContent(props: {
@@ -0,0 +1,57 @@
import { motionTuning } from "@opencode/ui/motion-tuning"
import { createStore } from "solid-js/store"
export type SiteIconMode = "letters" | "site"
const enabled = motionTuning.toggle("sources.enabled", {
label: "Enabled",
group: "Experiments",
subsection: "Sources",
experiment: true,
value: false,
})
// A site's own icon is fetched from that site, which tells it the page was looked at; letters stay on this device.
const icons = motionTuning.choice("sources.icons", {
label: "Site icons",
group: "Experiments",
subsection: "Sources",
when: enabled,
value: "letters",
labels: { letters: "Letters", site: "Site icon" },
})
/** The chip fading in as its turn finishes. */
export const sourcesFade = motionTuning.spring("sources.fade", {
label: "Fade in",
group: "Experiments",
subsection: "Sources",
when: enabled,
shipped: "smooth",
presets: {
snappy: { duration: 0.2, bounce: 0 },
smooth: { duration: 0.3, bounce: 0 },
calm: { duration: 0.45, bounce: 0 },
},
})
/** A search opening to its results, and closing again. */
export const sourcesExpand = motionTuning.spring("sources.expand", {
label: "Expand",
group: "Experiments",
subsection: "Sources",
when: enabled,
shipped: "smooth",
presets: {
snappy: { duration: 0.25, bounce: 0 },
smooth: { duration: 0.35, bounce: 0 },
calm: { duration: 0.45, bounce: 0 },
},
})
const [state, setState] = createStore({ enabled: enabled(), icons: icons() })
motionTuning.subscribe(() => setState({ enabled: enabled(), icons: icons() }))
/** Experiment: a "N sources" chip under a reply that searched the web, opening the turn's searches in the side panel. */
export const sourcesExperiment = state
@@ -0,0 +1,53 @@
import { createSignal, Show } from "solid-js"
import type { SiteIconMode } from "./experiment"
// The project avatar colours, so a site's tile reads like the rest of the app's letter tiles in light and dark.
const colors = ["orange", "yellow", "cyan", "green", "red", "pink", "blue", "purple"]
// Hosts whose favicon failed this session, so every later tile for them shows its letter at once.
const failed = new Set<string>()
/** A site's letter tile, or with `site` its own favicon over the tile, falling back to the letter if that fails. */
export function SiteIcon(props: { site: string; host: string; mode: SiteIconMode }) {
const [state, setState] = createSignal<"loading" | "loaded" | "failed">(failed.has(props.host) ? "failed" : "loading")
const favicon = () => props.mode === "site" && state() !== "failed"
return (
<span
data-component="site-icon"
data-state={favicon() ? state() : undefined}
aria-hidden="true"
style={{
"--site-icon-bg": `var(--v2-avatar-bg-${colors[hash(props.site) % colors.length]})`,
}}
>
<Show when={favicon()} fallback={letter(props.site)}>
<img
data-slot="site-icon-image"
src={`https://${props.host}/favicon.ico`}
alt=""
draggable={false}
referrerPolicy="no-referrer"
onLoad={(event) => {
if (event.currentTarget.naturalWidth > 0) return setState("loaded")
failed.add(props.host)
setState("failed")
}}
onError={() => {
failed.add(props.host)
setState("failed")
}}
/>
</Show>
</span>
)
}
function letter(site: string) {
return Array.from(site)[0]?.toUpperCase() ?? ""
}
// FNV-1a, so a site keeps its colour everywhere it shows.
function hash(value: string) {
return Array.from(value).reduce((sum, char) => Math.imul(sum ^ char.codePointAt(0)!, 16777619) >>> 0, 2166136261)
}
@@ -0,0 +1,57 @@
import { useI18n } from "@opencode/ui/context/i18n"
import { Icon } from "@opencode/ui/icon"
import { frameLoop, prefersReducedMotion, Spring } from "@opencode/ui/motion"
import { createMemo, For, onCleanup, onMount, Show } from "solid-js"
import { sourcesFade, type SiteIconMode } from "./experiment"
import { SiteIcon } from "./site-icon"
import type { TurnSources } from "./sources"
import "./sources.css"
/**
* "N sources" under a reply, with the first three sites stacked. `appear` fades it in, for a turn that finished while
* it was on screen; a turn that was already done shows it at rest.
*/
export function SourcesChip(props: { sources: TurnSources; icons: SiteIconMode; appear: boolean; onOpen: () => void }) {
const i18n = useI18n()
let button: HTMLButtonElement | undefined
const sites = createMemo(() =>
props.sources.sources
.filter((source, index, all) => all.findIndex((item) => item.site === source.site) === index)
.slice(0, 3),
)
onMount(() => {
if (!props.appear || !button) return
const el = button
const spring = Spring.fromDuration(0, prefersReducedMotion() ? { duration: 0.15, bounce: 0 } : sourcesFade())
spring.set(1)
el.style.opacity = "0"
onCleanup(
frameLoop.add((dt) => {
el.style.opacity = String(spring.step(dt))
if (!spring.resting) return true
el.style.opacity = ""
return false
}),
)
})
return (
<button ref={button} type="button" data-component="sources-chip" onClick={() => props.onOpen()}>
<span data-slot="sources-chip-icons">
<Show when={props.sources.sources.length > 0} fallback={<Icon name="globe" size="small" />}>
<For each={sites()}>{(source) => <SiteIcon site={source.site} host={source.host} mode={props.icons} />}</For>
</Show>
</span>
<span data-slot="sources-chip-label">
{props.sources.sources.length > 0
? i18n.plural("ui.sources.count", props.sources.sources.length)
: i18n.t("ui.sources.none")}
</span>
</button>
)
}
@@ -0,0 +1,193 @@
import { useI18n } from "@opencode/ui/context/i18n"
import { Icon } from "@opencode/ui/icon"
import { frameLoop, prefersReducedMotion, Spring } from "@opencode/ui/motion"
import { createSignal, For, Match, onCleanup, Show, Switch } from "solid-js"
import { sourcesExpand, type SiteIconMode } from "./experiment"
import { SiteIcon } from "./site-icon"
import type { SourceResult, SourceStep, TurnSources } from "./sources"
import "./sources.css"
/** A turn's searches and opened pages in the order they ran. `onOpen` opens a result's or page's URL. */
export function SourcesPanel(props: { sources: TurnSources; icons: SiteIconMode; onOpen: (url: string) => void }) {
return (
<div data-component="sources-panel">
<For each={props.sources.steps}>
{(step) => (
<Switch>
<Match when={step.type === "search" ? step : undefined}>
{(search) => <SearchStep step={search()} icons={props.icons} onOpen={props.onOpen} />}
</Match>
<Match when={step.type === "fetch" ? step : undefined}>
{(page) => <FetchStep step={page()} onOpen={props.onOpen} />}
</Match>
</Switch>
)}
</For>
</div>
)
}
function SearchStep(props: {
step: Extract<SourceStep, { type: "search" }>
icons: SiteIconMode
onOpen: (url: string) => void
}) {
const i18n = useI18n()
const [state, setState] = createSignal({ open: false, mounted: false })
const expandable = () => props.step.results.length > 0
let region: HTMLDivElement | undefined
let list: HTMLDivElement | undefined
let stop: (() => void) | undefined
// Height follows one spring; opening again mid-close keeps its velocity.
const spring = new Spring(0)
onCleanup(() => stop?.())
const toggle = () => {
const open = !state().open
setState({ open, mounted: true })
if (!region || !list) return
const el = region
// Layout is read once per toggle, never per frame: the results' height, now that they render, and where a
// resting region starts from. A moving one starts from its spring.
const height = open ? list.offsetHeight : 0
if (!stop) spring.snap(el.offsetHeight)
stop?.()
stop = undefined
if (prefersReducedMotion()) {
spring.snap(height)
el.style.height = open ? "" : "0px"
if (open) fadeIn(list)
if (!open) setState({ open, mounted: false })
return
}
const options = sourcesExpand()
spring.omega = (2 * Math.PI) / options.duration
spring.zeta = 1 - options.bounce
spring.set(height)
el.dataset.moving = ""
stop = frameLoop.add((dt) => {
el.style.height = `${spring.step(dt)}px`
if (!spring.resting) return true
delete el.dataset.moving
el.style.height = open ? "" : "0px"
stop = undefined
if (!open) setState({ open, mounted: false })
return false
})
}
return (
<div data-slot="sources-step" data-open={state().open ? "" : undefined}>
<button
type="button"
data-slot="sources-step-row"
aria-expanded={expandable() ? state().open : undefined}
disabled={!expandable()}
onClick={toggle}
>
<span data-slot="sources-step-icon">
<Icon name="magnifying-glass" size="small" />
</span>
<span data-slot="sources-step-text">
<span data-slot="sources-step-label">
{i18n.t(props.step.status === "error" ? "ui.sources.searchFailed" : "ui.sources.searched")}
</span>
<span data-slot="sources-step-detail">{props.step.query}</span>
<Show when={props.step.error}>{(error) => <span data-slot="sources-step-error">{error()}</span>}</Show>
</span>
<Show when={props.step.status === "completed"}>
<span data-slot="sources-step-count" data-empty={expandable() ? undefined : ""}>
{expandable() ? props.step.results.length : i18n.t("ui.sources.noResults")}
</span>
</Show>
</button>
<div ref={region} data-slot="sources-step-results" style={{ height: "0px" }}>
<div ref={list} data-slot="sources-step-list">
<Show when={state().mounted}>
<For each={props.step.results}>
{(result) => <ResultRow result={result} icons={props.icons} onOpen={props.onOpen} />}
</For>
</Show>
</div>
</div>
</div>
)
}
function ResultRow(props: { result: SourceResult; icons: SiteIconMode; onOpen: (url: string) => void }) {
return (
<a
data-slot="sources-result"
href={props.result.url}
title={props.result.url}
onClick={(event) => {
event.preventDefault()
props.onOpen(props.result.url)
}}
>
<SiteIcon site={props.result.site} host={props.result.host} mode={props.icons} />
<span data-slot="sources-result-text">
<span data-slot="sources-result-title">{props.result.title ?? props.result.url}</span>
<span data-slot="sources-result-site">{props.result.site}</span>
</span>
</a>
)
}
function FetchStep(props: { step: Extract<SourceStep, { type: "fetch" }>; onOpen: (url: string) => void }) {
const i18n = useI18n()
return (
<div data-slot="sources-step">
<a
data-slot="sources-step-row"
href={props.step.url}
title={props.step.url}
onClick={(event) => {
event.preventDefault()
props.onOpen(props.step.url)
}}
>
<span data-slot="sources-step-icon">
<Icon name="window-cursor" size="small" />
</span>
<span data-slot="sources-step-text">
<span data-slot="sources-step-label">
{i18n.t(props.step.status === "error" ? "ui.sources.openFailed" : "ui.sources.opened")}
</span>
<span data-slot="sources-step-detail">
{props.step.site}
<span data-slot="sources-step-path">{props.step.path}</span>
</span>
<Show when={props.step.error}>{(error) => <span data-slot="sources-step-error">{error()}</span>}</Show>
</span>
</a>
</div>
)
}
// Reduced motion trades the height for a short fade.
function fadeIn(el: HTMLElement) {
const spring = Spring.fromDuration(0, { duration: 0.15, bounce: 0 })
spring.set(1)
el.style.opacity = "0"
frameLoop.add((dt) => {
el.style.opacity = String(spring.step(dt))
if (!spring.resting) return true
el.style.opacity = ""
return false
})
}
@@ -0,0 +1,21 @@
import { useI18n } from "@opencode/ui/context/i18n"
import { Icon } from "@opencode/ui/icon"
import { Show } from "solid-js"
/** The Sources panel's title in its side-panel tab: "Sources · 87". */
export function SourcesTitle(props: { count: number }) {
const i18n = useI18n()
return (
<div class="flex min-w-0 items-center gap-1.5">
<Icon name="globe" class="shrink-0" />
<span class="truncate">{i18n.t("ui.sources.title")}</span>
<Show when={props.count > 0}>
<span class="shrink-0 text-v2-text-text-faint" aria-hidden="true">
·
</span>
<span class="shrink-0 tabular-nums text-v2-text-text-faint">{props.count}</span>
</Show>
</div>
)
}
+266
View File
@@ -0,0 +1,266 @@
[data-component="site-icon"] {
--site-icon-size: 16px;
position: relative;
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: var(--site-icon-size);
height: var(--site-icon-size);
overflow: hidden;
border-radius: 9999px;
background-color: var(--site-icon-bg);
box-shadow: inset 0 0 0 0.5px var(--v2-alpha-dark-12);
color: var(--v2-avatar-fg);
font-family: var(--font-family-sans);
font-size: 9px;
font-weight: var(--font-weight-medium);
line-height: 1;
user-select: none;
&[data-state] {
background-color: var(--v2-background-bg-layer-02);
}
[data-slot="site-icon-image"] {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: opacity 150ms ease-out;
}
&[data-state="loaded"] [data-slot="site-icon-image"] {
opacity: 1;
}
}
:root[data-motion="reduce"] [data-component="site-icon"] [data-slot="site-icon-image"] {
transition: none;
}
[data-component="sources-chip"] {
display: inline-flex;
flex: none;
align-items: center;
gap: 6px;
height: 20px;
padding-inline: 2px 8px;
border-radius: 9999px;
background-color: var(--v2-overlay-simple-overlay-hover);
color: var(--v2-text-text-muted);
font-family: var(--v2-font-family-sans);
font-size: 12px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: 0.05px;
white-space: nowrap;
cursor: default;
transition:
background-color 150ms ease-out,
color 150ms ease-out;
&:hover,
&:focus-visible {
background-color: var(--v2-overlay-simple-overlay-pressed);
color: var(--v2-text-text-base);
}
&:focus-visible {
outline: 1px solid var(--v2-border-border-focus);
outline-offset: 1px;
}
[data-slot="sources-chip-icons"] {
display: inline-flex;
align-items: center;
> [data-slot="icon-svg"] {
margin-inline-start: 4px;
color: var(--v2-text-text-faint);
}
}
/* Each later site tucks under the one before it, cut by a mask so the gap shows whatever is behind the chip. */
[data-component="site-icon"] + [data-component="site-icon"] {
margin-inline-start: -3px;
mask-image: radial-gradient(circle at -5px 50%, transparent 9.5px, #000 10px);
}
}
:root[data-motion="reduce"] [data-component="sources-chip"] {
transition: none;
}
/* The turn's footer, set off from the reply by the same gap as its changed-files footer (`session-turn-diffs`). */
[data-component="text-part"] [data-slot="text-part-footer"] {
display: flex;
align-items: center;
gap: 8px;
min-height: 20px;
margin-top: 16px;
> [data-slot="text-part-copy-wrapper"] {
flex: 1;
min-width: 0;
margin-top: 0;
}
}
[data-component="sources-panel"] {
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px;
[data-slot="sources-step-row"] {
display: grid;
grid-template-columns: 16px minmax(0, 1fr) auto;
column-gap: 10px;
width: 100%;
padding: 8px;
border-radius: 8px;
color: inherit;
text-align: start;
text-decoration: none;
cursor: default;
transition: background-color 150ms ease-out;
&:not(:disabled):hover,
&:focus-visible {
background-color: var(--v2-overlay-simple-overlay-hover);
}
&:focus-visible {
outline: 1px solid var(--v2-border-border-focus);
outline-offset: -1px;
}
}
[data-slot="sources-step-icon"] {
display: flex;
align-items: center;
height: 16px;
color: var(--v2-text-text-faint);
}
[data-slot="sources-step-text"] {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
[data-slot="sources-step-label"] {
font-size: 12px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: 0.05px;
color: var(--v2-text-text-faint);
}
[data-slot="sources-step-detail"],
[data-slot="sources-result-title"],
[data-slot="sources-result-site"] {
overflow: hidden;
white-space: nowrap;
mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent);
}
[data-slot="sources-step-detail"] {
font-family: var(--font-family-mono);
font-size: 13px;
font-weight: 440;
line-height: var(--line-height-compact);
letter-spacing: -0.04px;
color: var(--v2-text-text-base);
}
[data-slot="sources-step-path"] {
color: var(--v2-text-text-muted);
}
[data-slot="sources-step-error"] {
font-size: 12px;
line-height: var(--line-height-compact);
color: var(--v2-state-fg-danger);
}
[data-slot="sources-step-count"] {
align-self: start;
height: 16px;
font-size: 12px;
font-weight: 440;
line-height: var(--line-height-compact);
font-variant-numeric: tabular-nums;
color: var(--v2-text-text-faint);
}
[data-slot="sources-step"][data-open] [data-slot="sources-step-count"] {
color: var(--v2-text-text-base);
}
[data-slot="sources-step-results"] {
overflow: clip;
&[data-moving] {
mask-image: linear-gradient(to bottom, #000 calc(100% - 16px), transparent);
}
}
[data-slot="sources-step-list"] {
display: flex;
flex-direction: column;
padding-block: 2px 6px;
}
/* The site icon sits on the step's text edge; the row's highlight bleeds out past it. */
[data-slot="sources-result"] {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
column-gap: 10px;
margin-inline-start: 26px;
padding: 6px 8px;
border-radius: 8px;
color: inherit;
text-decoration: none;
cursor: default;
transition: background-color 150ms ease-out;
&:hover,
&:focus-visible {
background-color: var(--v2-overlay-simple-overlay-hover);
}
&:focus-visible {
outline: 1px solid var(--v2-border-border-focus);
outline-offset: -1px;
}
}
[data-slot="sources-result-text"] {
display: flex;
flex-direction: column;
min-width: 0;
}
[data-slot="sources-result-title"] {
font-size: 13px;
line-height: var(--line-height-compact);
color: var(--v2-text-text-base);
}
[data-slot="sources-result-site"] {
font-size: 12px;
line-height: var(--line-height-compact);
letter-spacing: 0.05px;
color: var(--v2-text-text-faint);
}
}
:root[data-motion="reduce"] [data-component="sources-panel"] {
[data-slot="sources-step-row"],
[data-slot="sources-result"] {
transition: none;
}
}
@@ -0,0 +1,172 @@
import type { SessionMessageAssistant, SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise"
import { describe, expect, test } from "bun:test"
import { turnMessages, turnSources } from "./sources"
const model = { id: "claude-sonnet-4", providerID: "anthropic" }
// The text content the websearch tool writes for its results (packages/core/src/tool/plugin/websearch.ts).
const searchText = (results: { url: string; title?: string; content?: string }[]) =>
results.length
? results
.map(
(result) =>
`## [${result.title ?? result.url}](${result.url})${result.content ? `\n\n${result.content}` : ""}`,
)
.join("\n\n")
: "No search results found. Please try a different query."
const search = (id: string, query: string, results: { url: string; title?: string; content?: string }[]) =>
({
type: "tool",
id,
name: "websearch",
state: {
status: "completed",
input: { query },
content: [{ type: "text", text: searchText(results) }],
metadata: { provider: "exa" },
},
time: { created: 1, ran: 2, completed: 3 },
}) satisfies SessionMessageAssistantTool
const fetch = (id: string, url: string, error?: string) =>
({
type: "tool",
id,
name: "webfetch",
state: error
? { status: "error", input: { url, format: "markdown" }, error: { type: "ToolExecutionError", message: error } }
: { status: "completed", input: { url, format: "markdown" }, content: [{ type: "text", text: "# Page" }] },
time: { created: 1, ran: 2, completed: 3 },
}) satisfies SessionMessageAssistantTool
const assistant = (id: string, content: SessionMessageAssistant["content"]): SessionMessageAssistant => ({
id,
type: "assistant",
agent: "build",
model,
content,
time: { created: 1, completed: 4 },
})
describe("turnSources", () => {
test("lists searches and fetches across the turn's messages in the order they ran", () => {
const value = turnSources([
assistant("msg_1", [
{ type: "text", text: "Looking." },
search("call_1", "one million checkboxes", [
{ url: "https://eieio.games/blog/one-million-checkboxes", title: "One Million Checkboxes" },
]),
{
type: "tool",
id: "call_read",
name: "read",
state: { status: "completed", input: {}, content: [{ type: "text", text: "x" }] },
time: { created: 1 },
},
]),
assistant("msg_2", [fetch("call_2", "https://www.nytimes.com/2024/07/03/technology/checkboxes.html")]),
])
expect(value.steps.map((step) => [step.type, step.id])).toEqual([
["search", "call_1"],
["fetch", "call_2"],
])
expect(value.steps[0]).toMatchObject({
query: "one million checkboxes",
status: "completed",
results: [{ title: "One Million Checkboxes", site: "eieio.games" }],
})
expect(value.steps[1]).toMatchObject({
site: "nytimes.com",
host: "www.nytimes.com",
path: "/2024/07/03/technology/checkboxes.html",
})
})
test("counts each page once, however its URL was written", () => {
const value = turnSources([
assistant("msg_1", [
search("call_1", "a", [
{ url: "https://eieio.games/", title: "eieio" },
{ url: "https://example.com/post?id=1" },
]),
search("call_2", "b", [
{ url: "https://www.eieio.games", title: "eieio again" },
{ url: "http://example.com/post?id=1#top" },
{ url: "https://example.com/post?id=2" },
]),
fetch("call_3", "https://eieio.games/"),
]),
])
expect(value.sources.map((source) => source.url)).toEqual([
"https://eieio.games/",
"https://example.com/post?id=1",
"https://example.com/post?id=2",
])
})
test("keeps a title only when the tool had one, and skips headings that aren't web links", () => {
const [step] = turnSources([
assistant("msg_1", [
search("call_1", "titles", [
{ url: "https://example.com/a" },
{ url: "https://example.com/b", title: "Notes [draft](v2)", content: "## [Not a result](file:///etc/hosts)" },
]),
]),
]).steps
expect(step?.type === "search" ? step.results.map((result) => [result.url, result.title]) : []).toEqual([
["https://example.com/a", undefined],
["https://example.com/b", "Notes [draft](v2)"],
])
})
test("reads empty and failed searches and failed fetches without inventing sources", () => {
const failed: SessionMessageAssistantTool = {
type: "tool",
id: "call_2",
name: "websearch",
state: {
status: "error",
input: { query: "rate limited" },
error: { type: "ToolExecutionError", message: "Web search rate limited (HTTP 429)" },
},
time: { created: 1, completed: 3 },
}
const value = turnSources([
assistant("msg_1", [
search("call_1", "nothing here", []),
failed,
fetch("call_3", "https://down.example.com/page", "Request failed with status code: 503"),
]),
])
expect(value.steps).toMatchObject([
{ type: "search", status: "completed", results: [] },
{ type: "search", status: "error", results: [], error: "Web search rate limited (HTTP 429)" },
{ type: "fetch", status: "error", error: "Request failed with status code: 503" },
])
expect(value.sources).toEqual([])
})
})
describe("turnMessages", () => {
test("takes the assistant messages after the prompt, up to the next prompt", () => {
const user = (id: string): SessionMessageInfo => ({ id, type: "user", text: id, time: { created: 1 } })
const messages = [
user("msg_u1"),
assistant("msg_a1", []),
assistant("msg_a2", []),
user("msg_u2"),
assistant("msg_a3", []),
]
expect(turnMessages(messages, "msg_u1").map((message) => message.id)).toEqual(["msg_a1", "msg_a2"])
expect(turnMessages(messages, "msg_u2").map((message) => message.id)).toEqual(["msg_a3"])
expect(turnMessages(messages, "msg_missing")).toEqual([])
})
})
+141
View File
@@ -0,0 +1,141 @@
import type { SessionMessageAssistant, SessionMessageAssistantTool, SessionMessageInfo } from "@opencode/client/promise"
import { Option, Schema } from "effect"
import { currentToolError, currentToolInput, currentToolOutput } from "../message/current-tool-state"
const decodeQuery = Schema.decodeUnknownOption(Schema.Struct({ query: Schema.String }))
const decodeURL = Schema.decodeUnknownOption(Schema.Struct({ url: Schema.String }))
export type SourceResult = {
url: string
title?: string
/** The hostname without `www.`, as shown and as the letter tile's seed. */
site: string
/** The full hostname, where its favicon lives. */
host: string
}
type StepStatus = "running" | "completed" | "error"
export type SourceStep =
| { type: "search"; id: string; query: string; status: StepStatus; results: SourceResult[]; error?: string }
| ({ type: "fetch"; id: string; path: string; status: StepStatus; error?: string } & SourceResult)
export type TurnSources = {
steps: SourceStep[]
/** Distinct sources in the order the turn met them: search results and opened pages, deduped by URL. */
sources: SourceResult[]
}
/** The web searches and page fetches of one turn's assistant messages, in the order they ran. */
export function turnSources(messages: readonly SessionMessageAssistant[]): TurnSources {
const steps = messages.flatMap((message) => message.content.flatMap((content) => step(content)))
const seen = new Set<string>()
const sources = steps
.flatMap((item) => (item.type === "search" ? item.results : item.status === "error" ? [] : [item]))
.filter((item) => {
const key = identity(item.url)
if (seen.has(key)) return false
seen.add(key)
return true
})
return { steps, sources }
}
/** The assistant messages of the turn a user message opened, grouped as the timeline groups them. */
export function turnMessages(messages: readonly SessionMessageInfo[], from: string) {
const start = messages.findIndex((message) => message.id === from)
if (start === -1) return []
const end = messages.findIndex(
(message, index) => index > start && (message.type === "user" || message.type === "shell"),
)
return messages
.slice(start + 1, end === -1 ? undefined : end)
.filter((message): message is SessionMessageAssistant => message.type === "assistant")
}
function step(content: SessionMessageAssistant["content"][number]): SourceStep[] {
if (content.type !== "tool" || content.state.status === "streaming") return []
if (content.name === "websearch") return [search(content)]
if (content.name !== "webfetch") return []
const page = Option.getOrUndefined(
decodeURL(currentToolInput(content)).pipe(Option.flatMapNullishOr((input) => source(input.url))),
)
if (!page) return []
return [
{
type: "fetch",
id: content.id,
...page,
path: path(page.url),
status: content.state.status,
error: currentToolError(content),
},
]
}
function search(tool: SessionMessageAssistantTool): SourceStep {
return {
type: "search",
id: tool.id,
query: Option.match(decodeQuery(currentToolInput(tool)), { onNone: () => "", onSome: (input) => input.query }),
status: tool.state.status === "streaming" ? "running" : tool.state.status,
results: tool.state.status === "completed" ? results(currentToolOutput(tool) ?? "") : [],
error: currentToolError(tool),
}
}
// The websearch tool keeps its structured results out of the message and writes each one as a `## [title](url)`
// heading in its text content (packages/core/src/tool/plugin/websearch.ts); a result without a title repeats its URL.
function results(text: string) {
return text.split("\n").flatMap((line): SourceResult[] => {
if (!line.startsWith("## [") || !line.endsWith(")")) return []
const split = line.lastIndexOf("](")
if (split < 4) return []
const result = source(line.slice(split + 2, -1))
if (!result) return []
const title = line.slice(4, split).trim()
return [{ ...result, title: title && title !== result.url ? title : undefined }]
})
}
function source(url: string): SourceResult | undefined {
if (!URL.canParse(url)) return undefined
const parsed = new URL(url)
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return undefined
return { url, host: parsed.hostname, site: parsed.hostname.replace(/^www\./, "") }
}
// One source per page: the scheme, `www.`, a trailing slash and the fragment don't make another.
function identity(url: string) {
const parsed = new URL(url)
return `${parsed.hostname.replace(/^www\./, "")}${parsed.pathname.replace(/\/+$/, "")}${parsed.search}`
}
function path(url: string) {
const parsed = new URL(url)
return `${parsed.pathname.replace(/\/+$/, "")}${parsed.search}`
}
@@ -26,6 +26,8 @@ import { Dynamic } from "solid-js/web"
import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions"
import { useData } from "../context"
import { useMessageMenu } from "../context/message-menu"
import { useSources } from "../context/sources"
import { turnSources } from "../sources/sources"
import { TimelineSeparator } from "../components/timeline-separator"
import {
SessionAssistantContent,
@@ -103,6 +105,7 @@ export function createSessionTimelineRowRenderer(input: {
const i18n = useI18n()
const data = useData()
const menu = useMessageMenu()
const sourcesHost = useSources()
// Cached timelines retain file-change subgroup identities alongside their disclosure choices.
const patchGroupKeys = input.disclosure.patchGroupKeys ?? new Map<string, string>()
const patchPartKeys = new WeakMap<SessionMessageAssistant["content"][number], string>()
@@ -158,6 +161,7 @@ export function createSessionTimelineRowRenderer(input: {
// A steer sent while the timeline is open grows in. Messages already there when a session loads, and rows the
// virtualizer remounts, appear as they are.
const seen = { sessionID: "", ids: new Set<string>() }
const arrivals = createMemo(() => {
const sessionID = input.sessionID()
const loaded = seen.sessionID === sessionID && seen.ids.size > 0
@@ -439,6 +443,19 @@ export function createSessionTimelineRowRenderer(input: {
return item ? contentDefaultOpen(item) : undefined
})
// Only the finished turn's footer part derives them, and only while the host shows sources.
const turnSourcesValue = createMemo(() => {
const current = ref()
if (!sourcesHost?.enabled || !current || copyContentID(row().userMessageID) !== current.partID) return undefined
const value = turnSources(
input.projection.assistantMessagesByParent().get(row().userMessageID) ?? emptyAssistantMessages,
)
return value.steps.length > 0 ? value : undefined
})
const disclosureKey = () => (content()?.type === "reasoning" ? ref()!.partID : row().group.key)
return (
@@ -452,6 +469,8 @@ export function createSessionTimelineRowRenderer(input: {
contentID={ref()!.partID}
showAssistantCopyPartID={copyContentID(row().userMessageID)}
turnDurationMs={duration(row().userMessageID)}
sources={turnSourcesValue()}
onOpenSources={() => sourcesHost?.open(row().userMessageID)}
defaultOpen={defaultOpen()}
toolOpen={input.disclosure.value(disclosureKey()) ?? defaultOpen()}
onToolOpenChange={(open) => input.disclosure.set(disclosureKey(), open)}
@@ -1317,5 +1336,6 @@ function growIn(el: HTMLElement) {
return false
},
)
onCleanup(remove)
}
+9
View File
@@ -302,6 +302,15 @@ const source = {
"ui.message.duration.hoursMinutes": "{{hours}}h {{minutes}}m",
"ui.message.interrupted": "Interrupted",
"ui.message.modelVariant": "{{model}} ({{variant}})",
"ui.sources.count.one": "{{count}} source",
"ui.sources.count.other": "{{count}} sources",
"ui.sources.none": "No sources",
"ui.sources.title": "Sources",
"ui.sources.searched": "Searched web",
"ui.sources.searchFailed": "Search failed",
"ui.sources.noResults": "No results",
"ui.sources.opened": "Opened page",
"ui.sources.openFailed": "Couldn’t open page",
"ui.sessionTimeline.notice.model": "Model",
"ui.sessionTimeline.notice.modelSwitched": "Switched to {{model}}",
"ui.sessionTimeline.notice.variantSwitched": "Switched variant to {{variant}}",