Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(chat): render citation superscripts after multi-tool RAG turns

Akarshan Biswasa1bb23c588a0
diff --git a/web-app/src/stores/__tests__/grounding-store.test.ts b/web-app/src/stores/__tests__/grounding-store.test.ts
new file mode 100644
index 000000000..a072bd41b
--- /dev/null
+++ b/web-app/src/stores/__tests__/grounding-store.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import type { GroundingResult } from '@/lib/grounding'
+
+// Controllable computeGrounding so we can resolve runs out of order.
+const deferreds: Array<{
+ resolve: (r: GroundingResult) => void
+ reject: (e: unknown) => void
+}> = []
+vi.mock('@/lib/grounding', () => ({
+ computeGrounding: vi.fn(
+ () =>
+ new Promise<GroundingResult>((resolve, reject) => {
+ deferreds.push({ resolve, reject })
+ })
+ ),
+}))
+
+import { useGroundingStore } from '../grounding-store'
+
+const citation = (id: string) => ({
+ id,
+ text: `text-${id}`,
+ score: 1,
+ file_id: 'f1',
+})
+
+const result = (tag: string): GroundingResult => ({
+ sentenceCitations: { [tag]: [0] },
+ citations: [citation('a')],
+})
+
+describe('grounding-store ensure', () => {
+ beforeEach(() => {
+ deferreds.length = 0
+ useGroundingStore.setState({ byMessageId: {}, computing: {} })
+ })
+
+ afterEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('ignores a stale run that resolves after a newer run started', async () => {
+ const embed = vi.fn(async () => [[1]])
+ const { ensure } = useGroundingStore.getState()
+
+ // Partial input (mid tool-sequence flicker).
+ ensure('m1', 'partial', [citation('a')], embed)
+ // Final input (full answer) — must supersede the partial run.
+ ensure('m1', 'the full final answer text', [citation('a')], embed)
+
+ expect(deferreds).toHaveLength(2)
+
+ // Resolve the newer (final) run first, then the stale partial run.
+ deferreds[1].resolve(result('final'))
+ deferreds[0].resolve(result('partial'))
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(useGroundingStore.getState().byMessageId.m1).toEqual(result('final'))
+ expect(useGroundingStore.getState().computing.m1).toBe(false)
+ })
+
+ it('does not restart for an identical fingerprint', () => {
+ const embed = vi.fn(async () => [[1]])
+ const { ensure } = useGroundingStore.getState()
+
+ ensure('m2', 'same text', [citation('a')], embed)
+ ensure('m2', 'same text', [citation('a')], embed)
+
+ expect(deferreds).toHaveLength(1)
+ })
+
+ it('skips empty inputs', () => {
+ const embed = vi.fn(async () => [[1]])
+ const { ensure } = useGroundingStore.getState()
+
+ ensure('', 'text', [citation('a')], embed)
+ ensure('m3', '', [citation('a')], embed)
+ ensure('m3', 'text', [], embed)
+
+ expect(deferreds).toHaveLength(0)
+ })
+})
diff --git a/web-app/src/stores/grounding-store.ts b/web-app/src/stores/grounding-store.ts
index fdb5f860b..869f17ec0 100644
--- a/web-app/src/stores/grounding-store.ts
+++ b/web-app/src/stores/grounding-store.ts
@@ -22,8 +22,14 @@ 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) => ({
+// Monotonic token per message: a multi-tool turn flickers to !isStreaming
+// between tool calls, kicking off grounding on partial text while the final
+// answer is still streaming. We can't drop the later (full-text) request — its
+// result must win — so we tag each run and ignore any stale result that
+// resolves after a newer run has started.
+const runSeq: Record<string, number> = {}
+
+export const useGroundingStore = create<State>((set) => ({
byMessageId: {},
computing: {},
@@ -31,19 +37,21 @@ export const useGroundingStore = create<State>((set, get) => ({
if (!messageId || !text || !citations.length) return
const fp = fingerprint(text, citations)
if (lastFp[messageId] === fp) return
- if (get().computing[messageId]) return
lastFp[messageId] = fp
+ const token = (runSeq[messageId] = (runSeq[messageId] ?? 0) + 1)
set((s) => ({ computing: { ...s.computing, [messageId]: true } }))
computeGrounding({ text, citations, embed })
.then((result) => {
+ if (runSeq[messageId] !== token) return
set((s) => ({
byMessageId: { ...s.byMessageId, [messageId]: result },
computing: { ...s.computing, [messageId]: false },
}))
})
.catch(() => {
+ if (runSeq[messageId] !== token) return
set((s) => ({ computing: { ...s.computing, [messageId]: false } }))
})
},