From b35b7d32696e9de39a5025319bc22fc3f4f9eae2 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:33:55 +0800 Subject: [PATCH 01/18] fix(web): remove the leftover ViteMcp plugin call The previous commit dropped vite-plugin-mcp and its import but kept the call, so every build failed with ViteMcp is not defined. --- apps/web/vite.config.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 96a0e5fa..06fd6a5f 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -10,7 +10,6 @@ export default defineConfig(({ mode }) => { return { plugins: lazyPlugins(() => [ react(), - ViteMcp(), // `cf build` and `cf deploy` delegate to `vite build`, which needs the // Cloudflare plugin to emit the Worker plus its static assets as Build // Output. Under `serve` the same plugin boots the Worker behind the dev From e38a027ebbfb75a32e7d4c71b33cb13ddccaece8 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:54:14 +0800 Subject: [PATCH 02/18] feat(web): stream the pages web search read as source-url events The chat UI can only cite what it knows the agent read. Sources whose URL the 4096-byte result limit cut off are dropped, since the model never saw them, and sources are stripped from the tool message so snippets are not sent to the model twice. --- apps/web/worker/agent/loop.ts | 5 ++ apps/web/worker/agent/observation.ts | 91 +++++++++++++++++++++++++++- apps/web/worker/agent/stream.ts | 15 +++++ apps/web/worker/tools/types.ts | 12 ++++ apps/web/worker/tools/web-search.ts | 77 ++++++++++++++++++----- 5 files changed, 183 insertions(+), 17 deletions(-) diff --git a/apps/web/worker/agent/loop.ts b/apps/web/worker/agent/loop.ts index 741cd91f..950a9747 100644 --- a/apps/web/worker/agent/loop.ts +++ b/apps/web/worker/agent/loop.ts @@ -21,6 +21,7 @@ import { sendContent, sendDone, sendFallback, + sendSourceUrl, sendToolResult, sendToolStart, emitAgentStep, @@ -538,6 +539,10 @@ async function executeStreamingToolCalls(options: { observation.summary, ) + for (const source of observation.sources ?? []) { + await sendSourceUrl(options.writer, source) + } + toolResults.push({ toolCall, observation, diff --git a/apps/web/worker/agent/observation.ts b/apps/web/worker/agent/observation.ts index 95fa3b10..55d13fe0 100644 --- a/apps/web/worker/agent/observation.ts +++ b/apps/web/worker/agent/observation.ts @@ -1,4 +1,4 @@ -import type { ToolResult } from "../tools/types.ts" +import type { ToolResult, ToolSource } from "../tools/types.ts" import { buildToolResultContent, type ProviderMessage } from "./messages.ts" export interface ObservationError { @@ -24,6 +24,11 @@ export interface Observation { originalByteCount?: number truncatedByteCount?: number | null providerMessage?: ProviderMessage + /** + * Pages the model actually read: the tool's `metadata.sources` minus any whose + * URL was cut from `raw` by the registry's byte limit. Absent on errors. + */ + sources?: ToolSource[] } interface BuildObservationOptions { @@ -48,6 +53,9 @@ export function buildObservation(options: BuildObservationOptions): Observation : null const summary = buildSummary(options.result.content, parsedContent, hasError) const error = hasError ? buildObservationError(parsedContent, summary) : null + const sources = hasError + ? [] + : readVisibleSources(options.result.metadata?.sources, options.result.content) return createObservation({ toolCallId: options.toolCallId, @@ -66,8 +74,9 @@ export function buildObservation(options: BuildObservationOptions): Observation providerMessage: { role: "tool", tool_call_id: options.toolCallId, - content: buildToolResultContent(options.result), + content: buildToolResultContent(withoutSourcesMetadata(options.result)), }, + ...(sources.length > 0 ? { sources } : {}), }) } @@ -75,6 +84,84 @@ function byteLength(value: string): number { return textEncoder.encode(value).length } +/** + * Sources are UI-only: `buildToolResultContent` would otherwise serialize them + * into the tool message, re-sending every snippet (including pages the byte + * limit cut) to the model. + */ +function withoutSourcesMetadata(result: ToolResult): ToolResult { + if (!result.metadata || !("sources" in result.metadata)) { + return result + } + + const metadata = { ...result.metadata } + delete metadata.sources + + return { + ...result, + metadata: Object.keys(metadata).length > 0 ? metadata : undefined, + } +} + +function readVisibleSources(value: unknown, content: string): ToolSource[] { + if (!Array.isArray(value)) return [] + + const sources: ToolSource[] = [] + const seen = new Set() + + for (const entry of value) { + const source = toToolSource(entry) + if (!source || seen.has(source.url) || !mentionsUrl(content, source.url)) continue + + seen.add(source.url) + sources.push(source) + } + + return sources +} + +function toToolSource(value: unknown): ToolSource | null { + if (value === null || typeof value !== "object") return null + + const { url, title, snippet } = value as Record + if (typeof url !== "string" || typeof title !== "string" || !isHttpUrl(url)) return null + if (snippet !== undefined && typeof snippet !== "string") return null + + return { + url, + title, + ...(snippet ? { snippet } : {}), + } +} + +function isHttpUrl(value: string): boolean { + try { + const { protocol } = new URL(value) + return protocol === "http:" || protocol === "https:" + } catch { + return false + } +} + +/** + * Characters after a URL that end it. Anything else (`/`, `-`, letters, ...) + * means the match is a prefix of a longer URL, which is a different page. + */ +const URL_TERMINATORS = /[\s)\]}>"'<,;]/ + +/** True when `content` contains `url` as a whole URL, not only as a prefix. */ +function mentionsUrl(content: string, url: string): boolean { + let index = content.indexOf(url) + + while (index !== -1) { + const next = content[index + url.length] + if (next === undefined || URL_TERMINATORS.test(next)) return true + index = content.indexOf(url, index + 1) + } + + return false +} + function numberMetadata(value: unknown, fallback: number): number { return typeof value === "number" ? value : fallback } diff --git a/apps/web/worker/agent/stream.ts b/apps/web/worker/agent/stream.ts index b44ab762..8406a82c 100644 --- a/apps/web/worker/agent/stream.ts +++ b/apps/web/worker/agent/stream.ts @@ -1,3 +1,5 @@ +import type { ToolSource } from "../tools/types.ts" + const textEncoder = new TextEncoder() type SSEWriter = WritableStreamDefaultWriter @@ -50,6 +52,19 @@ export async function sendToolResult( }) } +/** + * One page the model read, shaped like the AI SDK `source-url` stream part. + * The URL doubles as `sourceId` so repeated hits on a page collapse client-side. + */ +export async function sendSourceUrl(writer: SSEWriter, source: ToolSource): Promise { + await writeEvent(writer, "source-url", { + sourceId: source.url, + url: source.url, + title: source.title, + ...(source.snippet ? { snippet: source.snippet } : {}), + }) +} + export async function sendContent( writer: SSEWriter, delta: string, diff --git a/apps/web/worker/tools/types.ts b/apps/web/worker/tools/types.ts index 6c84de61..904b679c 100644 --- a/apps/web/worker/tools/types.ts +++ b/apps/web/worker/tools/types.ts @@ -16,6 +16,18 @@ export interface ToolResult { truncated?: boolean } +/** + * A page a retrieval tool handed to the model, returned as `metadata.sources`. + * The agent loop streams the ones the model actually saw to the browser as + * `source-url` events; they are never sent back to the model. + */ +export interface ToolSource { + url: string + title: string + /** Short plain-text excerpt for the citation preview. */ + snippet?: string +} + export interface OpenAITool { type: "function" function: { diff --git a/apps/web/worker/tools/web-search.ts b/apps/web/worker/tools/web-search.ts index af8e69bc..ce2e9192 100644 --- a/apps/web/worker/tools/web-search.ts +++ b/apps/web/worker/tools/web-search.ts @@ -1,15 +1,20 @@ import type { ToolRegistry } from "./registry" -import { ToolDefinition, ToolResult, RequestContext } from "./types" +import type { RequestContext, ToolDefinition, ToolResult, ToolSource } from "./types" + +interface TavilyResult { + title: string + url: string + content: string + score: number +} interface TavilyResponse { - results?: Array<{ - title: string - url: string - content: string - score: number - }> + results?: TavilyResult[] } +/** Longest citation preview, in characters, including the trailing ellipsis. */ +const SNIPPET_MAX_CHARS = 240 + interface WebSearchArgs { query: string max_results?: number @@ -38,14 +43,7 @@ function getResultPriority(url: string, score: number): number { return priority } -function formatResults( - results: Array<{ - title: string - url: string - content: string - score: number - }>, -): string { +function formatResults(results: TavilyResult[]): string { if (results.length === 0) { return "No results found for the search query." } @@ -55,6 +53,54 @@ function formatResults( .join("\n") } +function toSnippet(content: unknown): string | undefined { + if (typeof content !== "string") return undefined + + const collapsed = content.replace(/\s+/g, " ").trim() + // Count code points, not UTF-16 units, so the cut never splits a surrogate pair. + const chars = Array.from(collapsed) + if (chars.length === 0) return undefined + if (chars.length <= SNIPPET_MAX_CHARS) return collapsed + + return `${chars + .slice(0, SNIPPET_MAX_CHARS - 1) + .join("") + .trimEnd()}…` +} + +/** + * Citation metadata for the results in `formatResults` order. The URL is kept + * verbatim (not normalized) so it matches the `Source:` line the model reads. + */ +function buildSources(results: TavilyResult[]): ToolSource[] { + const sources: ToolSource[] = [] + const seen = new Set() + + for (const result of results) { + if (typeof result.url !== "string" || seen.has(result.url)) continue + + let hostname: string + try { + const parsed = new URL(result.url) + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") continue + hostname = parsed.hostname + } catch { + continue + } + + seen.add(result.url) + const title = typeof result.title === "string" ? result.title.trim() : "" + const snippet = toSnippet(result.content) + sources.push({ + url: result.url, + title: title || hostname, + ...(snippet ? { snippet } : {}), + }) + } + + return sources +} + export function createWebSearchTool(registry: ToolRegistry): ToolDefinition { const tool: ToolDefinition = { name: "web_search", @@ -122,6 +168,7 @@ export function createWebSearchTool(registry: ToolRegistry): ToolDefinition { return { content: formatResults(sorted), + metadata: { sources: buildSources(sorted) }, } } catch (error) { const message = error instanceof Error ? error.message : String(error) From 4aee6fea7c78cb2e47e0adb69f08f3f9e3af55d7 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:54:23 +0800 Subject: [PATCH 03/18] test(web): cover source-url streaming and the truncation filter --- apps/web/worker/agent/loop.test.ts | 262 ++++++++++++++++++++++ apps/web/worker/agent/observation.test.ts | 117 ++++++++++ apps/web/worker/agent/stream.test.ts | 36 +++ 3 files changed, 415 insertions(+) diff --git a/apps/web/worker/agent/loop.test.ts b/apps/web/worker/agent/loop.test.ts index baf25833..c10541f6 100644 --- a/apps/web/worker/agent/loop.test.ts +++ b/apps/web/worker/agent/loop.test.ts @@ -8,6 +8,7 @@ import { } from "../test/utils/mockProvider.ts" import { createStubTool } from "../test/utils/stubTools.ts" import { ToolRegistry } from "../tools/registry.ts" +import { createWebSearchTool } from "../tools/web-search.ts" import { runStreamingAgentLoop } from "./loop.ts" interface ProviderRequestBody { @@ -633,3 +634,264 @@ test("streaming allows tools for substantive query", async () => { globalThis.fetch = originalFetch } }) + +interface SourceUrlPayload { + sourceId: string + url: string + title: string + snippet?: string +} + +interface TavilyResultFixture { + title: string + url: string + content: string + score: number +} + +const TAVILY_SEARCH_URL = "https://api.tavily.com/search" + +/** Answers Tavily with `results`; everything else goes to the provider mock. */ +function routeTavily(providerFetch: typeof fetch, results: TavilyResultFixture[]): typeof fetch { + return (async (input: Parameters[0], init?: RequestInit) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url + if (url === TAVILY_SEARCH_URL) { + return new Response(JSON.stringify({ results }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }) + } + return providerFetch(input, init) + }) as typeof fetch +} + +function sourcePayloads(events: ParsedSSEEvent[]): SourceUrlPayload[] { + return events.filter((e) => e.event === "source-url").map((e) => e.data as SourceUrlPayload) +} + +function toolMessageContents(request: RecordedProviderRequest): string[] { + return (parseRequestBody(request).messages ?? []) + .filter((message) => message.role === "tool") + .map((message) => message.content ?? "") +} + +test("streaming emits source-url events right after tool_result, in result order", async () => { + const rates = { + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for 2026-27.", + } + const dining = { url: "https://housing.illinois.edu/dining", title: "Dining" } + const mockFetch = createMockProviderFetch([ + { + content: "Let me search...", + toolCalls: [{ name: "web_search", arguments: { query: "UIUC housing rates" } }], + stream: true, + }, + { content: "Rates are listed on the housing site.", stream: true }, + ]) + + const originalFetch = globalThis.fetch + globalThis.fetch = mockFetch + + try { + const registry = new ToolRegistry() + registry.register( + createStubTool({ + name: "web_search", + description: "Search the web", + content: `Source: ${rates.url}\nRates for 2026-27.\n---\nSource: ${dining.url}\nDining info.`, + metadata: { sources: [rates, dining] }, + }), + ) + const { writer, events } = createWriterWithStream() + + await runStreamingAgentLoop({ + message: "What are the UIUC housing rates?", + history: [], + registry, + env: createTestEnv(), + writer, + }) + + const parsed = await events + const eventNames = parsed.map((e) => e.event) + const toolResultIndex = eventNames.indexOf("tool_result") + assert.ok(toolResultIndex >= 0, "Should have tool_result event") + assert.deepEqual( + eventNames.slice(toolResultIndex, toolResultIndex + 3), + ["tool_result", "source-url", "source-url"], + "source-url events follow their tool_result directly", + ) + assert.ok( + eventNames.indexOf("source-url") < eventNames.lastIndexOf("content"), + "sources arrive before the answer text", + ) + + assert.deepEqual(sourcePayloads(parsed), [ + { sourceId: rates.url, url: rates.url, title: rates.title, snippet: rates.snippet }, + { sourceId: dining.url, url: dining.url, title: dining.title }, + ]) + + const [toolMessage] = toolMessageContents(mockFetch.requests[1]) + assert.ok(toolMessage.includes(rates.url), "model still reads the tool content") + assert.ok(!toolMessage.includes('"sources"'), "sources metadata is not sent to the model") + } finally { + globalThis.fetch = originalFetch + } +}) + +test("streaming web_search sources skip non-http results and fall back to the hostname", async () => { + const providerFetch = createMockProviderFetch([ + { + content: "Let me search...", + toolCalls: [{ name: "web_search", arguments: { query: "UIUC housing rates" } }], + stream: true, + }, + { content: "Here are the rates.", stream: true }, + ]) + const ratesContent = `Rates for\n\n2026-27 ${"x".repeat(400)}` + + const originalFetch = globalThis.fetch + globalThis.fetch = routeTavily(providerFetch, [ + { url: "https://www.illinois.edu/housing", title: "", content: "Short page.", score: 0.5 }, + { + url: "https://housing.illinois.edu/rates", + title: " Room and Board Rates ", + content: ratesContent, + score: 0.9, + }, + { url: "ftp://illinois.edu/rates.pdf", title: "FTP mirror", content: "binary", score: 0.99 }, + ]) + + try { + const registry = new ToolRegistry() + createWebSearchTool(registry) + const { writer, events } = createWriterWithStream() + + await runStreamingAgentLoop({ + message: "What are the UIUC housing rates?", + history: [], + registry, + env: { ...createTestEnv(), TAVILY_API_KEY: "test-tavily-key" }, + writer, + }) + + const sources = sourcePayloads(await events) + assert.deepEqual( + sources.map((source) => [source.url, source.title]), + [ + ["https://housing.illinois.edu/rates", "Room and Board Rates"], + ["https://www.illinois.edu/housing", "www.illinois.edu"], + ], + "sorted by priority, ftp dropped, empty title replaced by hostname", + ) + + const snippet = sources[0].snippet ?? "" + assert.ok(snippet.startsWith("Rates for 2026-27 xxx"), "whitespace is collapsed") + assert.equal(Array.from(snippet).length, 240, "snippet is cut to 240 characters") + assert.ok(snippet.endsWith("…"), "a cut snippet ends with an ellipsis") + assert.equal(sources[1].snippet, "Short page.") + } finally { + globalThis.fetch = originalFetch + } +}) + +test("streaming web_search drops sources the 4096-byte result limit cut off", async () => { + const visible = "https://www.illinois.edu/housing" + const cut = "https://housing.illinois.edu/contracts" + const providerFetch = createMockProviderFetch([ + { + content: "Let me search...", + toolCalls: [{ name: "web_search", arguments: { query: "UIUC housing contracts" } }], + stream: true, + }, + { content: "Here is what I found.", stream: true }, + ]) + + const originalFetch = globalThis.fetch + // Sized so the registry's cut lands inside the third result's `Source:` URL. + globalThis.fetch = routeTavily(providerFetch, [ + { + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + content: "r".repeat(3915), + score: 0.9, + }, + { url: visible, title: "", content: "Short page.", score: 0.8 }, + { url: cut, title: "Contracts", content: "c".repeat(500), score: 0.7 }, + ]) + + try { + const registry = new ToolRegistry() + createWebSearchTool(registry) + const { writer, events } = createWriterWithStream() + + await runStreamingAgentLoop({ + message: "How do UIUC housing contracts work?", + history: [], + registry, + env: { ...createTestEnv(), TAVILY_API_KEY: "test-tavily-key" }, + writer, + }) + + const [toolMessage] = toolMessageContents(providerFetch.requests[1]) + const { content, truncated } = JSON.parse(toolMessage) as { + content: string + truncated: boolean + } + assert.equal(truncated, true, "fixture must exceed the registry byte limit") + assert.ok(content.includes(visible), "fixture keeps the second result's URL") + assert.ok(!content.includes(cut), "fixture cuts the third result's URL") + + assert.deepEqual( + sourcePayloads(await events).map((source) => source.url), + ["https://housing.illinois.edu/rates", visible], + ) + } finally { + globalThis.fetch = originalFetch + } +}) + +test("streaming emits no source-url events when the tool errors", async () => { + const mockFetch = createMockProviderFetch([ + { + content: "Let me search...", + toolCalls: [{ name: "web_search", arguments: { query: "UIUC housing" } }], + stream: true, + }, + { content: "The search failed, but I can still help.", stream: true }, + ]) + + const originalFetch = globalThis.fetch + globalThis.fetch = mockFetch + + try { + const url = "https://housing.illinois.edu/rates" + const registry = new ToolRegistry() + registry.register( + createStubTool({ + name: "web_search", + description: "Search that reports an error", + content: `Partial failure.\nSource: ${url}`, + metadata: { error: true, sources: [{ url, title: "Rates" }] }, + }), + ) + const { writer, events } = createWriterWithStream() + + await runStreamingAgentLoop({ + message: "What are the UIUC housing rates?", + history: [], + registry, + env: createTestEnv(), + writer, + }) + + const parsed = await events + const toolResult = parsed.find((e) => e.event === "tool_result") + assert.equal((toolResult?.data as { status?: string } | undefined)?.status, "error") + assert.equal(sourcePayloads(parsed).length, 0, "error results stream no sources") + } finally { + globalThis.fetch = originalFetch + } +}) diff --git a/apps/web/worker/agent/observation.test.ts b/apps/web/worker/agent/observation.test.ts index faaf79cf..a9bc79ea 100644 --- a/apps/web/worker/agent/observation.test.ts +++ b/apps/web/worker/agent/observation.test.ts @@ -156,3 +156,120 @@ test("buildObservation handles empty successful output", () => { assert.ok(observation.providerMessage) assert.equal(observation.providerMessage.content, "") }) + +const RATES = { + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for 2026-27.", +} +const DINING = { url: "https://housing.illinois.edu/dining", title: "Dining" } + +function searchContent(...urls: string[]): string { + return urls.map((url) => `## Page\nSource: ${url}\n\nBody\n---`).join("\n") +} + +test("buildObservation keeps validated sources in order and hides them from the model", () => { + const content = searchContent(RATES.url, DINING.url) + const observation = buildObservation({ + toolCallId: "call_sources", + toolName: "web_search", + input: { query: "UIUC housing rates" }, + result: { content, metadata: { sources: [RATES, DINING] } }, + stepIndex: 0, + }) + + assert.deepEqual(observation.sources, [RATES, DINING]) + assert.equal( + observation.providerMessage?.content, + content, + "sources-only metadata must leave the tool message as plain content", + ) +}) + +test("buildObservation drops sources whose URL the byte limit cut from the content", () => { + const cut = "https://housing.illinois.edu/contracts" + const observation = buildObservation({ + toolCallId: "call_truncated_sources", + toolName: "web_search", + input: { query: "UIUC housing" }, + result: { + content: `${searchContent(RATES.url, DINING.url)}\n## Contracts\nSource: ${cut.slice(0, 30)}\n...[truncated]`, + metadata: { + sources: [RATES, DINING, { url: cut, title: "Contracts" }], + original_bytes: 9000, + truncated_bytes: 4096, + }, + truncated: true, + }, + stepIndex: 0, + }) + + assert.deepEqual( + observation.sources?.map((source) => source.url), + [RATES.url, DINING.url], + ) + assert.deepEqual(JSON.parse(observation.providerMessage?.content ?? ""), { + content: observation.raw, + metadata: { original_bytes: 9000, truncated_bytes: 4096 }, + truncated: true, + }) +}) + +test("buildObservation does not treat a longer URL in the content as a mention of its prefix", () => { + const observation = buildObservation({ + toolCallId: "call_prefix", + toolName: "web_search", + input: { query: "dining" }, + result: { + content: searchContent(`${DINING.url}-hours`), + metadata: { sources: [{ url: `${DINING.url}-hours`, title: "Hours" }, DINING] }, + }, + stepIndex: 0, + }) + + assert.deepEqual( + observation.sources?.map((source) => source.url), + [`${DINING.url}-hours`], + ) +}) + +test("buildObservation omits sources on error results", () => { + const observation = buildObservation({ + toolCallId: "call_error_sources", + toolName: "web_search", + input: { query: "UIUC housing" }, + result: { + content: `${JSON.stringify({ error: "upstream_failed" })}\n${searchContent(RATES.url)}`, + metadata: { error: true, sources: [RATES] }, + }, + stepIndex: 0, + }) + + assert.equal(observation.status, "error") + assert.ok(!("sources" in observation), "error observations carry no sources field") +}) + +test("buildObservation rejects malformed and non-http sources and omits an empty list", () => { + const malformed = [ + null, + "https://housing.illinois.edu/rates", + { url: RATES.url }, + { url: RATES.url, title: 7 }, + { url: RATES.url, title: "Rates", snippet: 1 }, + { url: "javascript:alert(1)", title: "XSS" }, + { url: "not a url", title: "Bad" }, + ] + const observation = buildObservation({ + toolCallId: "call_malformed", + toolName: "web_search", + input: { query: "UIUC housing" }, + result: { + content: `${searchContent(RATES.url)}\njavascript:alert(1)\nnot a url`, + metadata: { sources: malformed }, + }, + stepIndex: 0, + }) + + assert.equal(observation.status, "success") + assert.ok(!("sources" in observation), "no valid sources leaves the field absent") +}) diff --git a/apps/web/worker/agent/stream.test.ts b/apps/web/worker/agent/stream.test.ts index 58642387..6c7fe375 100644 --- a/apps/web/worker/agent/stream.test.ts +++ b/apps/web/worker/agent/stream.test.ts @@ -5,6 +5,7 @@ import { createSSEStream, sendToolStart, sendToolResult, + sendSourceUrl, sendContent, sendFallback, sendDone, @@ -425,3 +426,38 @@ test("existing tool_result test still passes (backward compat)", async () => { assert.equal(payload.status, "success") assert.equal(payload.summary, "2 results") }) + +test("source-url payload mirrors the AI SDK source-url part", async () => { + const { writer, events } = createTestWriterPair() + + await sendSourceUrl(writer, { + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for the 2026-27 academic year…", + }) + await writer.close() + + const parsed = await events + assert.equal(parsed.length, 1) + assert.equal(parsed[0].event, "source-url") + assert.deepEqual(parsed[0].data, { + sourceId: "https://housing.illinois.edu/rates", + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for the 2026-27 academic year…", + }) +}) + +test("source-url payload omits snippet when the source has none", async () => { + const { writer, events } = createTestWriterPair() + + await sendSourceUrl(writer, { url: "https://illinois.edu/", title: "illinois.edu" }) + await writer.close() + + const parsed = await events + assert.deepEqual(parsed[0].data, { + sourceId: "https://illinois.edu/", + url: "https://illinois.edu/", + title: "illinois.edu", + }) +}) From 9d03020d0e58159864fa8238584ad336b1f6bee9 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:54:40 +0800 Subject: [PATCH 04/18] feat(web): parse source-url events into chat stream chunks --- apps/web/src/services/ai/types.ts | 4 +++ apps/web/src/services/deepseekSse.ts | 50 +++++++++++++++++++++++++++- apps/web/src/types.ts | 10 ++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/apps/web/src/services/ai/types.ts b/apps/web/src/services/ai/types.ts index bbe315f0..3b2c89cb 100644 --- a/apps/web/src/services/ai/types.ts +++ b/apps/web/src/services/ai/types.ts @@ -1,3 +1,5 @@ +import type { MessageSource } from "../../types" + export interface StreamChunk { text: string followUpQuestions?: string[] @@ -6,6 +8,8 @@ export interface StreamChunk { label: string detail?: string } + /** A page the agent read, from the Worker's `source-url` event. */ + source?: MessageSource } export interface ChatHistoryItem { diff --git a/apps/web/src/services/deepseekSse.ts b/apps/web/src/services/deepseekSse.ts index ddd4eb93..3cad4c52 100644 --- a/apps/web/src/services/deepseekSse.ts +++ b/apps/web/src/services/deepseekSse.ts @@ -1,3 +1,4 @@ +import type { MessageSource } from "../types" import type { StreamChunk } from "./ai/types" type StreamLanguage = "en" | "zh" @@ -20,6 +21,19 @@ interface WorkerContentPayload { content?: string } +interface WorkerSourceUrlPayload { + sourceId?: unknown + url?: unknown + title?: unknown + snippet?: unknown +} + +/** + * Events whose payload never carries a legacy `choices[].delta`, so a payload + * the Worker handler rejects must not fall through to `parseLegacyDelta`. + */ +const EVENTS_WITHOUT_LEGACY_FALLBACK = new Set(["done", "source-url"]) + export interface SSEParserState { currentEvent: string reasoningBuffer: string @@ -53,6 +67,35 @@ function getWorkerToolName(payload: WorkerToolStartPayload | WorkerToolResultPay return payload.name ?? payload.tool ?? "unknown" } +/** + * Validates a `source-url` payload. The URL becomes a link in the UI, so only + * http(s) is accepted; anything malformed yields `null` and no chunk. + */ +function parseSourceUrl(payload: unknown): MessageSource | null { + if (payload === null || typeof payload !== "object") return null + + const data = payload as WorkerSourceUrlPayload + if (typeof data.url !== "string") return null + + let parsed: URL + try { + parsed = new URL(data.url) + } catch { + return null + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null + + const title = typeof data.title === "string" ? data.title.trim() : "" + const snippet = typeof data.snippet === "string" ? data.snippet.trim() : "" + + return { + id: typeof data.sourceId === "string" && data.sourceId ? data.sourceId : data.url, + url: data.url, + title: title || parsed.hostname, + ...(snippet ? { snippet } : {}), + } +} + function parseLegacyDelta( payload: unknown, state: SSEParserState, @@ -136,6 +179,11 @@ function parseWorkerEvent( return text ? [{ text }] : [] } + if (eventName === "source-url") { + const source = parseSourceUrl(payload) + return source ? [{ text: "", source }] : [] + } + return [] } @@ -163,7 +211,7 @@ export function parseDeepSeekSSELine( if (state.currentEvent) { const workerChunks = parseWorkerEvent(state.currentEvent, payload, lang) - if (workerChunks.length || state.currentEvent === "done") { + if (workerChunks.length || EVENTS_WITHOUT_LEGACY_FALLBACK.has(state.currentEvent)) { return workerChunks } } diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index 2eb660a1..ed39b791 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -36,6 +36,16 @@ export interface ThinkingStep { done: boolean } +/** A web page the agent read while answering (mirrors the AI SDK `source-url` part). */ +export interface MessageSource { + /** Stable id; the Worker uses the URL. */ + id: string + url: string + title: string + /** Short excerpt of the page, for the citation preview. */ + snippet?: string +} + export interface ChatMessage { id: string role: "user" | "model" From 4071034c3e8566d89bd914ce6114d87960d8d8d0 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:54:44 +0800 Subject: [PATCH 05/18] test(web): cover source-url parsing in the chat SSE client --- .../services/__tests__/deepseekSse.test.ts | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/apps/web/src/services/__tests__/deepseekSse.test.ts b/apps/web/src/services/__tests__/deepseekSse.test.ts index d0b031a4..a17328c8 100644 --- a/apps/web/src/services/__tests__/deepseekSse.test.ts +++ b/apps/web/src/services/__tests__/deepseekSse.test.ts @@ -206,3 +206,76 @@ test("ignores unknown events", () => { assert.equal(chunks.length, 0) }) + +function parseSourceEvent(payload: unknown) { + const state = createSSEParserState() + parseDeepSeekSSELine("event: source-url", state, "en") + return parseDeepSeekSSELine(`data: ${JSON.stringify(payload)}`, state, "en") +} + +test("source-url event: yields a source chunk with id, url, title, and snippet", () => { + const chunks = parseSourceEvent({ + sourceId: "https://housing.illinois.edu/rates", + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for the 2026-27 academic year…", + }) + + assert.deepEqual(chunks, [ + { + text: "", + source: { + id: "https://housing.illinois.edu/rates", + url: "https://housing.illinois.edu/rates", + title: "Room and Board Rates", + snippet: "Rates for the 2026-27 academic year…", + }, + }, + ]) +}) + +test("source-url event: falls back to the hostname when the title is missing or blank", () => { + const missing = parseSourceEvent({ + sourceId: "https://housing.illinois.edu/rates", + url: "https://housing.illinois.edu/rates", + }) + const blank = parseSourceEvent({ url: "https://www.illinois.edu/about", title: " " }) + + assert.equal(missing.length, 1) + assert.equal(missing[0].source?.title, "housing.illinois.edu") + assert.ok(!("snippet" in (missing[0].source ?? {})), "absent snippet stays absent") + assert.equal(blank[0].source?.title, "www.illinois.edu") +}) + +test("source-url event: sourceId falls back to the url", () => { + const chunks = parseSourceEvent({ url: "https://illinois.edu/", title: "Illinois" }) + + assert.equal(chunks[0].source?.id, "https://illinois.edu/") +}) + +test("source-url event: ignores non-http(s) and unparseable URLs", () => { + for (const url of [ + "javascript:alert(1)", + "data:text/html,hi", + "ftp://illinois.edu/file", + "not a url", + "", + ]) { + assert.deepEqual(parseSourceEvent({ sourceId: url, url, title: "x" }), [], url) + } +}) + +test("source-url event: ignores payloads without a string url", () => { + assert.deepEqual(parseSourceEvent({ title: "No URL" }), []) + assert.deepEqual(parseSourceEvent({ url: 42, title: "Numeric URL" }), []) + assert.deepEqual(parseSourceEvent(null), []) +}) + +test("source-url event: an invalid payload never falls through to legacy delta parsing", () => { + const chunks = parseSourceEvent({ + url: "javascript:alert(1)", + choices: [{ delta: { content: "injected text" } }], + }) + + assert.deepEqual(chunks, []) +}) From 18ee5d0efdab4110ae5fb230b9f3e83e406b22a0 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:54:54 +0800 Subject: [PATCH 06/18] feat(web): keep each reply's sources in chat history Signed-in chats store them in a new messages.sources column (scripts/migrations/add_message_sources.sql). Until that migration runs, Supabase rejects the column with PGRST204 and the message is saved again without its sources rather than lost. --- .../migrations/add_message_sources.sql | 11 ++++++++ .../web/src/components/chat/useChatSession.ts | 13 ++++++++- apps/web/src/services/conversationService.ts | 28 ++++++++++++------- .../src/services/localConversationService.ts | 5 +++- apps/web/src/services/supabase.ts | 3 ++ apps/web/src/types.ts | 2 ++ 6 files changed, 50 insertions(+), 12 deletions(-) create mode 100644 apps/web/scripts/migrations/add_message_sources.sql diff --git a/apps/web/scripts/migrations/add_message_sources.sql b/apps/web/scripts/migrations/add_message_sources.sql new file mode 100644 index 00000000..1b7f1551 --- /dev/null +++ b/apps/web/scripts/migrations/add_message_sources.sql @@ -0,0 +1,11 @@ +-- Migration: Add sources to chat messages +-- Purpose: Keep the web pages an assistant reply was based on, so the +-- "N sources" button and numbered citations survive reloading a conversation. +-- Shape: [{ "id": text, "url": text, "title": text, "snippet"?: text }] +-- Until this runs, the app saves messages without their sources. + +ALTER TABLE public.messages + ADD COLUMN IF NOT EXISTS sources JSONB; + +-- Reload PostgREST's schema cache so the new column is accepted right away. +NOTIFY pgrst, 'reload schema'; diff --git a/apps/web/src/components/chat/useChatSession.ts b/apps/web/src/components/chat/useChatSession.ts index 4780ea3f..74aa974e 100644 --- a/apps/web/src/components/chat/useChatSession.ts +++ b/apps/web/src/components/chat/useChatSession.ts @@ -6,7 +6,7 @@ import { streamChatResponse } from "../../services/ai" import { conversationService } from "../../services/conversationService" import { localConversationService } from "../../services/localConversationService" import { memoryService } from "../../services/memoryService" -import { Language, ChatMessage, ThinkingStep } from "../../types" +import { Language, ChatMessage, MessageSource, ThinkingStep } from "../../types" interface UseChatSessionOptions { language: Language @@ -257,8 +257,18 @@ export const useChatSession = ({ let followUpQuestions: string[] | undefined let thinkingEndedAt: number | undefined const thinkingSteps: ThinkingStep[] = [] + // Several searches can return the same page; keep its first position. + const sources: MessageSource[] = [] for await (const chunk of stream) { + if (chunk.source && !sources.some((source) => source.url === chunk.source?.url)) { + sources.push(chunk.source) + dispatch({ + type: "UPDATE_MESSAGE", + payload: { id: aiMsgId, updates: { sources: [...sources] } }, + }) + } + if (chunk.thinkingStep) { if (thinkingSteps.length > 0) { thinkingSteps[thinkingSteps.length - 1].done = true @@ -395,6 +405,7 @@ export const useChatSession = ({ thinkingSteps: thinkingSteps.length > 0 ? thinkingSteps : undefined, thinkingStartedAt, thinkingEndedAt, + sources: sources.length > 0 ? sources : undefined, } streamingMessageIdRef.current = null diff --git a/apps/web/src/services/conversationService.ts b/apps/web/src/services/conversationService.ts index 19640dd3..459aef95 100644 --- a/apps/web/src/services/conversationService.ts +++ b/apps/web/src/services/conversationService.ts @@ -91,16 +91,23 @@ export const conversationService = { }, async saveMessage(conversationId: string, message: ChatMessage) { - const { data, error } = await supabase - .from("messages") - .insert({ - conversation_id: conversationId, - role: message.role, - content: message.text, - follow_up_questions: message.followUpQuestions || null, - }) - .select() - .single() + const row = { + conversation_id: conversationId, + role: message.role, + content: message.text, + follow_up_questions: message.followUpQuestions || null, + } + const insert = (values: typeof row & { sources?: ChatMessage["sources"] }) => + supabase.from("messages").insert(values).select().single() + + let { data, error } = await insert( + message.sources?.length ? { ...row, sources: message.sources } : row, + ) + // PGRST204: the `sources` column does not exist yet (migration + // add_message_sources.sql not applied). Keep the message, drop its sources. + if (error?.code === "PGRST204" && message.sources?.length) { + ;({ data, error } = await insert(row)) + } await supabase .from("conversations") @@ -149,6 +156,7 @@ export const conversationService = { role: msg.role as "user" | "model", text: msg.content, followUpQuestions: msg.follow_up_questions || undefined, + sources: msg.sources || undefined, })) }, } diff --git a/apps/web/src/services/localConversationService.ts b/apps/web/src/services/localConversationService.ts index 6d6ccd5b..cf013931 100644 --- a/apps/web/src/services/localConversationService.ts +++ b/apps/web/src/services/localConversationService.ts @@ -1,4 +1,4 @@ -import { ChatMessage } from "../types" +import { ChatMessage, MessageSource } from "../types" const STORAGE_KEY = "guest_conversations" @@ -9,6 +9,7 @@ interface LocalMessage { content: string created_at: string follow_up_questions?: string[] + sources?: MessageSource[] } interface LocalConversation { @@ -107,6 +108,7 @@ export const localConversationService = { content: message.text, created_at: new Date().toISOString(), follow_up_questions: message.followUpQuestions, + sources: message.sources, } conv.messages.push(newMessage) @@ -153,6 +155,7 @@ export const localConversationService = { role: msg.role, text: msg.content, followUpQuestions: msg.follow_up_questions, + sources: msg.sources, })) }, } diff --git a/apps/web/src/services/supabase.ts b/apps/web/src/services/supabase.ts index 465ca21a..d4a79e56 100644 --- a/apps/web/src/services/supabase.ts +++ b/apps/web/src/services/supabase.ts @@ -1,5 +1,7 @@ import { createClient } from "@supabase/supabase-js" +import type { MessageSource } from "../types" + const supabaseUrl = import.meta.env.VITE_SUPABASE_URL const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY @@ -75,6 +77,7 @@ export interface Message { role: "user" | "model" content: string follow_up_questions?: string[] + sources?: MessageSource[] | null created_at: string } diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index ed39b791..d87c153a 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -58,6 +58,8 @@ export interface ChatMessage { thinkingStartedAt?: number /** When the first reply text arrived, i.e. thinking finished (ms since epoch). */ thinkingEndedAt?: number + /** Pages the agent read for this reply, in the order they were found. */ + sources?: MessageSource[] } export interface ConversationSummary { From ff1637df10fe5652381a130b7275e0f002aadea7 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:56:44 +0800 Subject: [PATCH 07/18] chore(web): set up shadcn/ui with the AI Elements chat components Adds the primitives and the Sources, InlineCitation, and Suggestion elements the chat will use. Theme tokens map onto the existing slate and Illini palette. The default border colour applies only to data-slot elements and radius tokens keep Tailwind's defaults, so pages outside the chat render as before; dark: utilities need a .dark ancestor because the app is light-only. --- apps/web/components.json | 24 ++ apps/web/package.json | 8 +- .../ai-elements/inline-citation.tsx | 251 ++++++++++++++++++ .../src/components/ai-elements/sources.tsx | 54 ++++ .../src/components/ai-elements/suggestion.tsx | 49 ++++ apps/web/src/components/ui/badge.tsx | 46 ++++ apps/web/src/components/ui/button.tsx | 62 +++++ apps/web/src/components/ui/carousel.tsx | 221 +++++++++++++++ apps/web/src/components/ui/collapsible.tsx | 19 ++ apps/web/src/components/ui/hover-card.tsx | 38 +++ apps/web/src/components/ui/scroll-area.tsx | 54 ++++ apps/web/src/index.css | 61 +++++ apps/web/src/utils/cn.ts | 7 + pnpm-lock.yaml | 147 +++++----- 14 files changed, 964 insertions(+), 77 deletions(-) create mode 100644 apps/web/components.json create mode 100644 apps/web/src/components/ai-elements/inline-citation.tsx create mode 100644 apps/web/src/components/ai-elements/sources.tsx create mode 100644 apps/web/src/components/ai-elements/suggestion.tsx create mode 100644 apps/web/src/components/ui/badge.tsx create mode 100644 apps/web/src/components/ui/button.tsx create mode 100644 apps/web/src/components/ui/carousel.tsx create mode 100644 apps/web/src/components/ui/collapsible.tsx create mode 100644 apps/web/src/components/ui/hover-card.tsx create mode 100644 apps/web/src/components/ui/scroll-area.tsx create mode 100644 apps/web/src/utils/cn.ts diff --git a/apps/web/components.json b/apps/web/components.json new file mode 100644 index 00000000..77142c57 --- /dev/null +++ b/apps/web/components.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "ui": "@/components/ui", + "utils": "@/utils/cn", + "lib": "@/utils", + "hooks": "@/hooks" + }, + "registries": { + "@ai-elements": "https://ai-sdk.dev/elements/api/registry/{name}.json" + } +} diff --git a/apps/web/package.json b/apps/web/package.json index 19c36158..69389c8c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -11,16 +11,22 @@ "@assistant-ui/react-markdown": "0.14.17", "@headlessui/react": "^2.2.10", "@supabase/supabase-js": "^2.117.2", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "embla-carousel-react": "^8.6.0", "framer-motion": "^13.4.4", "lucide-react": "^1.48.0", "mapbox-gl": "^3.31.0", + "radix-ui": "^1.6.7", "rc-slider": "^11.1.9", "react": "^19.3.0", "react-dom": "^19.3.0", "react-map-gl": "^8.1.3", "react-markdown": "^10.1.0", "react-router-dom": "^7.18.4", - "remark-gfm": "^4.0.1" + "remark-gfm": "^4.0.1", + "tailwind-merge": "^3.7.0", + "tw-animate-css": "^1.4.0" }, "devDependencies": { "@cloudflare/vite-plugin": "^2.0.0-beta.sha-238e489d5", diff --git a/apps/web/src/components/ai-elements/inline-citation.tsx b/apps/web/src/components/ai-elements/inline-citation.tsx new file mode 100644 index 00000000..d51f90a0 --- /dev/null +++ b/apps/web/src/components/ai-elements/inline-citation.tsx @@ -0,0 +1,251 @@ +"use client" + +import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react" +import type { ComponentProps } from "react" +import { createContext, useCallback, useContext, useEffect, useState } from "react" + +import { Badge } from "@/components/ui/badge" +import type { CarouselApi } from "@/components/ui/carousel" +import { Carousel, CarouselContent, CarouselItem } from "@/components/ui/carousel" +import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card" +import { cn } from "@/utils/cn" + +export type InlineCitationProps = ComponentProps<"span"> + +export const InlineCitation = ({ className, ...props }: InlineCitationProps) => ( + +) + +export type InlineCitationTextProps = ComponentProps<"span"> + +export const InlineCitationText = ({ className, ...props }: InlineCitationTextProps) => ( + +) + +export type InlineCitationCardProps = ComponentProps + +export const InlineCitationCard = (props: InlineCitationCardProps) => ( + +) + +export type InlineCitationCardTriggerProps = ComponentProps & { + sources: string[] +} + +export const InlineCitationCardTrigger = ({ + sources, + className, + ...props +}: InlineCitationCardTriggerProps) => ( + + + {sources[0] ? ( + <> + {new URL(sources[0]).hostname} {sources.length > 1 && `+${sources.length - 1}`} + + ) : ( + "unknown" + )} + + +) + +export type InlineCitationCardBodyProps = ComponentProps<"div"> + +export const InlineCitationCardBody = ({ className, ...props }: InlineCitationCardBodyProps) => ( + +) + +const CarouselApiContext = createContext(undefined) + +const useCarouselApi = () => { + const context = useContext(CarouselApiContext) + return context +} + +export type InlineCitationCarouselProps = ComponentProps + +export const InlineCitationCarousel = ({ + className, + children, + ...props +}: InlineCitationCarouselProps) => { + const [api, setApi] = useState() + + return ( + + + {children} + + + ) +} + +export type InlineCitationCarouselContentProps = ComponentProps<"div"> + +export const InlineCitationCarouselContent = (props: InlineCitationCarouselContentProps) => ( + +) + +export type InlineCitationCarouselItemProps = ComponentProps<"div"> + +export const InlineCitationCarouselItem = ({ + className, + ...props +}: InlineCitationCarouselItemProps) => ( + +) + +export type InlineCitationCarouselHeaderProps = ComponentProps<"div"> + +export const InlineCitationCarouselHeader = ({ + className, + ...props +}: InlineCitationCarouselHeaderProps) => ( +
+) + +export type InlineCitationCarouselIndexProps = ComponentProps<"div"> + +export const InlineCitationCarouselIndex = ({ + children, + className, + ...props +}: InlineCitationCarouselIndexProps) => { + const api = useCarouselApi() + const [current, setCurrent] = useState(0) + const [count, setCount] = useState(0) + + const syncState = useCallback(() => { + if (!api) { + return + } + setCount(api.scrollSnapList().length) + setCurrent(api.selectedScrollSnap() + 1) + }, [api]) + + useEffect(() => { + if (!api) { + return + } + + syncState() + + api.on("select", syncState) + + return () => { + api.off("select", syncState) + } + }, [api, syncState]) + + return ( +
+ {children ?? `${current}/${count}`} +
+ ) +} + +export type InlineCitationCarouselPrevProps = ComponentProps<"button"> + +export const InlineCitationCarouselPrev = ({ + className, + ...props +}: InlineCitationCarouselPrevProps) => { + const api = useCarouselApi() + + const handleClick = useCallback(() => { + if (api) { + api.scrollPrev() + } + }, [api]) + + return ( + + ) +} + +export type InlineCitationCarouselNextProps = ComponentProps<"button"> + +export const InlineCitationCarouselNext = ({ + className, + ...props +}: InlineCitationCarouselNextProps) => { + const api = useCarouselApi() + + const handleClick = useCallback(() => { + if (api) { + api.scrollNext() + } + }, [api]) + + return ( + + ) +} + +export type InlineCitationSourceProps = ComponentProps<"div"> & { + title?: string + url?: string + description?: string +} + +export const InlineCitationSource = ({ + title, + url, + description, + className, + children, + ...props +}: InlineCitationSourceProps) => ( +
+ {title &&

{title}

} + {url &&

{url}

} + {description && ( +

{description}

+ )} + {children} +
+) + +export type InlineCitationQuoteProps = ComponentProps<"blockquote"> + +export const InlineCitationQuote = ({ + children, + className, + ...props +}: InlineCitationQuoteProps) => ( +
+ {children} +
+) diff --git a/apps/web/src/components/ai-elements/sources.tsx b/apps/web/src/components/ai-elements/sources.tsx new file mode 100644 index 00000000..4501ab5e --- /dev/null +++ b/apps/web/src/components/ai-elements/sources.tsx @@ -0,0 +1,54 @@ +"use client" + +import { BookIcon, ChevronDownIcon } from "lucide-react" +import type { ComponentProps } from "react" + +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" +import { cn } from "@/utils/cn" + +export type SourcesProps = ComponentProps<"div"> + +export const Sources = ({ className, ...props }: SourcesProps) => ( + +) + +export type SourcesTriggerProps = ComponentProps & { + count: number +} + +export const SourcesTrigger = ({ className, count, children, ...props }: SourcesTriggerProps) => ( + + {children ?? ( + <> +

Used {count} sources

+ + + )} +
+) + +export type SourcesContentProps = ComponentProps + +export const SourcesContent = ({ className, ...props }: SourcesContentProps) => ( + +) + +export type SourceProps = ComponentProps<"a"> + +export const Source = ({ href, title, children, ...props }: SourceProps) => ( + + {children ?? ( + <> + + {title} + + )} + +) diff --git a/apps/web/src/components/ai-elements/suggestion.tsx b/apps/web/src/components/ai-elements/suggestion.tsx new file mode 100644 index 00000000..cdc529ee --- /dev/null +++ b/apps/web/src/components/ai-elements/suggestion.tsx @@ -0,0 +1,49 @@ +"use client" + +import type { ComponentProps } from "react" +import { useCallback } from "react" + +import { Button } from "@/components/ui/button" +import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area" +import { cn } from "@/utils/cn" + +export type SuggestionsProps = ComponentProps + +export const Suggestions = ({ className, children, ...props }: SuggestionsProps) => ( + +
{children}
+ +
+) + +export type SuggestionProps = Omit, "onClick"> & { + suggestion: string + onClick?: (suggestion: string) => void +} + +export const Suggestion = ({ + suggestion, + onClick, + className, + variant = "outline", + size = "sm", + children, + ...props +}: SuggestionProps) => { + const handleClick = useCallback(() => { + onClick?.(suggestion) + }, [onClick, suggestion]) + + return ( + + ) +} diff --git a/apps/web/src/components/ui/badge.tsx b/apps/web/src/components/ui/badge.tsx new file mode 100644 index 00000000..03974bf3 --- /dev/null +++ b/apps/web/src/components/ui/badge.tsx @@ -0,0 +1,46 @@ +import { cva, type VariantProps } from "class-variance-authority" +import { Slot } from "radix-ui" +import * as React from "react" + +import { cn } from "@/utils/cn" + +const badgeVariants = cva( + "inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90", + secondary: "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90", + destructive: + "bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90", + outline: + "border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", + ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground", + link: "text-primary underline-offset-4 [a&]:hover:underline", + }, + }, + defaultVariants: { + variant: "default", + }, + }, +) + +function Badge({ + className, + variant = "default", + asChild = false, + ...props +}: React.ComponentProps<"span"> & VariantProps & { asChild?: boolean }) { + const Comp = asChild ? Slot.Root : "span" + + return ( + + ) +} + +export { Badge, badgeVariants } diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx new file mode 100644 index 00000000..e8840c35 --- /dev/null +++ b/apps/web/src/components/ui/button.tsx @@ -0,0 +1,62 @@ +import { cva, type VariantProps } from "class-variance-authority" +import { Slot } from "radix-ui" +import * as React from "react" + +import { cn } from "@/utils/cn" + +const buttonVariants = cva( + "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", + outline: + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", + secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", + "icon-sm": "size-8", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + }, +) + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot.Root : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/apps/web/src/components/ui/carousel.tsx b/apps/web/src/components/ui/carousel.tsx new file mode 100644 index 00000000..d5335f54 --- /dev/null +++ b/apps/web/src/components/ui/carousel.tsx @@ -0,0 +1,221 @@ +import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react" +import { ArrowLeft, ArrowRight } from "lucide-react" +import * as React from "react" + +import { Button } from "@/components/ui/button" +import { cn } from "@/utils/cn" + +type CarouselApi = UseEmblaCarouselType[1] +type UseCarouselParameters = Parameters +type CarouselOptions = UseCarouselParameters[0] +type CarouselPlugin = UseCarouselParameters[1] + +type CarouselProps = { + opts?: CarouselOptions + plugins?: CarouselPlugin + orientation?: "horizontal" | "vertical" + setApi?: (api: CarouselApi) => void +} + +type CarouselContextProps = { + carouselRef: ReturnType[0] + api: ReturnType[1] + scrollPrev: () => void + scrollNext: () => void + canScrollPrev: boolean + canScrollNext: boolean +} & CarouselProps + +const CarouselContext = React.createContext(null) + +function useCarousel() { + const context = React.useContext(CarouselContext) + + if (!context) { + throw new Error("useCarousel must be used within a ") + } + + return context +} + +function Carousel({ + orientation = "horizontal", + opts, + setApi, + plugins, + className, + children, + ...props +}: React.ComponentProps<"div"> & CarouselProps) { + const [carouselRef, api] = useEmblaCarousel( + { + ...opts, + axis: orientation === "horizontal" ? "x" : "y", + }, + plugins, + ) + const [canScrollPrev, setCanScrollPrev] = React.useState(false) + const [canScrollNext, setCanScrollNext] = React.useState(false) + + const onSelect = React.useCallback((api: CarouselApi) => { + if (!api) return + setCanScrollPrev(api.canScrollPrev()) + setCanScrollNext(api.canScrollNext()) + }, []) + + const scrollPrev = React.useCallback(() => { + api?.scrollPrev() + }, [api]) + + const scrollNext = React.useCallback(() => { + api?.scrollNext() + }, [api]) + + const handleKeyDown = React.useCallback( + (event: React.KeyboardEvent) => { + if (event.key === "ArrowLeft") { + event.preventDefault() + scrollPrev() + } else if (event.key === "ArrowRight") { + event.preventDefault() + scrollNext() + } + }, + [scrollPrev, scrollNext], + ) + + React.useEffect(() => { + if (!api || !setApi) return + setApi(api) + }, [api, setApi]) + + React.useEffect(() => { + if (!api) return + onSelect(api) + api.on("reInit", onSelect) + api.on("select", onSelect) + + return () => { + api?.off("select", onSelect) + } + }, [api, onSelect]) + + return ( + +
+ {children} +
+
+ ) +} + +function CarouselContent({ className, ...props }: React.ComponentProps<"div">) { + const { carouselRef, orientation } = useCarousel() + + return ( +
+
+
+ ) +} + +function CarouselItem({ className, ...props }: React.ComponentProps<"div">) { + const { orientation } = useCarousel() + + return ( +
+ ) +} + +function CarouselPrevious({ + className, + variant = "outline", + size = "icon", + ...props +}: React.ComponentProps) { + const { orientation, scrollPrev, canScrollPrev } = useCarousel() + + return ( + + ) +} + +function CarouselNext({ + className, + variant = "outline", + size = "icon", + ...props +}: React.ComponentProps) { + const { orientation, scrollNext, canScrollNext } = useCarousel() + + return ( + + ) +} + +export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext } diff --git a/apps/web/src/components/ui/collapsible.tsx b/apps/web/src/components/ui/collapsible.tsx new file mode 100644 index 00000000..e0caf875 --- /dev/null +++ b/apps/web/src/components/ui/collapsible.tsx @@ -0,0 +1,19 @@ +import { Collapsible as CollapsiblePrimitive } from "radix-ui" + +function Collapsible({ ...props }: React.ComponentProps) { + return +} + +function CollapsibleTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function CollapsibleContent({ + ...props +}: React.ComponentProps) { + return +} + +export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/apps/web/src/components/ui/hover-card.tsx b/apps/web/src/components/ui/hover-card.tsx new file mode 100644 index 00000000..7d7eebc5 --- /dev/null +++ b/apps/web/src/components/ui/hover-card.tsx @@ -0,0 +1,38 @@ +"use client" + +import { HoverCard as HoverCardPrimitive } from "radix-ui" +import * as React from "react" + +import { cn } from "@/utils/cn" + +function HoverCard({ ...props }: React.ComponentProps) { + return +} + +function HoverCardTrigger({ ...props }: React.ComponentProps) { + return +} + +function HoverCardContent({ + className, + align = "center", + sideOffset = 4, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { HoverCard, HoverCardTrigger, HoverCardContent } diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsx new file mode 100644 index 00000000..20f8dc5c --- /dev/null +++ b/apps/web/src/components/ui/scroll-area.tsx @@ -0,0 +1,54 @@ +import { ScrollArea as ScrollAreaPrimitive } from "radix-ui" +import * as React from "react" + +import { cn } from "@/utils/cn" + +function ScrollArea({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + + ) +} + +function ScrollBar({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { ScrollArea, ScrollBar } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 97078e85..d5fd2339 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1,6 +1,12 @@ /* [ROOT] Global styles and Tailwind CSS directives. */ /* [根组件] 全局样式和 Tailwind CSS 指令。 */ @import "tailwindcss"; +@import "tw-animate-css"; + +/* The app is light-only. shadcn components carry `dark:` utilities; scoping the + variant to a `.dark` ancestor (never set) keeps them from half-applying when + the OS is in dark mode. */ +@custom-variant dark (&:is(.dark *)); @theme { --color-illini-blue: #13294b; @@ -9,6 +15,61 @@ --color-illini-orange-dark: #e05504; } +/* shadcn/ui tokens, mapped onto the app's slate + Illini palette. Radius tokens + are left at Tailwind's defaults so existing `rounded-*` classes keep their + size. */ +:root { + --background: #ffffff; + --foreground: #0f172a; + --card: #ffffff; + --card-foreground: #0f172a; + --popover: #ffffff; + --popover-foreground: #0f172a; + --primary: #13294b; + --primary-foreground: #ffffff; + --secondary: #f1f5f9; + --secondary-foreground: #0f172a; + --muted: #f1f5f9; + --muted-foreground: #64748b; + --accent: #f1f5f9; + --accent-foreground: #0f172a; + --destructive: #dc2626; + --border: #e2e8f0; + --input: #e2e8f0; + --ring: #94a3b8; +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); +} + +/* shadcn components assume a themed default border colour. Scope it to their + `data-slot` elements so the rest of the app keeps Tailwind's default. In the + base layer, so `border-*` utilities on those elements still win. */ +@layer base { + [data-slot] { + border-color: var(--border); + outline-color: color-mix(in oklab, var(--ring) 50%, transparent); + } +} + /* Body base style */ body { font-family: "Plus Jakarta Sans", sans-serif; diff --git a/apps/web/src/utils/cn.ts b/apps/web/src/utils/cn.ts new file mode 100644 index 00000000..a73cbe57 --- /dev/null +++ b/apps/web/src/utils/cn.ts @@ -0,0 +1,7 @@ +import { clsx, type ClassValue } from "clsx" +import { twMerge } from "tailwind-merge" + +/** Joins class names and lets later Tailwind utilities override earlier ones. */ +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b75efd87..26d2155b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -253,16 +253,25 @@ importers: dependencies: '@assistant-ui/react': specifier: ^0.15.22 - version: 0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@3.25.76))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)) + version: 0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@4.6.5))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)) '@assistant-ui/react-markdown': specifier: 0.14.17 - version: 0.14.17(@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@3.25.76))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(supports-color@10.2.2) + version: 0.14.17(@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@4.6.5))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(supports-color@10.2.2) '@headlessui/react': specifier: ^2.2.10 version: 2.2.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@supabase/supabase-js': specifier: ^2.117.2 version: 2.117.2 + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + embla-carousel-react: + specifier: ^8.6.0 + version: 8.6.0(react@19.3.0) framer-motion: specifier: ^13.4.4 version: 13.4.6(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -272,6 +281,9 @@ importers: mapbox-gl: specifier: ^3.31.0 version: 3.32.0 + radix-ui: + specifier: ^1.6.7 + version: 1.6.7(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) rc-slider: specifier: ^11.1.9 version: 11.1.9(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -293,6 +305,12 @@ importers: remark-gfm: specifier: ^4.0.1 version: 4.0.1(supports-color@10.2.2) + tailwind-merge: + specifier: ^3.7.0 + version: 3.7.0 + tw-animate-css: + specifier: ^1.4.0 + version: 1.4.0 devDependencies: '@cloudflare/vite-plugin': specifier: ^2.0.0-beta.sha-238e489d5 @@ -3435,6 +3453,9 @@ packages: chownr@1.1.4: resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + class-variance-authority@0.7.1: + resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + classnames@2.5.1: resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==} @@ -3572,6 +3593,19 @@ packages: electron-to-chromium@1.5.443: resolution: {integrity: sha512-TDJG36L9A3CWWwZ97HKaE+Iz1sW80pNp6sAU0owzCIV3Zc9eVyRqZK8Vz6NKuMIU8WjP0pIkoqCa0VRf/yFD0Q==} + embla-carousel-react@8.6.0: + resolution: {integrity: sha512-0/PjqU7geVmo6F734pmPqpyHqiM99olvyecY7zdweCw+6tKEXnrE90pBiBbMMU8s5tICemzpQ3hi5EpxzGW+JA==} + peerDependencies: + react: ^16.8.0 || ^17.0.1 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + + embla-carousel-reactive-utils@8.6.0: + resolution: {integrity: sha512-fMVUDUEx0/uIEDM0Mz3dHznDhfX+znCCDCeIophYb1QGVM7YThSWX+wz11zlYwWFOr74b4QLGg0hrGPJeG2s4A==} + peerDependencies: + embla-carousel: 8.6.0 + + embla-carousel@8.6.0: + resolution: {integrity: sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==} + empathic@2.1.0: resolution: {integrity: sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==} engines: {node: '>=14'} @@ -4190,9 +4224,6 @@ packages: resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} engines: {node: '>=18'} - micromark-core-commonmark@2.0.3: - resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==} - micromark-core-commonmark@2.0.4: resolution: {integrity: sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==} @@ -4274,9 +4305,6 @@ packages: micromark-util-symbol@2.0.1: resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} - micromark-util-types@2.0.2: - resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==} - micromark-util-types@2.0.3: resolution: {integrity: sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==} @@ -4827,10 +4855,6 @@ packages: resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} engines: {node: '>=18'} - smol-toml@1.8.0: - resolution: {integrity: sha512-kCZr2V3ch9i00x8zXRhjUNVcjG9ijES5dDudkXvUVCT5QlJNQWElSJdZqyPemffHoLNUYwOcou0Fy+ojN0uHSQ==} - engines: {node: '>= 18'} - smol-toml@1.9.0: resolution: {integrity: sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==} engines: {node: '>= 18'} @@ -4904,6 +4928,9 @@ packages: tabbable@6.5.0: resolution: {integrity: sha512-wieBHXygIm7OyQOu5hQlkk62/WyCFYGlWg7L6/ZCUZwx0o398Zkn4pVmMyfYhfMG8kGrj/Krt8eIk6UKC6VzwA==} + tailwind-merge@3.7.0: + resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==} + tailwindcss@4.3.3: resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} @@ -4969,6 +4996,9 @@ packages: resolution: {integrity: sha512-I8yFsfRzmzK0WV1pNNOA4A7y4RDfFxPRxb3t+e3ui14qSGOxGtiSP6GjeX+Y6CHb7HYaFj7ECUD7VE5kQMZWGQ==} engines: {node: '>=18', npm: '>=9'} + tw-animate-css@1.4.0: + resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + type-is@2.1.0: resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==} engines: {node: '>= 18'} @@ -5287,9 +5317,6 @@ packages: peerDependencies: zod: ^3.25.28 || ^4 - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} @@ -5325,14 +5352,6 @@ snapshots: '@ai-sdk/provider-utils': 5.0.53(zod@4.6.5) zod: 4.6.5 - '@ai-sdk/gateway@4.0.102(zod@3.25.76)': - dependencies: - '@ai-sdk/provider': 4.0.21 - '@ai-sdk/provider-utils': 5.0.53(zod@3.25.76) - '@vercel/oidc': 3.2.0 - zod: 3.25.76 - optional: true - '@ai-sdk/gateway@4.0.102(zod@4.6.5)': dependencies: '@ai-sdk/provider': 4.0.21 @@ -5346,16 +5365,6 @@ snapshots: '@ai-sdk/provider-utils': 5.0.53(zod@4.6.5) zod: 4.6.5 - '@ai-sdk/provider-utils@5.0.53(zod@3.25.76)': - dependencies: - '@ai-sdk/provider': 4.0.21 - '@standard-schema/spec': 1.1.0 - '@workflow/serde': 4.1.0 - eventsource-parser: 3.1.1 - undici: 7.30.0 - zod: 3.25.76 - optional: true - '@ai-sdk/provider-utils@5.0.53(zod@4.6.5)': dependencies: '@ai-sdk/provider': 4.0.21 @@ -5369,7 +5378,7 @@ snapshots: dependencies: json-schema: 0.4.0 - '@assistant-ui/core@0.3.21(@assistant-ui/store@0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0))(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(assistant-cloud@0.2.3(ai@7.0.126(zod@3.25.76)))(react@19.3.0)': + '@assistant-ui/core@0.3.21(@assistant-ui/store@0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0))(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(assistant-cloud@0.2.3(ai@7.0.126(zod@4.6.5)))(react@19.3.0)': dependencies: '@assistant-ui/store': 0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0) '@assistant-ui/tap': 0.9.19(@types/react@19.3.0)(react@19.3.0) @@ -5377,15 +5386,15 @@ snapshots: nanoid: 6.0.1 optionalDependencies: '@types/react': 19.3.0 - assistant-cloud: 0.2.3(ai@7.0.126(zod@3.25.76)) + assistant-cloud: 0.2.3(ai@7.0.126(zod@4.6.5)) react: 19.3.0 transitivePeerDependencies: - ioredis - redis - '@assistant-ui/react-markdown@0.14.17(@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@3.25.76))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(supports-color@10.2.2)': + '@assistant-ui/react-markdown@0.14.17(@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@4.6.5))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(supports-color@10.2.2)': dependencies: - '@assistant-ui/react': 0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@3.25.76))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)) + '@assistant-ui/react': 0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@4.6.5))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)) '@radix-ui/react-primitive': 2.1.10(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@radix-ui/react-use-callback-ref': 1.1.4(@types/react@19.3.0)(react@19.3.0) '@types/hast': 3.0.5 @@ -5399,12 +5408,12 @@ snapshots: - react-dom - supports-color - '@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@3.25.76))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0))': + '@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(ai@7.0.126(zod@4.6.5))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0))': dependencies: - '@assistant-ui/core': 0.3.21(@assistant-ui/store@0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0))(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(assistant-cloud@0.2.3(ai@7.0.126(zod@3.25.76)))(react@19.3.0) + '@assistant-ui/core': 0.3.21(@assistant-ui/store@0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0))(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(assistant-cloud@0.2.3(ai@7.0.126(zod@4.6.5)))(react@19.3.0) '@assistant-ui/store': 0.3.15(@assistant-ui/tap@0.9.19(@types/react@19.3.0)(react@19.3.0))(@types/react@19.3.0)(react@19.3.0) '@assistant-ui/tap': 0.9.19(@types/react@19.3.0)(react@19.3.0) - assistant-cloud: 0.2.3(ai@7.0.126(zod@3.25.76)) + assistant-cloud: 0.2.3(ai@7.0.126(zod@4.6.5)) assistant-stream: 0.3.45 radix-ui: 1.6.7(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react: 19.3.0 @@ -7698,14 +7707,6 @@ snapshots: - '@babel/runtime' - rolldown - ai@7.0.126(zod@3.25.76): - dependencies: - '@ai-sdk/gateway': 4.0.102(zod@3.25.76) - '@ai-sdk/provider': 4.0.21 - '@ai-sdk/provider-utils': 5.0.53(zod@3.25.76) - zod: 3.25.76 - optional: true - ai@7.0.126(zod@4.6.5): dependencies: '@ai-sdk/gateway': 4.0.102(zod@4.6.5) @@ -7746,11 +7747,11 @@ snapshots: assign-symbols@1.0.0: {} - assistant-cloud@0.2.3(ai@7.0.126(zod@3.25.76)): + assistant-cloud@0.2.3(ai@7.0.126(zod@4.6.5)): dependencies: assistant-stream: 0.3.45 optionalDependencies: - ai: 7.0.126(zod@3.25.76) + ai: 7.0.126(zod@4.6.5) transitivePeerDependencies: - ioredis - redis @@ -7912,6 +7913,10 @@ snapshots: chownr@1.1.4: optional: true + class-variance-authority@0.7.1: + dependencies: + clsx: 2.1.1 + classnames@2.5.1: {} clean-git-ref@2.0.1: {} @@ -8010,6 +8015,18 @@ snapshots: electron-to-chromium@1.5.443: {} + embla-carousel-react@8.6.0(react@19.3.0): + dependencies: + embla-carousel: 8.6.0 + embla-carousel-reactive-utils: 8.6.0(embla-carousel@8.6.0) + react: 19.3.0 + + embla-carousel-reactive-utils@8.6.0(embla-carousel@8.6.0): + dependencies: + embla-carousel: 8.6.0 + + embla-carousel@8.6.0: {} + empathic@2.1.0: {} encodeurl@2.0.0: {} @@ -8732,25 +8749,6 @@ snapshots: merge-descriptors@2.0.0: {} - micromark-core-commonmark@2.0.3: - dependencies: - decode-named-character-reference: 1.3.0 - devlop: 1.1.0 - micromark-factory-destination: 2.0.1 - micromark-factory-label: 2.0.1 - micromark-factory-space: 2.1.0 - micromark-factory-title: 2.0.1 - micromark-factory-whitespace: 2.0.1 - micromark-util-character: 2.1.1 - micromark-util-chunked: 2.0.1 - micromark-util-classify-character: 2.0.1 - micromark-util-html-tag-name: 2.0.1 - micromark-util-normalize-identifier: 2.0.1 - micromark-util-resolve-all: 2.0.1 - micromark-util-subtokenize: 2.1.0 - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - micromark-core-commonmark@2.0.4: dependencies: decode-named-character-reference: 1.3.0 @@ -8923,8 +8921,6 @@ snapshots: micromark-util-symbol@2.0.1: {} - micromark-util-types@2.0.2: {} - micromark-util-types@2.0.3: {} micromark@4.0.3(supports-color@10.2.2): @@ -9696,8 +9692,6 @@ snapshots: mrmime: 2.0.1 totalist: 3.0.1 - smol-toml@1.8.0: {} - smol-toml@1.9.0: {} sort-asc@0.2.0: {} @@ -9763,6 +9757,8 @@ snapshots: tabbable@6.5.0: {} + tailwind-merge@3.7.0: {} + tailwindcss@4.3.3: {} tapable@2.3.3: {} @@ -9828,6 +9824,8 @@ snapshots: dependencies: '@mixmark-io/domino': 2.2.0 + tw-animate-css@1.4.0: {} + type-is@2.1.0: dependencies: content-type: 2.1.0 @@ -10227,9 +10225,6 @@ snapshots: dependencies: zod: 4.6.5 - zod@3.25.76: - optional: true - zod@4.4.3: {} zod@4.6.5: {} From fe76b51f3a4e03231e92a63bc7c8f4140cbe5d83 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:57:09 +0800 Subject: [PATCH 08/18] feat(web): let the InlineCitation trigger take a custom label The upstream trigger always shows the source's hostname; a long domain like housing.illinois.edu clutters Chinese prose, so the chat passes the source number instead. --- .../components/ai-elements/inline-citation.tsx | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/ai-elements/inline-citation.tsx b/apps/web/src/components/ai-elements/inline-citation.tsx index d51f90a0..9025d7d2 100644 --- a/apps/web/src/components/ai-elements/inline-citation.tsx +++ b/apps/web/src/components/ai-elements/inline-citation.tsx @@ -35,17 +35,20 @@ export type InlineCitationCardTriggerProps = ComponentProps & { export const InlineCitationCardTrigger = ({ sources, className, + children, ...props }: InlineCitationCardTriggerProps) => ( - {sources[0] ? ( - <> - {new URL(sources[0]).hostname} {sources.length > 1 && `+${sources.length - 1}`} - - ) : ( - "unknown" - )} + {/* Local change: callers may pass their own label (IlliniGuide shows the source number). */} + {children ?? + (sources[0] ? ( + <> + {new URL(sources[0]).hostname} {sources.length > 1 && `+${sources.length - 1}`} + + ) : ( + "unknown" + ))} ) From 612ed0a4fae0b8f339e7e5750c961347a94ba1d5 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:57:31 +0800 Subject: [PATCH 09/18] feat(web): rebuild the chat thread on shadcn/ui and AI Elements Replaces the assistant-ui runtime and primitives. While a reply thinks, its header shows the current step and a timer; once the answer starts, a sources pill (AI Elements Sources) takes that place, links to those pages become numbered InlineCitation markers, and follow-up questions render as Suggestion chips. A sent question still scrolls to the top with the reply growing below it unfollowed; useTopAnchoredScroll takes over what turnAnchor="top" did. The regenerate button only renders once a handler is passed: the external-store runtime never had onReload, so it was always disabled. The inline web-search tool card is gone, since its query and count now live in the thinking steps and the sources pill. --- apps/web/package.json | 2 - apps/web/src/components/chat/ChatComposer.tsx | 152 ++++------ .../components/chat/ChatRuntimeProvider.tsx | 206 ------------- apps/web/src/components/chat/ChatThread.tsx | 151 ++++++---- .../adapters/__tests__/messageAdapter.test.ts | 122 -------- .../chat/adapters/messageAdapter.ts | 77 ----- .../chat/messages/AssistantMessage.tsx | 179 +++++------ .../chat/messages/MarkdownContent.tsx | 143 +++++++-- .../chat/messages/MessageCopyButton.tsx | 41 ++- .../chat/messages/MessageSources.tsx | 59 ++++ .../chat/messages/SourceCitation.tsx | 51 ++++ .../components/chat/messages/UserMessage.tsx | 30 +- .../chat/messages/markdownContext.ts | 20 ++ .../chat/messages/markdownLabels.ts | 13 - .../components/chat/messages/sourceUtils.ts | 44 +++ .../components/chat/tools/WebSearchToolUI.tsx | 29 -- apps/web/src/components/chat/tools/index.ts | 1 - .../components/chat/tools/toolUiHelpers.tsx | 121 -------- .../components/chat/useTopAnchoredScroll.ts | 149 +++++++++ apps/web/src/i18n/uiText.ts | 4 + apps/web/src/index.css | 12 +- apps/web/src/pages/chat/ChatPage.tsx | 16 +- pnpm-lock.yaml | 283 ------------------ 23 files changed, 750 insertions(+), 1155 deletions(-) delete mode 100644 apps/web/src/components/chat/ChatRuntimeProvider.tsx delete mode 100644 apps/web/src/components/chat/adapters/__tests__/messageAdapter.test.ts delete mode 100644 apps/web/src/components/chat/adapters/messageAdapter.ts create mode 100644 apps/web/src/components/chat/messages/MessageSources.tsx create mode 100644 apps/web/src/components/chat/messages/SourceCitation.tsx create mode 100644 apps/web/src/components/chat/messages/markdownContext.ts delete mode 100644 apps/web/src/components/chat/messages/markdownLabels.ts create mode 100644 apps/web/src/components/chat/messages/sourceUtils.ts delete mode 100644 apps/web/src/components/chat/tools/WebSearchToolUI.tsx delete mode 100644 apps/web/src/components/chat/tools/index.ts delete mode 100644 apps/web/src/components/chat/tools/toolUiHelpers.tsx create mode 100644 apps/web/src/components/chat/useTopAnchoredScroll.ts diff --git a/apps/web/package.json b/apps/web/package.json index 69389c8c..04ae543d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -7,8 +7,6 @@ "dev": "vp dev" }, "dependencies": { - "@assistant-ui/react": "^0.15.22", - "@assistant-ui/react-markdown": "0.14.17", "@headlessui/react": "^2.2.10", "@supabase/supabase-js": "^2.117.2", "class-variance-authority": "^0.7.1", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index b2fed600..9ab632fc 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1,103 +1,79 @@ -import { AuiIf, ComposerPrimitive } from "@assistant-ui/react" import { ArrowUp, Loader2 } from "lucide-react" import * as React from "react" +import { Button } from "@/components/ui/button" + interface ChatComposerProps { placeholder: string hint: string + /** A reply is streaming; sending is blocked until it finishes. */ + isRunning: boolean + onSend: (text: string) => void } -const toTextareaValue = (value: React.TextareaHTMLAttributes["value"]) => { - if (Array.isArray(value)) { - return value.join(",") - } - - return value?.toString() ?? "" -} - -const isNativeInputComposing = (event: React.ChangeEvent) => - event.nativeEvent instanceof InputEvent && event.nativeEvent.isComposing - -const ImeSafeComposerTextarea = React.forwardRef< - HTMLTextAreaElement, - React.TextareaHTMLAttributes ->(({ onChange, onCompositionEnd, onCompositionStart, value, ...props }, ref) => { - const isComposingRef = React.useRef(false) - const [compositionValue, setCompositionValue] = React.useState("") - const controlledValue = toTextareaValue(value) - - const handleCompositionStart = (event: React.CompositionEvent) => { - isComposingRef.current = true - setCompositionValue(event.currentTarget.value) - onCompositionStart?.(event) - } - - const handleChange = (event: React.ChangeEvent) => { - if (isComposingRef.current || isNativeInputComposing(event)) { - setCompositionValue(event.currentTarget.value) - } +/** + * Auto-growing input with a send button that turns into a spinner while a + * reply is running. Enter sends and Shift + Enter adds a line; an Enter that + * confirms an IME candidate (e.g. pinyin) is left to the IME. The textarea + * grows with its content via `field-sizing: content`, capped at ~8 lines. + */ +export const ChatComposer = ({ placeholder, hint, isRunning, onSend }: ChatComposerProps) => { + const [value, setValue] = React.useState("") + const canSend = !isRunning && value.trim().length > 0 - onChange?.(event) + const submit = () => { + if (!canSend) return + onSend(value) + setValue("") } - const handleCompositionEnd = (event: React.CompositionEvent) => { - isComposingRef.current = false - setCompositionValue(event.currentTarget.value) - onCompositionEnd?.(event) + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return + event.preventDefault() + submit() } return ( -