Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: inline MCP approval, citation cards, and RAG grounding markers (#8140)
Akarshan Biswasc7cd78612fe4
diff --git a/core/src/browser/extensions/rag.ts b/core/src/browser/extensions/rag.tsindex 15addfb52..1886e52b1 100644--- a/core/src/browser/extensions/rag.ts+++ b/core/src/browser/extensions/rag.ts@@ -43,4 +43,10 @@ export abstract class RAGExtension extends BaseExtension {* Parse a document into plain text for inline ingestion or preprocessing.*/abstract parseDocument(path: string, type?: string): Promise<string>++ /**+ * Embed a batch of texts using the configured embedding model.+ * Returns one vector per input in input order.+ */+ abstract embed(texts: string[]): Promise<number[][]>}diff --git a/extensions/rag-extension/src/index.ts b/extensions/rag-extension/src/index.tsindex e73fc5848..b61af08b0 100644--- a/extensions/rag-extension/src/index.ts+++ b/extensions/rag-extension/src/index.ts@@ -518,6 +518,11 @@ export default class RagExtension extends RAGExtension {return await ragApi.parseDocument(path, type || 'application/octet-stream')}+ async embed(texts: string[]): Promise<number[][]> {+ if (!texts || texts.length === 0) return []+ return this.embedTexts(texts)+ }+// Locally implement embedding logic (previously in embeddings-extension)private async embedTexts(texts: string[]): Promise<number[][]> {const llm = window.core?.extensionManager.getByName(diff --git a/web-app/src/components/CitationLink.tsx b/web-app/src/components/CitationLink.tsxnew file mode 100644index 000000000..c2ec814d0--- /dev/null+++ b/web-app/src/components/CitationLink.tsx@@ -0,0 +1,90 @@+import { memo, useMemo } from 'react'+import { FileTextIcon } from 'lucide-react'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import { useGroundingStore } from '@/stores/grounding-store'+import { useAttachmentName } from '@/hooks/useAttachmentNames'+import { cn } from '@/lib/utils'++const HREF_RE = /^#cite-(.+)-(\d+)$/++type Parsed = { messageId: string; index: number } | null++const parseHref = (href: string | undefined): Parsed => {+ if (!href) return null+ const m = HREF_RE.exec(href)+ if (!m) return null+ return { messageId: m[1], index: Number(m[2]) - 1 }+}++export const CitationLink = memo(+ ({+ href,+ children,+ className,+ }: {+ href?: string+ children?: React.ReactNode+ className?: string+ }) => {+ const parsed = useMemo(() => parseHref(href), [href])++ const citation = useGroundingStore((s) => {+ if (!parsed) return undefined+ return s.byMessageId[parsed.messageId]?.citations[parsed.index]+ })++ const filename = useAttachmentName(citation?.file_id)++ if (!parsed || !citation) {+ return (+ <a href={href} className={className}>+ {children}+ </a>+ )+ }++ return (+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className={cn(+ 'no-underline text-primary hover:text-primary/80 mx-0.5 align-super text-[0.7em] cursor-pointer',+ className+ )}+ >+ {children}+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ side="top"+ className="w-80 p-3 text-xs space-y-2"+ >+ <div className="flex items-center gap-2">+ <FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate font-medium">+ {filename || `${citation.file_id.slice(0, 8)}…`}+ </span>+ {typeof citation.chunk_file_order === 'number' && (+ <span className="text-muted-foreground">+ #{citation.chunk_file_order}+ </span>+ )}+ <span className="ml-auto rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">+ {typeof citation.score === 'number' ? citation.score.toFixed(2) : ''}+ </span>+ </div>+ <p className="whitespace-pre-wrap text-muted-foreground leading-relaxed max-h-60 overflow-auto">+ {citation.text}+ </p>+ </PopoverContent>+ </Popover>+ )+ }+)+CitationLink.displayName = 'CitationLink'diff --git a/web-app/src/components/Citations.tsx b/web-app/src/components/Citations.tsxnew file mode 100644index 000000000..db0f78351--- /dev/null+++ b/web-app/src/components/Citations.tsx@@ -0,0 +1,213 @@+import { memo, useMemo, useState } from 'react'+import { FileTextIcon, GlobeIcon, ChevronRightIcon } from 'lucide-react'+import { cn } from '@/lib/utils'+import {+ useAttachmentName,+ useEnsureAttachmentNames,+} from '@/hooks/useAttachmentNames'++export type RagCitation = {+ id: string+ text: string+ score: number+ file_id: string+ chunk_file_order?: number+}++export type WebCitation = {+ url: string+ title?: string+ text?: string+ score?: number+ published_date?: string+ author?: string+ favicon?: string+}++export type CitationsPayload =+ | {+ kind: 'rag'+ query?: string+ scope?: 'thread' | 'project'+ threadId?: string+ projectId?: string+ citations: RagCitation[]+ }+ | {+ kind: 'web'+ query?: string+ citations: WebCitation[]+ }++const formatScore = (s: number | undefined) =>+ typeof s === 'number' ? s.toFixed(2) : ''++const RagCitationItem = memo(+ ({+ c,+ index,+ anchorId,+ }: {+ c: RagCitation+ index: number+ anchorId?: string+ }) => {+ const [expanded, setExpanded] = useState(false)+ const name = useAttachmentName(c.file_id) || `${c.file_id.slice(0, 8)}…`+ return (+ <li+ id={anchorId}+ className="scroll-mt-16 rounded-md border bg-card/40 px-3 py-2 text-xs target:ring-2 target:ring-primary/60"+ >+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="flex w-full items-center gap-2 text-left"+ >+ <span className="inline-flex size-5 shrink-0 items-center justify-center rounded bg-muted font-mono text-[10px] text-muted-foreground">+ {index + 1}+ </span>+ <FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate font-medium">{name}</span>+ {typeof c.chunk_file_order === 'number' && (+ <span className="text-muted-foreground">#{c.chunk_file_order}</span>+ )}+ <span className="ml-auto rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">+ {formatScore(c.score)}+ </span>+ <ChevronRightIcon+ className={cn(+ 'size-3 shrink-0 text-muted-foreground transition-transform',+ expanded && 'rotate-90'+ )}+ />+ </button>+ {expanded && c.text && (+ <p className="mt-2 whitespace-pre-wrap text-muted-foreground leading-relaxed">+ {c.text}+ </p>+ )}+ </li>+ )+ }+)+RagCitationItem.displayName = 'RagCitationItem'++const WebCitationItem = memo(({ c }: { c: WebCitation }) => {+ const [expanded, setExpanded] = useState(false)+ let host = ''+ try {+ host = new URL(c.url).hostname.replace(/^www\./, '')+ } catch {+ host = c.url+ }+ return (+ <li className="rounded-md border bg-card/40 px-3 py-2 text-xs">+ <div className="flex items-center gap-2">+ {c.favicon ? (+ <img src={c.favicon} alt="" className="size-3.5 rounded-sm" />+ ) : (+ <GlobeIcon className="size-3.5 shrink-0 text-muted-foreground" />+ )}+ <a+ href={c.url}+ target="_blank"+ rel="noreferrer noopener"+ className="truncate font-medium hover:underline"+ title={c.url}+ >+ {c.title || host}+ </a>+ <span className="ml-auto truncate text-[10px] text-muted-foreground">+ {host}+ </span>+ {typeof c.score === 'number' && (+ <span className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">+ {formatScore(c.score)}+ </span>+ )}+ {c.text && (+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className="text-muted-foreground"+ aria-label="toggle snippet"+ >+ <ChevronRightIcon+ className={cn(+ 'size-3 transition-transform',+ expanded && 'rotate-90'+ )}+ />+ </button>+ )}+ </div>+ {expanded && c.text && (+ <p className="mt-2 whitespace-pre-wrap text-muted-foreground leading-relaxed">+ {c.text}+ </p>+ )}+ </li>+ )+})+WebCitationItem.displayName = 'WebCitationItem'++export const Citations = memo(+ ({+ payload,+ anchorPrefix,+ }: {+ payload: CitationsPayload+ anchorPrefix?: string+ }) => {+ useEnsureAttachmentNames(+ payload.kind === 'rag' ? payload.scope : undefined,+ payload.kind === 'rag'+ ? payload.scope === 'project'+ ? payload.projectId+ : payload.threadId+ : undefined+ )++ const items = useMemo(() => {+ if (payload.kind === 'rag') {+ return payload.citations.map((c, i) => (+ <RagCitationItem+ key={c.id}+ c={c}+ index={i}+ anchorId={anchorPrefix ? `${anchorPrefix}-${i + 1}` : undefined}+ />+ ))+ }+ return payload.citations.map((c, i) => (+ <WebCitationItem key={`${c.url}-${i}`} c={c} />+ ))+ }, [payload, anchorPrefix])++ if (!items.length) return null++ const heading =+ payload.kind === 'rag'+ ? `${payload.citations.length} document ${+ payload.citations.length === 1 ? 'citation' : 'citations'+ }`+ : `${payload.citations.length} web ${+ payload.citations.length === 1 ? 'source' : 'sources'+ }`++ return (+ <div className="mt-4 space-y-2">+ <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">+ {heading}+ {payload.query && (+ <span className="ml-2 normal-case font-normal text-muted-foreground/70">+ for “{payload.query}”+ </span>+ )}+ </h4>+ <ul className="space-y-1.5">{items}</ul>+ </div>+ )+})+Citations.displayName = 'Citations'diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsxindex b0aec5205..660fafdb1 100644--- a/web-app/src/components/ai-elements/tool.tsx+++ b/web-app/src/components/ai-elements/tool.tsx@@ -16,14 +16,22 @@ import {useContext,useEffect,useMemo,+ useRef,useState,} from 'react'import { CodeBlock } from './code-block'+import { useToolApproval } from '@/hooks/useToolApproval'+import { Button } from '@/components/ui/button'+import { ShieldAlertIcon } from 'lucide-react'+import { Citations } from '@/components/Citations'+import { parseCitationsFromToolOutput } from '@/lib/citation-parser'type ToolContextValue = {isOpen: booleansetIsOpen: (open: boolean) => voidstate: ToolUIPart['state']+ toolCallId?: string+ messageId?: string}const ToolContext = createContext<ToolContextValue | null>(null)@@ -39,6 +47,8 @@ export const useTool = () => {export type ToolProps = ComponentProps<typeof Collapsible> & {className?: stringstate: ToolUIPart['state']+ toolCallId?: string+ messageId?: stringopen?: booleandefaultOpen?: booleanonOpenChange?: (open: boolean) => void@@ -48,24 +58,41 @@ export const Tool = memo(({className,state,+ toolCallId,+ messageId,open,defaultOpen = false,onOpenChange,children,...props}: ToolProps) => {+ const isPending = useToolApproval((s) =>+ toolCallId ? Boolean(s.pending[toolCallId]) : false+ )const [isOpen, setIsOpen] = useControllableState({prop: open,- defaultProp: defaultOpen,+ defaultProp: defaultOpen || isPending,onChange: onOpenChange,})+ const wasPendingRef = useRef(isPending)+ useEffect(() => {+ if (isPending && !wasPendingRef.current) {+ setIsOpen(true)+ } else if (!isPending && wasPendingRef.current) {+ setIsOpen(false)+ }+ wasPendingRef.current = isPending+ }, [isPending, setIsOpen])+const handleOpenChange = (newOpen: boolean) => {setIsOpen(newOpen)}return (- <ToolContext.Provider value={{ isOpen, setIsOpen, state }}>+ <ToolContext.Provider+ value={{ isOpen, setIsOpen, state, toolCallId, messageId }}+ ><CollapsibleclassName={cn('not-prose', className)}onOpenChange={handleOpenChange}@@ -86,11 +113,18 @@ export type ToolHeaderProps = {className?: string}-const getStatusText = (status: ToolUIPart['state'], toolName: string) => {+const getStatusText = (+ status: ToolUIPart['state'],+ toolName: string,+ awaitingApproval: boolean+) => {const isRunning = status === 'input-streaming' || status === 'input-available'// @ts-expect-error state only available in AI SDK v6const hasError = status === 'output-error' || status === 'output-denied'+ if (awaitingApproval) {+ return `Awaiting approval: ${toolName.replaceAll('_', ' ')}`+ }if (isRunning) {return `Running ${toolName.replaceAll('_', ' ')}...`}@@ -102,7 +136,10 @@ const getStatusText = (status: ToolUIPart['state'], toolName: string) => {export const ToolHeader = memo(({ className, title, state, type }: ToolHeaderProps) => {- const { isOpen } = useTool()+ const { isOpen, toolCallId } = useTool()+ const awaitingApproval = useToolApproval((s) =>+ toolCallId ? Boolean(s.pending[toolCallId]) : false+ )const toolName = title ?? type.split('-').slice(1).join('-')return (@@ -112,8 +149,14 @@ export const ToolHeader = memo(className)}>- <WrenchIcon className="size-4" />- <span>{getStatusText(state, toolName)}</span>+ {awaitingApproval ? (+ <ShieldAlertIcon className="size-4 text-amber-500" />+ ) : (+ <WrenchIcon className="size-4" />+ )}+ <span className={cn(awaitingApproval && 'text-amber-600 dark:text-amber-400')}>+ {getStatusText(state, toolName, awaitingApproval)}+ </span><ChevronDownIconclassName={cn('size-4 transition-transform',@@ -150,19 +193,77 @@ export type ToolInputProps = ComponentProps<'div'> & {export const ToolInput = memo(({ className, input, ...props }: ToolInputProps) => {+ const formatted = useMemo(() => {+ let value: unknown = input+ if (typeof value === 'string') {+ try {+ value = JSON.parse(value)+ } catch {+ return value as string+ }+ }+ try {+ return JSON.stringify(value, null, 2)+ } catch {+ return String(value)+ }+ }, [input])+return (<div className={cn('space-y-2', className)} {...props}><h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">Parameters</h4><div className="rounded-md max-h-40 overflow-auto border ">- <CodeBlock code={JSON.stringify(input, null, 2)} language="json" />+ <CodeBlock code={formatted} language="json" /></div></div>)})+export const ToolApprovalActions = memo(() => {+ const { toolCallId } = useTool()+ const pending = useToolApproval((s) =>+ toolCallId ? s.pending[toolCallId] : undefined+ )+ const resolveApproval = useToolApproval((s) => s.resolveApproval)++ if (!pending || !toolCallId) return null++ return (+ <div className="mt-4 space-y-2 rounded-md border border-amber-500/30 bg-amber-500/5 p-3">+ <div className="flex items-center gap-2 text-amber-700 dark:text-amber-300 text-xs font-medium">+ <ShieldAlertIcon className="size-4" />+ <span>This tool needs your approval before it runs.</span>+ </div>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ variant="destructive"+ onClick={() => resolveApproval(toolCallId, 'deny')}+ >+ Deny+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => resolveApproval(toolCallId, 'allow-once')}+ >+ Allow once+ </Button>+ <Button+ size="sm"+ autoFocus+ onClick={() => resolveApproval(toolCallId, 'allow-always')}+ >+ Always allow+ </Button>+ </div>+ </div>+ )+})+type ToolImageProps = {data: stringindex: number@@ -218,11 +319,26 @@ export type ToolOutputProps = ComponentProps<'div'> & {export const ToolOutput = memo(({ className, output, errorText, resolver, ...props }: ToolOutputProps) => {+ const { messageId } = useTool()+ const citationPayload = useMemo(+ () => (output ? parseCitationsFromToolOutput(output) : null),+ [output]+ )+const Output = useMemo(() => {if (!(output || errorText)) {return null}+ if (citationPayload) {+ return (+ <Citations+ payload={citationPayload}+ anchorPrefix={messageId ? `cite-${messageId}` : undefined}+ />+ )+ }+// Handle string outputif (typeof output === 'string') {return (@@ -338,7 +454,7 @@ export const ToolOutput = memo(}return <div>{output as ReactNode}</div>- }, [output, errorText, resolver])+ }, [output, errorText, resolver, citationPayload, messageId])if (!(output || errorText)) {return null@@ -367,3 +483,4 @@ ToolHeader.displayName = 'ToolHeader'ToolContent.displayName = 'ToolContent'ToolInput.displayName = 'ToolInput'ToolOutput.displayName = 'ToolOutput'+ToolApprovalActions.displayName = 'ToolApprovalActions'diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 02a9b61f0..c5036af78 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -1,5 +1,5 @@/* eslint-disable @typescript-eslint/no-explicit-any */-import { memo, useState, useCallback } from 'react'+import { memo, useState, useCallback, useEffect } from 'react'import type { UIMessage, ChatStatus } from 'ai'import { RenderMarkdown } from './RenderMarkdown'import { cn } from '@/lib/utils'@@ -12,6 +12,7 @@ import {import { Streamdown } from 'streamdown'import {Tool,+ ToolApprovalActions,ToolContent,ToolHeader,ToolInput,@@ -28,6 +29,11 @@ import { extractFilesFromPrompt, FileMetadata } from '@/lib/fileMetadata'import { useMemo } from 'react'import { Button } from '@/components/ui/button'import { PromptProgress } from '@/components/PromptProgress'+import { useServiceHub } from '@/hooks/useServiceHub'+import { parseCitationsFromToolOutput } from '@/lib/citation-parser'+import type { RagCitation } from '@/components/Citations'+import { useGroundingStore } from '@/stores/grounding-store'+import { injectCitationMarkers } from '@/lib/grounding'const CHAT_STATUS = {STREAMING: 'streaming',@@ -118,7 +124,11 @@ export const MessageItem = memo(return message.parts.some((part) => {if (!part.type?.startsWith('tool-')) return falseconst state = (part as { state?: string }).state- return state !== 'output-available' && state !== 'output-error'+ return (+ state !== 'output-available' &&+ state !== 'output-error' &&+ state !== 'output-denied'+ )})}, [isLastMessage, message.role, message.parts])@@ -128,6 +138,50 @@ export const MessageItem = memo(status === CHAT_STATUS.SUBMITTED)) ||hasPendingToolCall+ const ragCitations = useMemo<RagCitation[]>(() => {+ if (message.role !== 'assistant') return []+ const out: RagCitation[] = []+ for (const part of message.parts as any[]) {+ if (!part.type?.startsWith('tool-')) continue+ if (part.state !== 'output-available') continue+ const parsed = parseCitationsFromToolOutput(part.output)+ if (parsed?.kind === 'rag') out.push(...parsed.citations)+ }+ return out+ }, [message.parts, message.role])++ const serviceHub = useServiceHub()+ const grounding = useGroundingStore((s) => s.byMessageId[message.id])+ const ensureGrounding = useGroundingStore((s) => s.ensure)++ const assistantText = useMemo(() => {+ if (message.role !== 'assistant') return ''+ return (message.parts as any[])+ .filter((p) => p.type === CONTENT_TYPE.TEXT && p.text)+ .map((p) => p.text)+ .join('\n')+ }, [message.parts, message.role])++ useEffect(() => {+ if (isStreaming) return+ if (!assistantText || !ragCitations.length) return+ const rag = serviceHub.rag()+ if (!rag.embed) return+ ensureGrounding(+ message.id,+ assistantText,+ ragCitations,+ rag.embed.bind(rag)+ )+ }, [+ isStreaming,+ assistantText,+ ragCitations,+ message.id,+ ensureGrounding,+ serviceHub,+ ])+// Extract file metadata from message text (for user messages with attachments)const attachedFiles = useMemo(() => {if (message.role !== 'user') return []@@ -215,7 +269,15 @@ export const MessageItem = memo() : (<><RenderMarkdown- content={part.text}+ content={+ grounding && !isStreaming+ ? injectCitationMarkers(+ part.text,+ grounding.sentenceCitations,+ `cite-${message.id}`+ )+ : part.text+ }isStreaming={isStreaming && isLastPart}messageId={message.id}isAnimating={isAnimating}@@ -314,6 +376,8 @@ export const MessageItem = memo(<Toolkey={`${message.id}-${partIndex}`}state={part.state}+ toolCallId={part.toolCallId}+ messageId={message.id}className="mb-1"><ToolHeader@@ -322,15 +386,8 @@ export const MessageItem = memo(state={part.state}/><ToolContent title={toolName}>- {part.input && (- <ToolInput- input={- typeof part.input === 'string'- ? part.input- : JSON.stringify(part.input)- }- />- )}+ {part.input && <ToolInput input={part.input} />}+ <ToolApprovalActions />{part.output && (<ToolOutputoutput={part.output}@@ -482,7 +539,7 @@ export const MessageItem = memo(return elements// eslint-disable-next-line react-hooks/exhaustive-deps- }, [message.parts, isStreaming, isReasoningAtBottom])+ }, [message.parts, isStreaming, isReasoningAtBottom, grounding])return (<div className="w-full mb-4">diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsxindex b888a46cd..d38acf036 100644--- a/web-app/src/containers/RenderMarkdown.tsx+++ b/web-app/src/containers/RenderMarkdown.tsx@@ -14,6 +14,7 @@ import remarkMath from 'remark-math'import rehypeKatex from 'rehype-katex'import 'katex/dist/katex.min.css'import { MermaidError } from '@/components/MermaidError'+import { CitationLink } from '@/components/CitationLink'interface MarkdownProps {content: string@@ -103,6 +104,23 @@ function RenderMarkdownComponent({// Memoize the normalized content to avoid reprocessing on every renderconst normalizedContent = useMemo(() => normalizeLatex(content), [content])+ const mergedComponents = useMemo<Components>(() => {+ const Anchor = (+ props: React.AnchorHTMLAttributes<HTMLAnchorElement>+ ) => {+ const { href, children, className: aClass } = props+ if (typeof href === 'string' && href.startsWith('#cite-')) {+ return (+ <CitationLink href={href} className={aClass}>+ {children}+ </CitationLink>+ )+ }+ return <a {...props}>{children}</a>+ }+ return { a: Anchor, ...(components ?? {}) } as Components+ }, [components])+const streamdownEl = (<Streamdownanimate={isAnimating ?? true}@@ -119,7 +137,7 @@ function RenderMarkdownComponent({rehypeKatex,defaultRehypePlugins.harden,]}- components={components}+ components={mergedComponents}plugins={{code: code,mermaid: mermaid,diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex c8b5a6955..8d36d8189 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -38,6 +38,7 @@ vi.mock('@/components/ai-elements/tool', () => ({ToolOutput: ({ output, errorText }: any) => (<div data-testid="tool-output">{errorText ?? String(output ?? '')}</div>),+ ToolApprovalActions: () => null,}))// Stub dialogsdiff --git a/web-app/src/hooks/useAttachmentNames.ts b/web-app/src/hooks/useAttachmentNames.tsnew file mode 100644index 000000000..a17faf11a--- /dev/null+++ b/web-app/src/hooks/useAttachmentNames.ts@@ -0,0 +1,78 @@+import { useEffect } from 'react'+import { create } from 'zustand'+import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'+import { ExtensionManager } from '@/lib/extension'++type AttachmentNamesState = {+ byId: Record<string, string>+ loading: Record<string, boolean>+ loadedScopes: Record<string, boolean>+ ensure: (scope: 'thread' | 'project', id: string) => void+}++const scopeKey = (scope: 'thread' | 'project', id: string) => `${scope}:${id}`++export const useAttachmentNamesStore = create<AttachmentNamesState>(+ (set, get) => ({+ byId: {},+ loading: {},+ loadedScopes: {},++ ensure: (scope, id) => {+ if (!id) return+ const key = scopeKey(scope, id)+ const state = get()+ if (state.loadedScopes[key] || state.loading[key]) return++ set((s) => ({ loading: { ...s.loading, [key]: true } }))+ const ext = ExtensionManager.getInstance().get<VectorDBExtension>(+ ExtensionTypeEnum.VectorDB+ )+ const fetcher =+ scope === 'project'+ ? ext?.listAttachmentsForProject?.bind(ext)+ : ext?.listAttachments?.bind(ext)++ if (!fetcher) {+ set((s) => ({+ loading: { ...s.loading, [key]: false },+ loadedScopes: { ...s.loadedScopes, [key]: true },+ }))+ return+ }++ fetcher(id)+ .then((files) => {+ const next: Record<string, string> = {}+ for (const f of files || []) {+ if (f?.id && f?.name) next[f.id] = f.name+ }+ set((s) => ({+ byId: { ...s.byId, ...next },+ loading: { ...s.loading, [key]: false },+ loadedScopes: { ...s.loadedScopes, [key]: true },+ }))+ })+ .catch(() => {+ set((s) => ({+ loading: { ...s.loading, [key]: false },+ loadedScopes: { ...s.loadedScopes, [key]: true },+ }))+ })+ },+ })+)++export function useAttachmentName(fileId: string | undefined): string | undefined {+ return useAttachmentNamesStore((s) => (fileId ? s.byId[fileId] : undefined))+}++export function useEnsureAttachmentNames(+ scope: 'thread' | 'project' | undefined,+ id: string | undefined+) {+ const ensure = useAttachmentNamesStore((s) => s.ensure)+ useEffect(() => {+ if (scope && id) ensure(scope, id)+ }, [scope, id, ensure])+}diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.tsindex 0e49cb462..171161ee6 100644--- a/web-app/src/hooks/useToolApproval.ts+++ b/web-app/src/hooks/useToolApproval.ts@@ -10,19 +10,28 @@ export type ToolApprovalModalProps = {onDeny: () => void}+export type PendingApproval = {+ toolCallId: string+ toolName: string+ threadId: string+ resolve: (approved: boolean) => void+}++export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'+type ToolApprovalState = {- // Track approved tools per thread- approvedTools: Record<string, string[]> // threadId -> toolNames[]- // Global MCP permission toggle+ approvedTools: Record<string, string[]>allowAllMCPPermissions: boolean- // Modal stateisModalOpen: booleanmodalProps: ToolApprovalModalProps | null+ pending: Record<string, PendingApproval>- // ActionsapproveToolForThread: (threadId: string, toolName: string) => voidisToolApproved: (threadId: string, toolName: string) => booleanshowApprovalModal: (toolName: string, threadId: string, toolParameters?: object) => Promise<boolean>+ requestApproval: (toolCallId: string, toolName: string, threadId: string) => Promise<boolean>+ resolveApproval: (toolCallId: string, decision: ApprovalDecision) => void+ isApprovalPending: (toolCallId: string) => booleancloseModal: () => voidsetModalOpen: (open: boolean) => voidsetAllowAllMCPPermissions: (allow: boolean) => void@@ -35,6 +44,7 @@ export const useToolApproval = create<ToolApprovalState>()(allowAllMCPPermissions: false,isModalOpen: false,modalProps: null,+ pending: {},approveToolForThread: (threadId: string, toolName: string) => {set((state) => ({@@ -92,6 +102,44 @@ export const useToolApproval = create<ToolApprovalState>()(})},+ requestApproval: (toolCallId, toolName, threadId) => {+ return new Promise<boolean>((resolve) => {+ const state = get()+ if (state.allowAllMCPPermissions) {+ resolve(true)+ return+ }+ if (state.isToolApproved(threadId, toolName)) {+ resolve(true)+ return+ }+ set((s) => ({+ pending: {+ ...s.pending,+ [toolCallId]: { toolCallId, toolName, threadId, resolve },+ },+ }))+ })+ },++ resolveApproval: (toolCallId, decision) => {+ const entry = get().pending[toolCallId]+ if (!entry) return+ if (decision === 'allow-always') {+ get().approveToolForThread(entry.threadId, entry.toolName)+ }+ set((s) => {+ const next = { ...s.pending }+ delete next[toolCallId]+ return { pending: next }+ })+ entry.resolve(decision !== 'deny')+ },++ isApprovalPending: (toolCallId) => {+ return Boolean(get().pending[toolCallId])+ },+closeModal: () => {set({isModalOpen: false,diff --git a/web-app/src/lib/citation-parser.ts b/web-app/src/lib/citation-parser.tsnew file mode 100644index 000000000..9483547ed--- /dev/null+++ b/web-app/src/lib/citation-parser.ts@@ -0,0 +1,110 @@+import type { CitationsPayload, RagCitation, WebCitation } from '@/components/Citations'++const tryParseJson = (s: string): unknown => {+ try {+ return JSON.parse(s)+ } catch {+ return null+ }+}++const isRagCitation = (x: unknown): x is RagCitation => {+ if (!x || typeof x !== 'object') return false+ const o = x as Record<string, unknown>+ return (+ typeof o.id === 'string' &&+ typeof o.text === 'string' &&+ typeof o.file_id === 'string'+ )+}++const isWebCitation = (x: unknown): x is WebCitation => {+ if (!x || typeof x !== 'object') return false+ const o = x as Record<string, unknown>+ return typeof o.url === 'string' && /^https?:\/\//.test(o.url)+}++const isTextItem = (it: unknown): it is { type: string; text: string } =>+ !!it &&+ typeof it === 'object' &&+ (it as { type?: string }).type === 'text' &&+ typeof (it as { text?: string }).text === 'string'++const extractTextItems = (output: unknown): string[] => {+ if (typeof output === 'string') return [output]+ if (Array.isArray(output)) {+ return output.filter(isTextItem).map((it) => it.text)+ }+ if (!output || typeof output !== 'object') return []+ const o = output as { content?: unknown }+ if (Array.isArray(o.content)) {+ return o.content.filter(isTextItem).map((it) => it.text)+ }+ return []+}++const fromRagPayload = (obj: Record<string, unknown>): CitationsPayload | null => {+ const citations = obj.citations+ if (!Array.isArray(citations)) return null+ const filtered = citations.filter(isRagCitation)+ if (!filtered.length) return null+ const scope = obj.scope === 'project' ? 'project' : 'thread'+ return {+ kind: 'rag',+ query: typeof obj.query === 'string' ? obj.query : undefined,+ scope,+ threadId: typeof obj.thread_id === 'string' ? obj.thread_id : undefined,+ projectId: typeof obj.project_id === 'string' ? obj.project_id : undefined,+ citations: filtered,+ }+}++const fromWebPayload = (obj: unknown): CitationsPayload | null => {+ let arr: unknown[] | null = null+ let query: string | undefined++ if (Array.isArray(obj)) {+ arr = obj+ } else if (obj && typeof obj === 'object') {+ const o = obj as Record<string, unknown>+ if (typeof o.query === 'string') query = o.query+ for (const key of ['results', 'citations', 'sources', 'data']) {+ const v = o[key]+ if (Array.isArray(v)) {+ arr = v+ break+ }+ }+ }++ if (!arr) return null+ const filtered = arr.filter(isWebCitation)+ if (!filtered.length) return null+ return { kind: 'web', query, citations: filtered }+}++export function parseCitationsFromToolOutput(+ output: unknown+): CitationsPayload | null {+ const texts = extractTextItems(output)+ for (const text of texts) {+ const parsed = tryParseJson(text)+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ const rag = fromRagPayload(parsed as Record<string, unknown>)+ if (rag) return rag+ }+ if (parsed !== null) {+ const web = fromWebPayload(parsed)+ if (web) return web+ }+ }++ if (output && typeof output === 'object' && !Array.isArray(output)) {+ const rag = fromRagPayload(output as Record<string, unknown>)+ if (rag) return rag+ }+ const web = fromWebPayload(output)+ if (web) return web++ return null+}diff --git a/web-app/src/lib/grounding.ts b/web-app/src/lib/grounding.tsnew file mode 100644index 000000000..3a85d19bb--- /dev/null+++ b/web-app/src/lib/grounding.ts@@ -0,0 +1,134 @@+import type { RagCitation } from '@/components/Citations'++const SENTENCE_BOUNDARY = /([^.!?\n]+[.!?]+(?:["')\]]+)?|\S[^\n]*$)/g++const stripMarkdown = (s: string): string =>+ s+ .replace(/^\s*[-*+]\s+/, '')+ .replace(/^\s*\d+\.\s+/, '')+ .replace(/\*{1,3}([^*]+)\*{1,3}/g, '$1')+ .replace(/_{1,3}([^_\n]+)_{1,3}/g, '$1')+ .replace(/`([^`]+)`/g, '$1')+ .replace(/~~([^~]+)~~/g, '$1')+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')+ .replace(/\s+/g, ' ')+ .trim()++export type Sentence = { formatted: string; plain: string }++export function splitSentences(text: string): Sentence[] {+ if (!text) return []+ const out: Sentence[] = []+ const re = new RegExp(SENTENCE_BOUNDARY.source, 'g')+ let m: RegExpExecArray | null+ while ((m = re.exec(text)) !== null) {+ const formatted = m[0].trim()+ if (!formatted) continue+ const plain = stripMarkdown(formatted)+ if (plain.length >= 12) out.push({ formatted, plain })+ }+ return out+}++export function cosine(a: number[], b: number[]): number {+ if (!a || !b || a.length !== b.length || a.length === 0) return 0+ let dot = 0+ let na = 0+ let nb = 0+ for (let i = 0; i < a.length; i++) {+ dot += a[i] * b[i]+ na += a[i] * a[i]+ nb += b[i] * b[i]+ }+ if (na === 0 || nb === 0) return 0+ return dot / (Math.sqrt(na) * Math.sqrt(nb))+}++export type GroundingResult = {+ sentenceCitations: Record<string, number[]>+ citations: RagCitation[]+}++export async function computeGrounding(opts: {+ text: string+ citations: RagCitation[]+ embed: (texts: string[]) => Promise<number[][]>+ threshold?: number+ topK?: number+}): Promise<GroundingResult> {+ const { text, citations } = opts+ const threshold = opts.threshold ?? 0.65+ const topK = opts.topK ?? 1+ const sentences = splitSentences(text)+ if (!sentences.length || !citations.length) {+ return { sentenceCitations: {}, citations }+ }++ const chunkTexts = citations.map((c) => stripMarkdown(c.text || ''))+ const all = await opts.embed([+ ...sentences.map((s) => s.plain),+ ...chunkTexts,+ ])+ if (!all || all.length !== sentences.length + chunkTexts.length) {+ return { sentenceCitations: {}, citations }+ }+ const sentenceEmb = all.slice(0, sentences.length)+ const chunkEmb = all.slice(sentences.length)++ const map: Record<string, number[]> = {}+ for (let i = 0; i < sentences.length; i++) {+ const scored = chunkEmb+ .map((e, j) => ({ j, s: cosine(sentenceEmb[i], e) }))+ .filter((x) => x.s >= threshold)+ .sort((a, b) => b.s - a.s)+ .slice(0, topK)+ .map((x) => x.j)+ if (scored.length) map[sentences[i].formatted] = scored+ }++ return { sentenceCitations: map, citations }+}++const FENCE_RE = /```[\s\S]*?```/g+const INLINE_CODE_RE = /`[^`\n]+`/g++const SUP_DIGITS = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']+const toSuperscript = (n: number): string =>+ String(n)+ .split('')+ .map((d) => SUP_DIGITS[Number(d)] ?? d)+ .join('')++export function injectCitationMarkers(+ markdown: string,+ sentenceCitations: Record<string, number[]>,+ anchorPrefix: string+): string {+ if (!markdown || !Object.keys(sentenceCitations).length) return markdown++ const codeSpans: string[] = []+ const stashOne = (m: string) => {+ codeSpans.push(m)+ return ` §${codeSpans.length - 1}§ `+ }+ let stash = markdown.replace(FENCE_RE, stashOne).replace(INLINE_CODE_RE, stashOne)++ const sentences = Object.keys(sentenceCitations).sort(+ (a, b) => b.length - a.length+ )+ for (const sentence of sentences) {+ const indices = sentenceCitations[sentence]+ if (!indices?.length) continue+ const marker = indices+ .map(+ (i) =>+ `[${toSuperscript(i + 1)}](#${anchorPrefix}-${i + 1})`+ )+ .join('')+ const esc = sentence.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')+ stash = stash.replace(new RegExp(esc), `${sentence}${marker}`)+ }++ stash = stash.replace(/ §(\d+)§ /g, (_, i) => codeSpans[Number(i)])+ return stash+}diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex 57dd07d95..0eaa11806 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -293,7 +293,7 @@ function ThreadDetail() {? true: await useToolApproval.getState()- .showApprovalModal(toolName, threadId, toolCall.input)+ .requestApproval(toolCall.toolCallId, toolName, threadId)if (!approved) {// User denied the tool calldiff --git a/web-app/src/services/rag/default.ts b/web-app/src/services/rag/default.tsindex a576eaabf..3f9712c00 100644--- a/web-app/src/services/rag/default.ts+++ b/web-app/src/services/rag/default.ts@@ -74,6 +74,19 @@ export class DefaultRAGService implements RAGService {}}+ async embed(texts: string[]): Promise<number[][]> {+ if (!texts || texts.length === 0) return []+ try {+ const ext = ExtensionManager.getInstance().get<RAGExtension>(+ ExtensionTypeEnum.RAG+ )+ if (ext?.embed) return await ext.embed(texts)+ } catch (e) {+ console.debug('RAG embed unavailable', e)+ }+ return []+ }+async parseDocument(path: string, type?: string): Promise<string> {try {const ext = ExtensionManager.getInstance().get<RAGExtension>(diff --git a/web-app/src/services/rag/types.ts b/web-app/src/services/rag/types.tsindex 18c999a98..b99eba8b9 100644--- a/web-app/src/services/rag/types.ts+++ b/web-app/src/services/rag/types.ts@@ -16,4 +16,6 @@ export interface RAGService {getToolNames(): Promise<string[]>// Parse a document to text for inline injection decisionsparseDocument?: (path: string, type?: string) => Promise<string>+ // Embed a batch of texts using the configured embedding model+ embed?: (texts: string[]) => Promise<number[][]>}diff --git a/web-app/src/stores/grounding-store.ts b/web-app/src/stores/grounding-store.tsnew file mode 100644index 000000000..fdb5f860b--- /dev/null+++ b/web-app/src/stores/grounding-store.ts@@ -0,0 +1,50 @@+import { create } from 'zustand'+import type { RagCitation } from '@/components/Citations'+import {+ computeGrounding,+ type GroundingResult,+} from '@/lib/grounding'++type EmbedFn = (texts: string[]) => Promise<number[][]>++type State = {+ byMessageId: Record<string, GroundingResult>+ computing: Record<string, boolean>+ ensure: (+ messageId: string,+ text: string,+ citations: RagCitation[],+ embed: EmbedFn+ ) => void+}++const fingerprint = (text: string, citations: RagCitation[]) =>+ `${text.length}:${citations.map((c) => c.id).join(',')}`++const lastFp: Record<string, string> = {}++export const useGroundingStore = create<State>((set, get) => ({+ byMessageId: {},+ computing: {},++ ensure: (messageId, text, citations, embed) => {+ if (!messageId || !text || !citations.length) return+ const fp = fingerprint(text, citations)+ if (lastFp[messageId] === fp) return+ if (get().computing[messageId]) return++ lastFp[messageId] = fp+ set((s) => ({ computing: { ...s.computing, [messageId]: true } }))++ computeGrounding({ text, citations, embed })+ .then((result) => {+ set((s) => ({+ byMessageId: { ...s.byMessageId, [messageId]: result },+ computing: { ...s.computing, [messageId]: false },+ }))+ })+ .catch(() => {+ set((s) => ({ computing: { ...s.computing, [messageId]: false } }))+ })+ },+}))