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): leave an @token that is not a file in the prompt as typed (#9291) (#9296)

Thinh Le9f313cfeaba3
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 24614034f..335c91074 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -112,10 +112,8 @@ import { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'
import { useAgentMode } from '@/hooks/useAgentMode'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import {
- parsePromptForReferences,
- resolvePathReference,
+ expandPromptReferences,
searchFiles,
- stripPromptReferences,
type FilePickerEntry as FileEntry,
} from '@/lib/path-references'
import { FilePickerPopover } from '@/components/FilePickerPopover'
@@ -430,46 +428,6 @@ const ChatInput = memo(function ChatInput({
filePickerCursorPos.current = null
}, [])
- // Resolve @path references in the prompt text, returning the resolved content
- const resolvePromptReferences = useCallback(
- async (text: string): Promise<{
- text: string
- resolvedContents: string
- }> => {
- const refs = parsePromptForReferences(text)
- if (refs.length === 0) return { text, resolvedContents: '' }
-
- const parts: string[] = []
- for (const ref of refs) {
- const resolved = await resolvePathReference(ref, workingDir)
- if (resolved) {
- if (resolved.kind === 'file') {
- parts.push(
- `--- File: ${resolved.absolutePath} ---\n${resolved.content}`
- )
- } else if (resolved.kind === 'directory') {
- parts.push(
- `--- Directory: ${resolved.absolutePath} ---\n${resolved.content}`
- )
- }
- } else {
- parts.push(
- `[File not found or too large: ${ref}]`
- )
- }
- }
-
- const resolvedContents = parts.join('\n\n')
-
- // Remove @ references from the prompt text (they'll be replaced by the
- // resolved contents above so the model sees the content directly)
- const cleanText = stripPromptReferences(text)
-
- return { text: cleanText, resolvedContents }
- },
- [workingDir]
- )
-
// Get current thread messages for token counting
const threadMessages = useMessages(
useShallow((state) =>
@@ -661,9 +619,10 @@ const ChatInput = memo(function ChatInput({
return
}
- // Resolve @path references before sending
+ // Expand @path references that resolve to a file or folder; any other
+ // `@token` (a pasted decorator) stays in the text as typed.
const { text: resolvedText, resolvedContents } =
- await resolvePromptReferences(prompt)
+ await expandPromptReferences(prompt, workingDir)
const effectivePrompt = resolvedContents
? `${resolvedText}\n\n---\nReferenced file contents:\n\n${resolvedContents}`
: resolvedText
diff --git a/web-app/src/lib/__tests__/path-references.test.ts b/web-app/src/lib/__tests__/path-references.test.ts
index a0717b967..f9590ab32 100644
--- a/web-app/src/lib/__tests__/path-references.test.ts
+++ b/web-app/src/lib/__tests__/path-references.test.ts
@@ -1,11 +1,17 @@
-import { describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fs } from '@janhq/core'
import {
+ expandPromptReferences,
parsePromptForReferences,
stripPromptReferences,
} from '../path-references'
vi.mock('@janhq/core', () => ({
- fs: {},
+ fs: {
+ fileStat: vi.fn(),
+ readFileSync: vi.fn(),
+ readdirSync: vi.fn(),
+ },
}))
describe('parsePromptForReferences', () => {
@@ -42,16 +48,91 @@ describe('parsePromptForReferences', () => {
})
describe('stripPromptReferences', () => {
- it('strips references but keeps ssh/email addresses', () => {
+ it('strips resolved references but keeps ssh/email addresses', () => {
expect(
- stripPromptReferences('see @src/main.ts and ssh [email protected]')
+ stripPromptReferences(
+ 'see @src/main.ts and ssh [email protected]',
+ new Set(['src/main.ts'])
+ )
).toBe('see and ssh [email protected]')
})
- it('keeps non-reference text intact', () => {
- expect(stripPromptReferences('no refs here')).toBe('no refs here')
- expect(stripPromptReferences('ssh [email protected]')).toBe(
+ it('leaves the text untouched when nothing resolved', () => {
+ const text = 'line one\n\n indented @property\nline two'
+ expect(stripPromptReferences(text, new Set())).toBe(text)
+ })
+
+ it('keeps unresolved tokens and the whitespace around them', () => {
+ expect(
+ stripPromptReferences(
+ 'read @a.ts\n\n@dataclass\nclass A:\n x: int',
+ new Set(['a.ts'])
+ )
+ ).toBe('read\n\n@dataclass\nclass A:\n x: int')
+ })
+
+ it('keeps leading indentation and trailing blank lines of the prompt', () => {
+ expect(
+ stripPromptReferences(
+ ' def f(): ...\n\nlook at @a.ts\n\n',
+ new Set(['a.ts'])
+ )
+ ).toBe(' def f(): ...\n\nlook at\n\n')
+ })
+})
+
+// A pasted snippet whose decorators look like `@path` references.
+const PYTHON = [
+ 'Why does this fail?',
+ '',
+ '@dataclass',
+ 'class A:',
+ ' x: int',
+ '',
+ '@app.route("/x")',
+ 'def f(): ...',
+ '',
+ '@property',
+ 'def p(self): ...',
+].join('\n')
+
+describe('expandPromptReferences', () => {
+ const stat = vi.mocked(fs.fileStat)
+ const read = vi.mocked(fs.readFileSync)
+
+ beforeEach(() => {
+ vi.resetAllMocks()
+ // Only these paths exist in the working directory.
+ const files: Record<string, { size: number; body: string }> = {
+ '/work/notes.md': { size: 5, body: 'hello' },
+ '/work/huge.log': { size: 5 * 1024 * 1024, body: '' },
+ }
+ stat.mockImplementation(async (p: string) => {
+ const f = files[p]
+ if (!f) throw new Error('ENOENT')
+ return { isDirectory: false, size: f.size } as never
+ })
+ read.mockImplementation(async (p: string) => files[p]?.body as never)
+ })
+
+ it('sends pasted code with decorators exactly as typed', async () => {
+ const out = await expandPromptReferences(PYTHON, '/work')
+ expect(out).toEqual({ text: PYTHON, resolvedContents: '' })
+ })
+
+ it('expands a real file and leaves decorators in the same prompt alone', async () => {
+ const out = await expandPromptReferences(
+ `summarise @notes.md\n\n${PYTHON}`,
+ '/work'
)
+ expect(out.text).toBe(`summarise\n\n${PYTHON}`)
+ expect(out.resolvedContents).toContain('hello')
+ expect(out.resolvedContents).not.toContain('not found')
+ })
+
+ it('still tells the user when a referenced file is too large', async () => {
+ const out = await expandPromptReferences('check @huge.log please', '/work')
+ expect(out.text).toBe('check please')
+ expect(out.resolvedContents).toBe('[File too large to include: huge.log]')
})
})
diff --git a/web-app/src/lib/path-references.ts b/web-app/src/lib/path-references.ts
index c55d2bb72..9f7352972 100644
--- a/web-app/src/lib/path-references.ts
+++ b/web-app/src/lib/path-references.ts
@@ -84,14 +84,29 @@ export function parsePromptForReferences(text: string): string[] {
}
/**
- * Remove qualified @path references from `text`, leaving non-reference `@`
- * tokens (ssh/email addresses, bare IPs) intact, and normalise whitespace.
+ * Remove the `@path` references in `resolved` from `text`, leaving every other
+ * `@token` (decorators, ssh/email addresses, bare IPs) and all other
+ * whitespace untouched. A removed token also takes one adjacent space so
+ * `see @a and b` becomes `see and b`, not `see and b`.
*/
-export function stripPromptReferences(text: string): string {
- const cleaned = text.replace(REFERENCE_PATTERN, (match, raw: string) =>
- isReferenceToken(raw) ? '' : match
+export function stripPromptReferences(
+ text: string,
+ resolved: ReadonlySet<string>
+): string {
+ if (resolved.size === 0) return text
+ const pattern = new RegExp(
+ `([ \\t]?)${REFERENCE_PATTERN.source}([ \\t]?)`,
+ 'g'
+ )
+ return text.replace(
+ pattern,
+ (match, lead: string, raw: string, trail: string) =>
+ isReferenceToken(raw) && resolved.has(raw)
+ ? lead && trail
+ ? ' '
+ : ''
+ : match
)
- return cleaned.replace(/\s+/g, ' ').trim()
}
/**
@@ -154,6 +169,20 @@ export async function searchFiles(
// ── Resolving a single reference content ─────────────────────────────────────
+export type ResolvedReference =
+ | {
+ kind: 'file' | 'directory'
+ absolutePath: string
+ content: string
+ isImage: boolean
+ imageBase64?: string
+ imageMimeType?: string
+ }
+ // The path exists but is over the size cap, so it cannot be inlined. Kept
+ // apart from `null` so the user is still told, instead of the `@path`
+ // silently turning into nothing.
+ | { kind: 'too-large'; absolutePath: string }
+
/**
* Resolve a @path reference and return the content to inject into the message.
*
@@ -162,14 +191,7 @@ export async function searchFiles(
export async function resolvePathReference(
rawPath: string,
workingDir?: string
-): Promise<{
- kind: 'file' | 'directory'
- absolutePath: string
- content: string
- isImage: boolean
- imageBase64?: string
- imageMimeType?: string
-} | null> {
+): Promise<ResolvedReference | null> {
const absolutePath = rawPath.startsWith('/')
? rawPath
: workingDir
@@ -200,7 +222,7 @@ export async function resolvePathReference(
// File
const size = stat.size ? Number(stat.size) : 0
if (size > MAX_FILE_BYTES) {
- return null // too large — caller handles
+ return { kind: 'too-large', absolutePath }
}
const ext = rawPath.split('.').pop()?.toLowerCase()
@@ -233,6 +255,44 @@ export async function resolvePathReference(
}
}
+/**
+ * Expand the `@path` references in a prompt that resolve to a file or folder
+ * in the working directory. Anything else that merely starts with `@` (Python
+ * decorators, `@mentions`) is left in the text exactly as typed.
+ *
+ * `resolvedContents` is the text to append after the prompt; `text` is the
+ * prompt with the expanded references removed.
+ */
+export async function expandPromptReferences(
+ text: string,
+ workingDir?: string
+): Promise<{ text: string; resolvedContents: string }> {
+ const refs = parsePromptForReferences(text)
+ if (refs.length === 0) return { text, resolvedContents: '' }
+
+ const parts: string[] = []
+ const expanded = new Set<string>()
+ for (const ref of refs) {
+ const resolved = await resolvePathReference(ref, workingDir)
+ if (!resolved) continue
+ expanded.add(ref)
+ if (resolved.kind === 'too-large') {
+ parts.push(`[File too large to include: ${ref}]`)
+ } else if (resolved.kind === 'file') {
+ parts.push(`--- File: ${resolved.absolutePath} ---\n${resolved.content}`)
+ } else {
+ parts.push(
+ `--- Directory: ${resolved.absolutePath} ---\n${resolved.content}`
+ )
+ }
+ }
+
+ return {
+ text: stripPromptReferences(text, expanded),
+ resolvedContents: parts.join('\n\n'),
+ }
+}
+
// ── Internal helpers ─────────────────────────────────────────────────────────
interface ScoredEntry {