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.

feat: paragraph-level Edit with AI for assistant markdown (#7812)

Claytonc203ebcdd193
diff --git a/web-app/src/components/ParagraphAiEditLayer.tsx b/web-app/src/components/ParagraphAiEditLayer.tsx
new file mode 100644
index 000000000..93d1364dd
--- /dev/null
+++ b/web-app/src/components/ParagraphAiEditLayer.tsx
@@ -0,0 +1,317 @@
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { toast } from 'sonner'
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Textarea } from '@/components/ui/textarea'
+import { IconSparkles } from '@tabler/icons-react'
+import {
+ applySpanReplacement,
+ buildParagraphEditPrompts,
+ findSelectedSpan,
+ unwrapModelPassage,
+} from '@/lib/paragraphEdit'
+import { runParagraphEditCompletion } from '@/lib/runParagraphEditCompletion'
+
+type ParagraphAiEditLayerProps = {
+ sourceMarkdown: string
+ disabled?: boolean
+ onApply: (newMarkdown: string) => void
+ children: ReactNode
+}
+
+export function ParagraphAiEditLayer({
+ sourceMarkdown,
+ disabled,
+ onApply,
+ children,
+}: ParagraphAiEditLayerProps) {
+ const { t } = useTranslation()
+ const containerRef = useRef<HTMLDivElement>(null)
+ const toolbarRef = useRef<HTMLDivElement>(null)
+ const selectedTextRef = useRef<string>('')
+ const editSelectionRef = useRef<string>('')
+ const [selectionPreview, setSelectionPreview] = useState('')
+ const [toolbar, setToolbar] = useState<{
+ left: number
+ top: number
+ } | null>(null)
+ const [dialogOpen, setDialogOpen] = useState(false)
+ const [instruction, setInstruction] = useState('')
+ const [previewText, setPreviewText] = useState<string>('')
+ const [running, setRunning] = useState(false)
+
+ const clearToolbar = useCallback(() => setToolbar(null), [])
+
+ useEffect(() => {
+ if (disabled) {
+ clearToolbar()
+ }
+ }, [disabled, clearToolbar])
+
+ useEffect(() => {
+ const onMouseDown = (e: MouseEvent) => {
+ const el = containerRef.current
+ const tb = toolbarRef.current
+ if (!el || !toolbar) return
+ const target = e.target as Node
+ if (tb?.contains(target)) return
+ if (el.contains(target)) return
+ clearToolbar()
+ }
+ document.addEventListener('mousedown', onMouseDown)
+ return () => document.removeEventListener('mousedown', onMouseDown)
+ }, [toolbar, clearToolbar])
+
+ const handleMouseUp = useCallback(() => {
+ if (disabled) return
+
+ const sel = window.getSelection()
+ const el = containerRef.current
+ if (!sel || sel.isCollapsed || !el) {
+ clearToolbar()
+ return
+ }
+
+ const anchor = sel.anchorNode
+ const focus = sel.focusNode
+ if (
+ !anchor ||
+ !focus ||
+ !el.contains(anchor) ||
+ !el.contains(focus)
+ ) {
+ clearToolbar()
+ return
+ }
+
+ const text = sel.toString()
+ if (!text.trim()) {
+ clearToolbar()
+ return
+ }
+
+ const range = sel.getRangeAt(0)
+ const rect = range.getBoundingClientRect()
+ if (rect.width === 0 && rect.height === 0) {
+ clearToolbar()
+ return
+ }
+
+ setToolbar({
+ left: rect.left + rect.width / 2,
+ top: rect.bottom + 8,
+ })
+ selectedTextRef.current = text
+ }, [disabled, clearToolbar])
+
+ const openDialog = useCallback(() => {
+ const raw = selectedTextRef.current
+ editSelectionRef.current = raw
+ setSelectionPreview(raw.trim())
+ setInstruction('')
+ setPreviewText('')
+ setDialogOpen(true)
+ clearToolbar()
+ window.getSelection()?.removeAllRanges()
+ }, [clearToolbar])
+
+ const handleGeneratePreview = useCallback(async () => {
+ const trimmed = instruction.trim()
+ if (!trimmed) return
+
+ const selected = editSelectionRef.current
+ const span = findSelectedSpan(sourceMarkdown, selected)
+ if (!span) {
+ toast.error(t('chat:paragraphEdit.errorLocate'))
+ return
+ }
+
+ const { system, user } = buildParagraphEditPrompts({
+ fullSource: sourceMarkdown,
+ span,
+ userInstruction: trimmed,
+ })
+
+ setRunning(true)
+ try {
+ const raw = await runParagraphEditCompletion({
+ system,
+ user,
+ })
+ const revised = unwrapModelPassage(raw)
+ if (!revised) {
+ toast.error(t('chat:paragraphEdit.errorEmpty'))
+ return
+ }
+ setPreviewText(revised)
+ } catch (e) {
+ const msg =
+ e instanceof Error ? e.message : t('chat:paragraphEdit.errorModel')
+ toast.error(msg)
+ } finally {
+ setRunning(false)
+ }
+ }, [instruction, sourceMarkdown, t])
+
+ const handleApply = useCallback(() => {
+ const selected = editSelectionRef.current
+ const span = findSelectedSpan(sourceMarkdown, selected)
+ if (!span) {
+ toast.error(t('chat:paragraphEdit.errorLocate'))
+ return
+ }
+
+ const revised = previewText.trim()
+ if (!revised) {
+ toast.error(t('chat:paragraphEdit.errorEmpty'))
+ return
+ }
+
+ const next = applySpanReplacement(sourceMarkdown, span, revised)
+ onApply(next)
+ setDialogOpen(false)
+ editSelectionRef.current = ''
+ selectedTextRef.current = ''
+ setPreviewText('')
+ }, [previewText, sourceMarkdown, onApply, t])
+
+ return (
+ <>
+ <div
+ ref={containerRef}
+ className="relative"
+ onMouseUp={handleMouseUp}
+ >
+ {children}
+ </div>
+
+ {toolbar && !disabled && (
+ <div
+ ref={toolbarRef}
+ className="fixed z-50 pointer-events-auto"
+ style={{
+ left: toolbar.left,
+ top: toolbar.top,
+ transform: 'translateX(-50%)',
+ }}
+ >
+ <Button
+ type="button"
+ size="sm"
+ variant="secondary"
+ className="shadow-md gap-1.5"
+ onClick={(e) => {
+ e.stopPropagation()
+ openDialog()
+ }}
+ >
+ <IconSparkles size={16} className="shrink-0" />
+ {t('chat:paragraphEdit.editWithAi')}
+ </Button>
+ </div>
+ )}
+
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t('chat:paragraphEdit.title')}</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-3">
+ <div>
+ <p className="text-xs text-muted-foreground mb-1">
+ {t('chat:paragraphEdit.selectionLabel')}
+ </p>
+ <div className="max-h-28 overflow-y-auto rounded-md border bg-muted/40 px-2 py-1.5 text-sm whitespace-pre-wrap">
+ {selectionPreview || '—'}
+ </div>
+ </div>
+ <div>
+ <label
+ htmlFor="paragraph-edit-instruction"
+ className="text-xs text-muted-foreground mb-1 block"
+ >
+ {t('chat:paragraphEdit.instructionLabel')}
+ </label>
+ <Textarea
+ id="paragraph-edit-instruction"
+ value={instruction}
+ onChange={(e) => setInstruction(e.target.value)}
+ placeholder={t('chat:paragraphEdit.instructionPlaceholder')}
+ rows={3}
+ disabled={running}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && e.ctrlKey) {
+ e.preventDefault()
+ if (previewText.trim()) {
+ handleApply()
+ } else {
+ void handleGeneratePreview()
+ }
+ }
+ }}
+ />
+ <p className="text-[11px] text-muted-foreground mt-1">
+ {previewText.trim()
+ ? t('chat:paragraphEdit.hintCtrlEnterApply')
+ : t('chat:paragraphEdit.hintCtrlEnterPreview')}
+ </p>
+ </div>
+
+ {previewText.trim() && (
+ <div>
+ <p className="text-xs text-muted-foreground mb-1">
+ {t('chat:paragraphEdit.previewLabel')}
+ </p>
+ <div className="max-h-40 overflow-y-auto rounded-md border bg-muted/30 px-2 py-1.5 text-sm whitespace-pre-wrap">
+ {previewText}
+ </div>
+ </div>
+ )}
+ </div>
+ <DialogFooter className="gap-2 sm:gap-0">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setDialogOpen(false)}
+ disabled={running}
+ >
+ {t('chat:paragraphEdit.cancel')}
+ </Button>
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => void handleGeneratePreview()}
+ disabled={running || !instruction.trim()}
+ >
+ {running
+ ? t('chat:paragraphEdit.running')
+ : previewText.trim()
+ ? t('chat:paragraphEdit.regeneratePreview')
+ : t('chat:paragraphEdit.preview')}
+ </Button>
+ <Button
+ type="button"
+ onClick={handleApply}
+ disabled={running || !previewText.trim()}
+ >
+ {t('chat:paragraphEdit.apply')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
+ )
+}
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 0e0dc9723..3e89d36ae 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -190,6 +190,14 @@ export const MessageItem = memo(
isStreaming={isStreaming && isLastPart}
messageId={message.id}
isAnimating={isAnimating}
+ onApplyContentEdit={
+ onEdit && !hideActions
+ ? (newContent) => onEdit(message.id, newContent)
+ : undefined
+ }
+ paragraphEditDisabled={
+ hideActions || (isStreaming && isLastPart)
+ }
/>
</>
)}
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 2721ccfff..b888a46cd 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -2,6 +2,7 @@
import { Components } from 'react-markdown'
import { memo, useMemo } from 'react'
import { cn, disableIndentedCodeBlockPlugin } from '@/lib/utils'
+import { ParagraphAiEditLayer } from '@/components/ParagraphAiEditLayer'
// import 'katex/dist/katex.min.css'
import { defaultRehypePlugins, Streamdown } from 'streamdown'
import { cjk } from '@streamdown/cjk'
@@ -22,6 +23,10 @@ interface MarkdownProps {
isStreaming?: boolean
messageId?: string
isAnimating?: boolean
+ /** When set, user can select text and use "Edit with AI" on assistant messages. */
+ onApplyContentEdit?: (newMarkdown: string) => void
+ /** Disable paragraph AI edit (e.g. while streaming). */
+ paragraphEditDisabled?: boolean
}
// Cache for normalized LaTeX content
@@ -90,23 +95,16 @@ function RenderMarkdownComponent({
isUser,
components,
messageId,
- isAnimating
+ isAnimating,
+ onApplyContentEdit,
+ paragraphEditDisabled,
}: MarkdownProps) {
// Memoize the normalized content to avoid reprocessing on every render
const normalizedContent = useMemo(() => normalizeLatex(content), [content])
- // Render the markdown content
- return (
- <div
- dir="auto"
- className={cn(
- 'markdown wrap-break-word select-text',
- isUser && 'is-user',
- className
- )}
- >
- <Streamdown
+ const streamdownEl = (
+ <Streamdown
animate={isAnimating ?? true}
animationDuration={500}
linkSafety={{
@@ -144,10 +142,39 @@ function RenderMarkdownComponent({
>
{normalizedContent}
</Streamdown>
+ )
+
+ // Render the markdown content
+ return (
+ <div
+ dir="auto"
+ className={cn(
+ 'markdown wrap-break-word select-text',
+ isUser && 'is-user',
+ className
+ )}
+ >
+ {onApplyContentEdit ? (
+ <ParagraphAiEditLayer
+ sourceMarkdown={normalizedContent}
+ disabled={paragraphEditDisabled}
+ onApply={onApplyContentEdit}
+ >
+ {streamdownEl}
+ </ParagraphAiEditLayer>
+ ) : (
+ streamdownEl
+ )}
</div>
)
}
export const RenderMarkdown = memo(
RenderMarkdownComponent,
- (prevProps, nextProps) => prevProps.content === nextProps.content
+ (prevProps, nextProps) =>
+ prevProps.content === nextProps.content &&
+ prevProps.isStreaming === nextProps.isStreaming &&
+ prevProps.isAnimating === nextProps.isAnimating &&
+ prevProps.messageId === nextProps.messageId &&
+ prevProps.onApplyContentEdit === nextProps.onApplyContentEdit &&
+ prevProps.paragraphEditDisabled === nextProps.paragraphEditDisabled
)
diff --git a/web-app/src/lib/__tests__/paragraphEdit.test.ts b/web-app/src/lib/__tests__/paragraphEdit.test.ts
new file mode 100644
index 000000000..53c26a311
--- /dev/null
+++ b/web-app/src/lib/__tests__/paragraphEdit.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest'
+import {
+ applySpanReplacement,
+ findSelectedSpan,
+ unwrapModelPassage,
+} from '@/lib/paragraphEdit'
+
+describe('findSelectedSpan', () => {
+ it('finds a unique exact match', () => {
+ const source = 'Hello world.\n\nSecond paragraph here.'
+ const span = findSelectedSpan(source, 'Second paragraph here.')
+ expect(span).toEqual({ start: 14, end: 36 })
+ })
+
+ it('returns null when the selection matches multiple times', () => {
+ const source = 'foo bar foo bar'
+ expect(findSelectedSpan(source, 'foo')).toBeNull()
+ })
+
+ it('returns null for empty selection', () => {
+ expect(findSelectedSpan('abc', ' ')).toBeNull()
+ })
+})
+
+describe('applySpanReplacement', () => {
+ it('splices replacement at span', () => {
+ const next = applySpanReplacement(
+ 'aaSELECTbb',
+ { start: 2, end: 8 },
+ 'X'
+ )
+ expect(next).toBe('aaXbb')
+ })
+})
+
+describe('unwrapModelPassage', () => {
+ it('trims plain text', () => {
+ expect(unwrapModelPassage(' hello ')).toBe('hello')
+ })
+
+ it('unwraps a single fenced block', () => {
+ expect(unwrapModelPassage('```md\n**bold**\n```')).toBe('**bold**')
+ })
+})
diff --git a/web-app/src/lib/paragraphEdit.ts b/web-app/src/lib/paragraphEdit.ts
new file mode 100644
index 000000000..f2be237c9
--- /dev/null
+++ b/web-app/src/lib/paragraphEdit.ts
@@ -0,0 +1,110 @@
+/**
+ * Helpers for mapping a DOM text selection back to the assistant markdown source
+ * and building a focused edit prompt (Gemini Canvas–style paragraph editing).
+ */
+
+export type SourceSpan = { start: number; end: number }
+
+function indicesOf(haystack: string, needle: string): number[] {
+ if (needle.length === 0) return []
+ const out: number[] = []
+ let from = 0
+ while (from <= haystack.length - needle.length) {
+ const i = haystack.indexOf(needle, from)
+ if (i === -1) break
+ out.push(i)
+ from = i + 1
+ }
+ return out
+}
+
+/**
+ * Map selected visible text to a unique substring range in `source`.
+ * Returns null if the passage cannot be located or matches more than once.
+ */
+export function findSelectedSpan(
+ source: string,
+ selected: string
+): SourceSpan | null {
+ const t = selected.trim()
+ if (!t) return null
+
+ let idxs = indicesOf(source, t)
+ if (idxs.length === 1) {
+ const start = idxs[0]
+ return { start, end: start + t.length }
+ }
+ if (idxs.length > 1) return null
+
+ const minLen = 12
+ for (let len = Math.min(t.length, 2000); len >= minLen; len--) {
+ const prefix = t.slice(0, len)
+ idxs = indicesOf(source, prefix)
+ if (idxs.length !== 1) continue
+ const start = idxs[0]
+ if (
+ start + t.length <= source.length &&
+ source.slice(start, start + t.length) === t
+ ) {
+ return { start, end: start + t.length }
+ }
+ }
+
+ return null
+}
+
+export function applySpanReplacement(
+ source: string,
+ span: SourceSpan,
+ replacement: string
+): string {
+ return source.slice(0, span.start) + replacement + source.slice(span.end)
+}
+
+const CONTEXT_CHARS = 1200
+
+export function buildParagraphEditPrompts(params: {
+ fullSource: string
+ span: SourceSpan
+ userInstruction: string
+}): { system: string; user: string } {
+ const { fullSource, span, userInstruction } = params
+ const selected = fullSource.slice(span.start, span.end)
+ const before = fullSource.slice(Math.max(0, span.start - CONTEXT_CHARS), span.start)
+ const after = fullSource.slice(
+ span.end,
+ Math.min(fullSource.length, span.end + CONTEXT_CHARS)
+ )
+
+ const system = `You revise a short passage from a markdown message. Reply with ONLY the revised passage text: no surrounding quotes, no markdown code fences, and no preamble or explanation (do not start with "Here is" or similar). Preserve markdown inline/block syntax that belongs to that passage when appropriate.`
+
+ const user = `The full message is markdown. Use the context only for tone and consistency; do not repeat it.
+
+--- Context before (reference only) ---
+${before}
+--- End context before ---
+
+--- Passage to revise ---
+${selected}
+--- End passage ---
+
+--- Context after (reference only) ---
+${after}
+--- End context after ---
+
+Instruction: ${userInstruction.trim()}`
+
+ return { system, user }
+}
+
+/** If the model wrapped the answer in a single fenced block, unwrap it. */
+export function unwrapModelPassage(text: string): string {
+ let s = text.trim()
+ if (!s.startsWith('```')) return s
+ const firstBreak = s.indexOf('\n')
+ if (firstBreak === -1) return s
+ s = s.slice(firstBreak + 1)
+ const close = s.lastIndexOf('```')
+ if (close !== -1) s = s.slice(0, close)
+ return s.trimEnd()
+}
diff --git a/web-app/src/lib/runParagraphEditCompletion.ts b/web-app/src/lib/runParagraphEditCompletion.ts
new file mode 100644
index 000000000..0ccc5e4ab
--- /dev/null
+++ b/web-app/src/lib/runParagraphEditCompletion.ts
@@ -0,0 +1,39 @@
+import { generateText } from 'ai'
+import { ModelFactory } from '@/lib/model-factory'
+import { useModelProvider } from '@/hooks/useModelProvider'
+import { useAssistant } from '@/hooks/useAssistant'
+import { useServiceStore } from '@/hooks/useServiceHub'
+
+export async function runParagraphEditCompletion(params: {
+ system: string
+ user: string
+ abortSignal?: AbortSignal
+}): Promise<string> {
+ const serviceHub = useServiceStore.getState().serviceHub
+ const modelId = useModelProvider.getState().selectedModel?.id
+ const providerId = useModelProvider.getState().selectedProvider
+ const provider = useModelProvider.getState().getProviderByName(providerId)
+
+ if (!serviceHub || !modelId || !provider) {
+ throw new Error('No model selected or service is not ready.')
+ }
+
+ const inferenceParams =
+ useAssistant.getState().currentAssistant?.parameters ?? {}
+
+ const model = await ModelFactory.createModel(
+ modelId,
+ provider,
+ inferenceParams
+ )
+
+ const { text } = await generateText({
+ model,
+ system: params.system,
+ messages: [{ role: 'user', content: params.user }],
+ abortSignal: params.abortSignal,
+ maxOutputTokens: 4096,
+ })
+
+ return text
+}
diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.json
index 5ca734fcc..ea347d88a 100644
--- a/web-app/src/locales/en/chat.json
+++ b/web-app/src/locales/en/chat.json
@@ -8,5 +8,23 @@
},
"sendMessage": "Send Message",
"newConversation": "New Conversation",
- "clearHistory": "Clear History"
+ "clearHistory": "Clear History",
+ "paragraphEdit": {
+ "editWithAi": "Edit with AI",
+ "title": "Edit selection with AI",
+ "selectionLabel": "Selected text",
+ "instructionLabel": "What should change?",
+ "instructionPlaceholder": "e.g. Make this shorter, fix grammar, simplify…",
+ "previewLabel": "Preview",
+ "preview": "Preview",
+ "regeneratePreview": "Regenerate preview",
+ "hintCtrlEnterPreview": "Ctrl+Enter to preview",
+ "hintCtrlEnterApply": "Ctrl+Enter to apply",
+ "apply": "Apply",
+ "cancel": "Cancel",
+ "running": "Editing…",
+ "errorLocate": "Could not map the selection to this message. Try selecting a longer or more specific passage.",
+ "errorEmpty": "The model returned an empty revision. Try again with a clearer instruction.",
+ "errorModel": "Could not run the edit. Check your model and try again."
+ }
}
\ No newline at end of file