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.

perf(cowork): re-render only the live tail while a write streams

Akarshan Biswas09ee0623a98d
diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.ts
index ed598169c..6c1b4d8a6 100644
--- a/web-app/src/lib/__tests__/coworkTurns.test.ts
+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest'
-import { coworkTurnsToUIMessages, userTurn } from '@/lib/coworkTurns'
+import {
+ appendLiveMessages,
+ coworkTurnsToUIMessages,
+ userTurn,
+} from '@/lib/coworkTurns'
import type { CoworkTurn } from '@/hooks/useCoworkSessions'
/* eslint-disable @typescript-eslint/no-explicit-any */
@@ -223,3 +227,71 @@ describe('coworkTurnsToUIMessages', () => {
})
})
})
+
+describe('appendLiveMessages', () => {
+ const committed: CoworkTurn[] = [
+ { role: 'user', content: 'q' },
+ { role: 'assistant', content: 'first' },
+ ]
+
+ it('an offset slice mints the ids the whole transcript would', () => {
+ const live: CoworkTurn[] = [
+ { role: 'user', content: 'again' },
+ { role: 'assistant', content: 'second' },
+ ]
+ const whole = coworkTurnsToUIMessages([...committed, ...live], 's')
+ const split = appendLiveMessages(
+ coworkTurnsToUIMessages(committed, 's'),
+ coworkTurnsToUIMessages(live, 's', committed.length)
+ )
+ expect(split).toEqual(whole)
+ expect(split.map((m) => m.id)).toEqual([
+ 's-user-0',
+ 's-asst-1',
+ 's-user-2',
+ 's-asst-3',
+ ])
+ })
+
+ it('keeps every committed message identical across a live update', () => {
+ const base = coworkTurnsToUIMessages(committed, 's')
+ const live: CoworkTurn[] = [
+ { role: 'user', content: 'again' },
+ {
+ role: 'tool',
+ content: '',
+ callId: 'c1',
+ name: 'write',
+ status: 'running',
+ argsLive: '{"path":"a.html","content":"<h1>',
+ },
+ ]
+ const out = appendLiveMessages(
+ base,
+ coworkTurnsToUIMessages(live, 's', committed.length)
+ )
+ expect(out[0]).toBe(base[0])
+ expect(out[1]).toBe(base[1])
+ expect(out).toHaveLength(4)
+ })
+
+ it('joins a resumed run onto the committed assistant message', () => {
+ const live: CoworkTurn[] = [{ role: 'assistant', content: 'continued' }]
+ const whole = coworkTurnsToUIMessages([...committed, ...live], 's')
+ const split = appendLiveMessages(
+ coworkTurnsToUIMessages(committed, 's'),
+ coworkTurnsToUIMessages(live, 's', committed.length)
+ )
+ expect(split).toEqual(whole)
+ expect(split).toHaveLength(2)
+ expect(partsOf(split, 1).map((p: any) => p.text)).toEqual([
+ 'first',
+ 'continued',
+ ])
+ })
+
+ it('returns the committed list itself when nothing is live', () => {
+ const base = coworkTurnsToUIMessages(committed, 's')
+ expect(appendLiveMessages(base, [])).toBe(base)
+ })
+})
diff --git a/web-app/src/lib/__tests__/streamingArgs.test.ts b/web-app/src/lib/__tests__/streamingArgs.test.ts
index beb5c751c..42e090a75 100644
--- a/web-app/src/lib/__tests__/streamingArgs.test.ts
+++ b/web-app/src/lib/__tests__/streamingArgs.test.ts
@@ -107,3 +107,29 @@ describe('editPreview', () => {
expect(editPreview([])).toEqual({ rows: [], skipped: 0 })
})
})
+
+describe('writeTail windowing', () => {
+ const bySplit = (body: string) => {
+ const all = body.split('\n')
+ const lines = all.slice(Math.max(0, all.length - STREAM_TAIL_LINES))
+ return { lines, skipped: all.length - lines.length }
+ }
+
+ it('matches a whole-body split for every window shape', () => {
+ const bodies = [
+ '',
+ '\n',
+ 'a',
+ 'a\n',
+ '\n'.repeat(STREAM_TAIL_LINES - 1),
+ '\n'.repeat(STREAM_TAIL_LINES),
+ '\n'.repeat(STREAM_TAIL_LINES + 1),
+ '\n' + 'x\n'.repeat(STREAM_TAIL_LINES),
+ Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n'),
+ Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n') + '\n',
+ ]
+ for (const body of bodies) {
+ expect(writeTail(body), JSON.stringify(body)).toEqual(bySplit(body))
+ }
+ })
+})
diff --git a/web-app/src/lib/coworkTurns.ts b/web-app/src/lib/coworkTurns.ts
index b6b38fde1..356e703b1 100644
--- a/web-app/src/lib/coworkTurns.ts
+++ b/web-app/src/lib/coworkTurns.ts
@@ -55,9 +55,14 @@ function userMessageParts(turn: CoworkTurn): unknown[] {
return [{ type: 'text', text }, ...(turn.media ?? [])]
}
+/**
+ * `indexOffset` is the position of `turns[0]` in the whole transcript, so a
+ * slice converted on its own mints the same ids the full transcript would.
+ */
export function coworkTurnsToUIMessages(
turns: CoworkTurn[],
- idPrefix = 'code'
+ idPrefix = 'code',
+ indexOffset = 0
): UIMessage[] {
const messages: UIMessage[] = []
let assistant: any = null
@@ -78,7 +83,8 @@ export function coworkTurnsToUIMessages(
return assistant
}
- turns.forEach((turn, i) => {
+ turns.forEach((turn, at) => {
+ const i = at + indexOffset
if (turn.role === 'user') {
flushAssistant()
messages.push({
@@ -161,3 +167,25 @@ export function coworkTurnsToUIMessages(
flushAssistant()
return messages
}
+
+/**
+ * The committed transcript followed by the rows a run is still producing.
+ *
+ * Converting the two separately keeps every committed message's identity across
+ * a streamed delta, so `MessageItem`'s memo skips them and a `write` of any
+ * size re-renders only the card it is filling. The one seam is a run resumed
+ * without a question: its first rows continue the last committed assistant
+ * message, so the two are joined here exactly as one conversion would have.
+ */
+export function appendLiveMessages(
+ committed: UIMessage[],
+ live: UIMessage[]
+): UIMessage[] {
+ if (live.length === 0) return committed
+ const last = committed.at(-1)
+ if (!last || last.role !== 'assistant' || live[0].role !== 'assistant') {
+ return [...committed, ...live]
+ }
+ const joined = { ...last, parts: [...last.parts, ...live[0].parts] }
+ return [...committed.slice(0, -1), joined, ...live.slice(1)]
+}
diff --git a/web-app/src/lib/streamingArgs.ts b/web-app/src/lib/streamingArgs.ts
index a4226125e..fb1e23930 100644
--- a/web-app/src/lib/streamingArgs.ts
+++ b/web-app/src/lib/streamingArgs.ts
@@ -36,13 +36,24 @@ export type WritePreview = {
* dropping it makes the preview look stalled.
*/
export function writeTail(body: string): WritePreview {
- const all = body.split('\n')
- const lines = all.slice(Math.max(0, all.length - STREAM_TAIL_LINES))
+ // Walk back from the end instead of splitting the whole body: this runs on
+ // every frame of the write, and the body only grows.
+ // `cut` is the newline just before the window, -1 when the body is shorter.
+ let cut = body.length
+ for (let n = 0; n < STREAM_TAIL_LINES && cut !== -1; n++) {
+ cut = cut === 0 ? -1 : body.lastIndexOf('\n', cut - 1)
+ }
+ const lines = body.slice(cut + 1).split('\n')
+ let skipped = 0
+ for (let at = body.indexOf('\n'); at !== -1 && at <= cut; ) {
+ skipped++
+ at = body.indexOf('\n', at + 1)
+ }
// The last line is the one still being written; the rest are finished.
const open = lines.length - 1
return {
lines: lines.map((line, i) => clampPreviewLine(line, i === open)),
- skipped: all.length - lines.length,
+ skipped,
}
}
@@ -73,9 +84,11 @@ export function editPreview(
): EditPreview {
const all: EditRow[] = []
for (const edit of edits) {
- for (const text of edit.old_string.split('\n')) all.push({ sign: '-', text })
+ for (const text of edit.old_string.split('\n'))
+ all.push({ sign: '-', text })
if (edit.new_string === undefined) continue
- for (const text of edit.new_string.split('\n')) all.push({ sign: '+', text })
+ for (const text of edit.new_string.split('\n'))
+ all.push({ sign: '+', text })
}
const rows = all.slice(Math.max(0, all.length - STREAM_TAIL_LINES))
// The last row is the one still being written.
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 55a93f118..6d9c25a0e 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -43,12 +43,13 @@ import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { useModelProvider } from '@/hooks/useModelProvider'
import { MessageItem } from '@/containers/MessageItem'
import SkillSelector from '@/containers/SkillSelector'
-import { coworkTurnsToUIMessages, userTurn } from '@/lib/coworkTurns'
-import { extractFilesFromPrompt } from '@/lib/fileMetadata'
import {
- importAttachedFiles,
- withAttachedFiles,
-} from '@/lib/coworkAttachments'
+ appendLiveMessages,
+ coworkTurnsToUIMessages,
+ userTurn,
+} from '@/lib/coworkTurns'
+import { extractFilesFromPrompt } from '@/lib/fileMetadata'
+import { importAttachedFiles, withAttachedFiles } from '@/lib/coworkAttachments'
import { useToolCallRuntime, withToolTiming } from '@/hooks/useToolCallRuntime'
import { PromptProgress } from '@/components/PromptProgress'
import { useAppState } from '@/hooks/useAppState'
@@ -166,6 +167,32 @@ function CoworkPage() {
const [runSid, setRunSid] = useState<string | null>(null)
const [liveTurns, setLiveTurns] = useState<CoworkTurn[]>([])
const liveTurnsRef = useRef<CoworkTurn[]>([])
+ const liveFrameRef = useRef<number | null>(null)
+ // Every stream delta mutates `liveTurnsRef` in place; the state behind the
+ // transcript is refreshed from it at most once per frame. A large `write`
+ // arrives as thousands of deltas, and re-rendering the transcript for each
+ // one is what made the card lag behind the model.
+ const syncLive = useCallback(() => {
+ if (liveFrameRef.current != null) {
+ cancelAnimationFrame(liveFrameRef.current)
+ liveFrameRef.current = null
+ }
+ setLiveTurns([...liveTurnsRef.current])
+ }, [])
+ const scheduleLiveSync = useCallback(() => {
+ if (liveFrameRef.current != null) return
+ liveFrameRef.current = requestAnimationFrame(() => {
+ liveFrameRef.current = null
+ setLiveTurns([...liveTurnsRef.current])
+ })
+ }, [])
+ useEffect(
+ () => () => {
+ if (liveFrameRef.current != null)
+ cancelAnimationFrame(liveFrameRef.current)
+ },
+ []
+ )
const [stoppedBy, setStoppedBy] = useState<RunOutcome['stoppedBy'] | null>(
null
)
@@ -266,9 +293,27 @@ function CoworkPage() {
: (session?.turns ?? []),
[viewingRun, liveTurns, session?.turns]
)
+ // Committed and live rows are converted separately so a streamed delta
+ // rebuilds only the live tail; the committed messages keep their identity
+ // and `MessageItem` skips them.
+ const committedMessages = useMemo(
+ () =>
+ coworkTurnsToUIMessages(session?.turns ?? [], session?.id ?? 'cowork'),
+ [session?.turns, session?.id]
+ )
const uiMessages = useMemo(
- () => coworkTurnsToUIMessages(displayedTurns, session?.id ?? 'cowork'),
- [displayedTurns, session?.id]
+ () =>
+ viewingRun
+ ? appendLiveMessages(
+ committedMessages,
+ coworkTurnsToUIMessages(
+ liveTurns,
+ session?.id ?? 'cowork',
+ session?.turns?.length ?? 0
+ )
+ )
+ : committedMessages,
+ [viewingRun, committedMessages, liveTurns, session?.id, session?.turns]
)
// While a run streams, the last assistant message is the only one that can
// still gain parts; its artifact cards wait until the turn finishes.
@@ -321,10 +366,13 @@ function CoworkPage() {
[running, displayedTurns]
)
- const pushLive = useCallback((turns: CoworkTurn[]) => {
- liveTurnsRef.current = [...liveTurnsRef.current, ...turns]
- setLiveTurns(liveTurnsRef.current)
- }, [])
+ const pushLive = useCallback(
+ (turns: CoworkTurn[]) => {
+ liveTurnsRef.current = [...liveTurnsRef.current, ...turns]
+ syncLive()
+ },
+ [syncLive]
+ )
/**
* Drive one request. `text` is null for a resume — a retry after a failure
@@ -367,7 +415,7 @@ function CoworkPage() {
liveTurnsRef.current = text
? [userTurn(text, attachments?.media, attachments?.files)]
: []
- setLiveTurns(liveTurnsRef.current)
+ syncLive()
// Marks the session running in the store (and resets its subagent lanes),
// so surfaces outside this component — the sidebar's per-session spinner
// and its empty-session filter — can see a run this component owns.
@@ -402,7 +450,7 @@ function CoworkPage() {
importFile: (path, parsed) => importAttachment(sid, path, parsed),
})
liveTurnsRef.current = [userTurn(text, attachments?.media, files)]
- setLiveTurns(liveTurnsRef.current)
+ syncLive()
}
// Warm the sandbox probe: the transport's prompt and tool set read it
@@ -439,7 +487,7 @@ function CoworkPage() {
const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]
if (last && last.role === 'assistant') {
last.content += delta
- setLiveTurns([...liveTurnsRef.current])
+ scheduleLiveSync()
} else {
pushLive([{ role: 'assistant', content: delta }])
}
@@ -451,7 +499,7 @@ function CoworkPage() {
const last = liveTurnsRef.current[liveTurnsRef.current.length - 1]
if (last && last.role === 'assistant') {
last.reasoning = (last.reasoning ?? '') + delta
- setLiveTurns([...liveTurnsRef.current])
+ scheduleLiveSync()
} else {
pushLive([{ role: 'assistant', content: '', reasoning: delta }])
}
@@ -474,7 +522,7 @@ function CoworkPage() {
const row = liveTurnsRef.current.find((turn) => turn.callId === callId)
if (!row) return
row.argsLive = (row.argsLive ?? '') + delta
- setLiveTurns([...liveTurnsRef.current])
+ scheduleLiveSync()
},
onToolCall: (call) => {
const row = liveTurnsRef.current.find(
@@ -482,7 +530,7 @@ function CoworkPage() {
)
if (row) {
row.args = call.input
- setLiveTurns([...liveTurnsRef.current])
+ syncLive()
}
},
}
@@ -765,7 +813,7 @@ function CoworkPage() {
)
useCoworkRun.getState().clearCodeRun(sid)
liveTurnsRef.current = []
- setLiveTurns([])
+ syncLive()
setRunning(false)
setRunSid(null)
abortRef.current = null