Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🌊 perf: Trim Per-Token and Per-Render Work in Streaming and Lists (#16718)

Marco Berettab24226672d35
diff --git a/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx b/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx
index 1d785550a4..d38d6b7f19 100644
--- a/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx
@@ -1,3 +1,4 @@
+import { memo } from 'react';
import { cn } from '~/utils';
const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
@@ -159,6 +160,55 @@ function lineNumber(line: DiffLine): number | undefined {
return line.type === 'del' ? line.oldLine : (line.newLine ?? line.oldLine);
}
+interface DiffRowProps {
+ type: DiffLine['type'];
+ text: string;
+ num?: number;
+ hasLineNumbers: boolean;
+}
+
+/** Primitive props only: `parseUnifiedDiff` rebuilds every line object on each
+ * streamed delta, so memo has to compare values, not object identity. */
+const DiffRow = memo(function DiffRow({ type, text, num, hasLineNumbers }: DiffRowProps) {
+ if (type === 'hunk') {
+ if (!text) {
+ return <div className="border-border-light mx-3 my-1.5 border-t" />;
+ }
+ return <div className="text-text-tertiary px-3 py-0.5 text-[11px] select-none">{text}</div>;
+ }
+ return (
+ <div
+ className={cn(
+ 'flex',
+ type === 'add' && 'bg-status-success-subtle',
+ type === 'del' && 'bg-status-error-subtle',
+ )}
+ >
+ {hasLineNumbers && (
+ <span className="text-text-tertiary w-9 shrink-0 pr-1 text-right text-[11px] select-none">
+ {num ?? ''}
+ </span>
+ )}
+ <span
+ className={cn(
+ 'shrink-0 text-center font-semibold select-none',
+ hasLineNumbers ? 'w-5' : 'w-6',
+ type === 'add' && 'text-status-success',
+ type === 'del' && 'text-status-error',
+ )}
+ >
+ {LINE_MARKERS[type]}
+ </span>
+ <span className="text-text-primary min-w-0 flex-1 pr-3 break-words whitespace-pre-wrap">
+ {text || ' '}
+ </span>
+ </div>
+ );
+});
+
+/** Index keys are safe: the parser walks the text top to bottom and the stream
+ * only appends, so a row's index, type and line numbers are stable once
+ * emitted. Only the trailing, still-growing line changes, and its props do too. */
export default function DiffView({ parsed }: { parsed: ParsedDiff }) {
const { lines, hasLineNumbers } = parsed;
const firstContentIndex = lines.findIndex((line) => line.type !== 'hunk');
@@ -166,50 +216,20 @@ export default function DiffView({ parsed }: { parsed: ParsedDiff }) {
return (
<div
data-testid="diff-view"
- className="max-h-[300px] overflow-y-auto bg-surface-code py-2 font-mono text-xs leading-5"
+ className="bg-surface-code max-h-[300px] overflow-y-auto py-2 font-mono text-xs leading-5"
>
{lines.map((line, index) => {
- if (line.type === 'hunk') {
- if (index < firstContentIndex || firstContentIndex === -1) {
- return null;
- }
- if (!line.text) {
- return <div key={index} className="mx-3 my-1.5 border-t border-border-light" />;
- }
- return (
- <div key={index} className="select-none px-3 py-0.5 text-[11px] text-text-tertiary">
- {line.text}
- </div>
- );
+ if (line.type === 'hunk' && (index < firstContentIndex || firstContentIndex === -1)) {
+ return null;
}
return (
- <div
+ <DiffRow
key={index}
- className={cn(
- 'flex',
- line.type === 'add' && 'bg-status-success-subtle',
- line.type === 'del' && 'bg-status-error-subtle',
- )}
- >
- {hasLineNumbers && (
- <span className="w-9 shrink-0 select-none pr-1 text-right text-[11px] text-text-tertiary">
- {lineNumber(line) ?? ''}
- </span>
- )}
- <span
- className={cn(
- 'shrink-0 select-none text-center font-semibold',
- hasLineNumbers ? 'w-5' : 'w-6',
- line.type === 'add' && 'text-status-success',
- line.type === 'del' && 'text-status-error',
- )}
- >
- {LINE_MARKERS[line.type]}
- </span>
- <span className="min-w-0 flex-1 whitespace-pre-wrap break-words pr-3 text-text-primary">
- {line.text || ' '}
- </span>
- </div>
+ type={line.type}
+ text={line.text}
+ num={lineNumber(line)}
+ hasLineNumbers={hasLineNumbers}
+ />
);
})}
</div>
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffViewRows.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffViewRows.test.tsx
new file mode 100644
index 0000000000..27b185965e
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffViewRows.test.tsx
@@ -0,0 +1,52 @@
+import { render } from '@testing-library/react';
+import DiffView, { parseUnifiedDiff } from '../DiffView';
+import { cn } from '~/utils';
+
+jest.mock('~/utils', () => {
+ const actual = jest.requireActual('~/utils');
+ return { ...actual, cn: jest.fn(actual.cn) };
+});
+
+const cnSpy = jest.mocked(cn);
+const base = ['@@ -1,2 +1,2 @@', '-old one', '+new one', ' same'].join('\n');
+
+/** Renders the base diff and returns how many `cn` calls one row costs, so the
+ * assertions below compare row renders instead of pinning the call count. */
+function renderBase(diff: string) {
+ cnSpy.mockClear();
+ const utils = render(<DiffView parsed={parseUnifiedDiff(diff)} />);
+ const rowCount = utils.getByTestId('diff-view').children.length;
+ const callsPerRow = cnSpy.mock.calls.length / rowCount;
+ cnSpy.mockClear();
+ return { ...utils, callsPerRow };
+}
+
+describe('DiffView row memoization', () => {
+ it('renders only the appended row when a line is added', () => {
+ const { rerender, getByTestId, callsPerRow } = renderBase(base);
+ expect(callsPerRow).toBeGreaterThan(0);
+
+ rerender(<DiffView parsed={parseUnifiedDiff(`${base}\n+appended`)} />);
+
+ expect(cnSpy).toHaveBeenCalledTimes(callsPerRow);
+ const rows = [...getByTestId('diff-view').children];
+ expect(rows.map((row) => row.textContent)).toEqual([
+ '1-old one',
+ '1+new one',
+ '2same',
+ '3+appended',
+ ]);
+ expect(rows[0]).toHaveClass('bg-status-error-subtle');
+ expect(rows[3]).toHaveClass('flex', 'bg-status-success-subtle');
+ expect(rows[3]).not.toHaveClass('bg-status-error-subtle');
+ });
+
+ it('re-renders only the growing trailing row while it streams', () => {
+ const { rerender, getByTestId, callsPerRow } = renderBase(`${base}\n+par`);
+
+ rerender(<DiffView parsed={parseUnifiedDiff(`${base}\n+partial`)} />);
+
+ expect(cnSpy).toHaveBeenCalledTimes(callsPerRow);
+ expect(getByTestId('diff-view').lastElementChild?.textContent).toBe('3+partial');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/parseJsonField.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/parseJsonField.test.ts
index b8d67f03f8..6e053a865e 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/parseJsonField.test.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/parseJsonField.test.ts
@@ -229,3 +229,14 @@ describe('areToolCallArgsComplete', () => {
expect(areToolCallArgsComplete('[]')).toBe(false);
});
});
+
+describe('cached field regexes', () => {
+ it('returns identical results across repeated calls on the same field', () => {
+ const partial = '{"command":"echo hi';
+ expect(parseJsonField(partial, 'command')).toBe('echo hi');
+ expect(parseJsonField(partial, 'command')).toBe('echo hi');
+ const many = '{"a":"1","a":"2","a":"3';
+ expect(parseJsonFieldOccurrences(many, 'a')).toEqual(['1', '2', '3']);
+ expect(parseJsonFieldOccurrences(many, 'a')).toEqual(['1', '2', '3']);
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts b/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
index 7322b1f215..a85b112dd5 100644
--- a/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
@@ -15,10 +15,19 @@ export function areToolCallArgsComplete(args: ToolCallArgs): boolean {
}
}
+const fieldRegexCache = new Map<string, RegExp>();
+
/** Matches `"field":"value"`, tolerating a missing closing quote and a dangling escape at the end of partially streamed args. */
function fieldRegex(field: string, flags?: string): RegExp {
+ const key = `${flags ?? ''}:${field}`;
+ const cached = fieldRegexCache.get(key);
+ if (cached) {
+ return cached;
+ }
const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- return new RegExp(`"${escaped}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)(?:"|\\\\?$)`, flags);
+ const regex = new RegExp(`"${escaped}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)(?:"|\\\\?$)`, flags);
+ fieldRegexCache.set(key, regex);
+ return regex;
}
const SIMPLE_ESCAPES: Record<string, string> = {
diff --git a/client/src/components/Chat/Trace/Timeline.tsx b/client/src/components/Chat/Trace/Timeline.tsx
index c92b044fe4..312ee3d622 100644
--- a/client/src/components/Chat/Trace/Timeline.tsx
+++ b/client/src/components/Chat/Trace/Timeline.tsx
@@ -65,6 +65,53 @@ function Timeline({
(position: number) => (position - bounds.start) / span,
[bounds.start, span],
);
+ const recordRects = useMemo(
+ () => (
+ <>
+ {model.turns.map((turn) => (
+ <rect
+ key={turn.key}
+ x={percent(toFraction(turnSpan(turn, scale).start))}
+ y={0}
+ width={1}
+ height="100%"
+ className="fill-border-medium"
+ />
+ ))}
+ {records.map((node) => {
+ const { record } = node;
+ const lane = lanes?.get(record.id) ?? sequenceLane(record);
+ const y = TOP_PADDING + lane * (LANE_HEIGHT + LANE_GAP);
+ const fill = record.status === 'error' ? 'fill-status-error' : appearanceOf(record).fill;
+ if (scale === 'time' && node.end == null) {
+ return (
+ <rect
+ key={record.id}
+ x={percent(toFraction(node.start))}
+ y={y - 1}
+ width={3}
+ height={LANE_HEIGHT + 2}
+ className={fill}
+ />
+ );
+ }
+ const recordSpan = spanOf(node, scale);
+ return (
+ <rect
+ key={record.id}
+ x={percent(toFraction(recordSpan.start))}
+ y={y}
+ width={`${Math.max(((recordSpan.end - recordSpan.start) / span) * 100, 0.15)}%`}
+ height={LANE_HEIGHT}
+ rx={1}
+ className={fill}
+ />
+ );
+ })}
+ </>
+ ),
+ [model.turns, records, lanes, scale, span, toFraction],
+ );
const tick = (fraction: number) =>
scale === 'sequence' ? String(Math.round(span * fraction)) : format.duration(span * fraction);
@@ -185,47 +232,7 @@ function Timeline({
className="border-border-light bg-surface-primary-alt focus-visible:ring-ring-primary relative h-[60px] cursor-crosshair touch-none overflow-hidden rounded-lg border select-none focus-visible:ring-2 focus-visible:outline-hidden"
>
<svg className="absolute inset-0 h-full w-full" aria-hidden="true">
- {model.turns.map((turn) => (
- <rect
- key={turn.key}
- x={percent(toFraction(turnSpan(turn, scale).start))}
- y={0}
- width={1}
- height="100%"
- className="fill-border-medium"
- />
- ))}
- {records.map((node) => {
- const { record } = node;
- const lane = lanes?.get(record.id) ?? sequenceLane(record);
- const y = TOP_PADDING + lane * (LANE_HEIGHT + LANE_GAP);
- const fill =
- record.status === 'error' ? 'fill-status-error' : appearanceOf(record).fill;
- if (scale === 'time' && node.end == null) {
- return (
- <rect
- key={record.id}
- x={percent(toFraction(node.start))}
- y={y - 1}
- width={3}
- height={LANE_HEIGHT + 2}
- className={fill}
- />
- );
- }
- const recordSpan = spanOf(node, scale);
- return (
- <rect
- key={record.id}
- x={percent(toFraction(recordSpan.start))}
- y={y}
- width={`${Math.max(((recordSpan.end - recordSpan.start) / span) * 100, 0.15)}%`}
- height={LANE_HEIGHT}
- rx={1}
- className={fill}
- />
- );
- })}
+ {recordRects}
</svg>
{selection && (
<>
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index 6892302862..1629f63e52 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -61,7 +61,7 @@ function Conversation({
const currentConvoId = useMemo(() => params.conversationId, [params.conversationId]);
const updateConvoMutation = useUpdateConversationMutation(currentConvoId ?? '');
const unpinMutation = usePinConversationMutation();
- const activeConvos = useRecoilValue(store.allConversationsSelector);
+ const activeConversationId = useRecoilValue(store.conversationIdByIndex(0));
const isSmallScreen = useMediaQuery('(max-width: 768px)');
/* A deployment with shared links off leaves existing links in the database but stops
serving them, so the row must not advertise one that no longer resolves. */
@@ -134,10 +134,9 @@ function Conversation({
if (currentConvoId !== Constants.NEW_CONVO) {
return currentConvoId === conversationId;
} else {
- const latestConvo = activeConvos?.[0];
- return latestConvo === conversationId;
+ return activeConversationId === conversationId;
}
- }, [currentConvoId, conversationId, activeConvos]);
+ }, [currentConvoId, conversationId, activeConversationId]);
const handleRename = () => {
setIsPopoverActive(false);
diff --git a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
index d921e383b4..9d2933f1fb 100644
--- a/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.touch.spec.tsx
@@ -38,7 +38,7 @@ jest.mock('recoil', () => ({
jest.mock('~/store', () => ({
__esModule: true,
- default: { allConversationsSelector: 'allConversationsSelector' },
+ default: { conversationIdByIndex: () => 'conversationIdByIndex' },
}));
jest.mock('~/utils', () => ({
diff --git a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
index 54c3117b76..9ba577f8f8 100644
--- a/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
+++ b/client/src/components/Conversations/__tests__/Convo.unpin.spec.tsx
@@ -53,7 +53,7 @@ jest.mock('recoil', () => ({
jest.mock('~/store', () => ({
__esModule: true,
- default: { allConversationsSelector: 'allConversationsSelector' },
+ default: { conversationIdByIndex: () => 'conversationIdByIndex' },
}));
jest.mock('~/utils', () => ({
diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx
index 8e88612440..05c0920f7f 100644
--- a/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx
+++ b/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx
@@ -47,6 +47,18 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })
),
[options, selectedAgentIds],
);
+ const rowOptionsByIndex = useMemo(
+ () =>
+ edges.map((edge) => {
+ const targetAgentId = getTargetAgentId(edge.to);
+ return options.filter(
+ (option) =>
+ typeof option.value === 'string' &&
+ (option.value === targetAgentId || !selectedAgentIds.has(option.value)),
+ );
+ }),
+ [options, selectedAgentIds, edges],
+ );
useEffect(() => {
if (!newAgentId) {
@@ -126,11 +138,7 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })
const targetAgentId = getTargetAgentId(edge.to);
const isExpanded = expandedIndices.has(idx);
const targetName = getAgent(targetAgentId)?.name ?? localize('com_ui_agent');
- const rowOptions = options.filter(
- (option) =>
- typeof option.value === 'string' &&
- (option.value === targetAgentId || !selectedAgentIds.has(option.value)),
- );
+ const rowOptions = rowOptionsByIndex[idx];
return (
<React.Fragment key={idx}>
diff --git a/client/src/components/Web/__tests__/plugin.test.ts b/client/src/components/Web/__tests__/plugin.test.ts
new file mode 100644
index 0000000000..fc9fe9c1e4
--- /dev/null
+++ b/client/src/components/Web/__tests__/plugin.test.ts
@@ -0,0 +1,38 @@
+import type { Node } from 'unist';
+import { unicodeCitation } from '../plugin';
+
+type TestNode = { type: string; value?: string; children?: TestNode[] };
+
+const run = (value: string): TestNode[] => {
+ const tree: TestNode = {
+ type: 'root',
+ children: [{ type: 'paragraph', children: [{ type: 'text', value }] }],
+ };
+ unicodeCitation()(tree as unknown as Node);
+ return tree.children![0].children!;
+};
+
+describe('unicodeCitation plugin', () => {
+ it('parses repeated composites with a reused ref regex', () => {
+ const text =
+ '\\ue200\\ue202turn0search0\\ue202turn0search1\\ue201 and \\ue200\\ue202turn1news2\\ue201';
+ const first = run(text).filter((n) => n.type === 'composite-citation');
+ const second = run(text).filter((n) => n.type === 'composite-citation');
+ expect(first).toHaveLength(2);
+ expect(second).toEqual(first);
+ });
+
+ it('treats a marker after a closed composite as standalone', () => {
+ const nodes = run('\\ue200\\ue202turn0search0\\ue201 x \\ue202turn0search1');
+ expect(nodes.map((n) => n.type)).toEqual(['composite-citation', 'text', 'citation']);
+ });
+
+ it('does not treat a marker inside a composite as standalone, using the unicode char form', () => {
+ const nodes = run('turn0search0turn0ref1');
+ expect(nodes.map((n) => n.type)).toEqual(['composite-citation', 'citation']);
+ });
+
+ it('handles a standalone marker at the start of the text', () => {
+ expect(run('\\ue202turn0search0').map((n) => n.type)).toEqual(['citation']);
+ });
+});
diff --git a/client/src/components/Web/plugin.ts b/client/src/components/Web/plugin.ts
index a298b28f56..fad3da94f9 100644
--- a/client/src/components/Web/plugin.ts
+++ b/client/src/components/Web/plugin.ts
@@ -3,6 +3,8 @@ import type { Node } from 'unist';
import type { Citation, CitationNode } from './types';
import { SPAN_REGEX, STANDALONE_PATTERN, CLEANUP_REGEX, COMPOSITE_REGEX } from '~/utils/citations';
+const compositeRefRegex = new RegExp(STANDALONE_PATTERN.source, 'g');
+
/**
* Checks if a standalone marker is truly standalone (not inside a composite block).
* A marker is inside a composite if there's an opening \ue200 without a closing \ue201 after it.
@@ -13,17 +15,20 @@ import { SPAN_REGEX, STANDALONE_PATTERN, CLEANUP_REGEX, COMPOSITE_REGEX } from '
* - Pure Unicode format: "..."
* - Mixed formats: "\ue200..." (different formats for open/close)
*/
-function isStandaloneMarker(text: string, position: number): boolean {
- const beforeText = text.substring(0, position);
+function lastIndexBefore(text: string, needle: string, position: number): number {
+ const fromIndex = position - needle.length;
+ return fromIndex < 0 ? -1 : text.lastIndexOf(needle, fromIndex);
+}
- // Find rightmost composite block start (either format)
- const lastUe200Literal = beforeText.lastIndexOf('\\ue200');
- const lastUe200Char = beforeText.lastIndexOf('\ue200');
+function isStandaloneMarker(text: string, position: number): boolean {
+ // Find rightmost composite block start (either format), ending before `position`
+ const lastUe200Literal = lastIndexBefore(text, '\\ue200', position);
+ const lastUe200Char = lastIndexBefore(text, '\ue200', position);
const lastUe200 = Math.max(lastUe200Literal, lastUe200Char);
// Find rightmost composite block end (either format)
- const lastUe201Literal = beforeText.lastIndexOf('\\ue201');
- const lastUe201Char = beforeText.lastIndexOf('\ue201');
+ const lastUe201Literal = lastIndexBefore(text, '\\ue201', position);
+ const lastUe201Char = lastIndexBefore(text, '\ue201', position);
const lastUe201 = Math.max(lastUe201Literal, lastUe201Char);
// Standalone if: no opening marker OR closing marker appears after opening
@@ -180,7 +185,7 @@ function processTree(tree: Node) {
const compositeText = matchText;
// Use a regular expression to extract reference indices
- const compositeRefRegex = new RegExp(STANDALONE_PATTERN.source, 'g');
+ compositeRefRegex.lastIndex = 0;
let refMatch: RegExpExecArray | null;
const citations: Array<Citation> = [];
diff --git a/client/src/hooks/Artifacts/useArtifacts.ts b/client/src/hooks/Artifacts/useArtifacts.ts
index 414ceadb9a..b1f8cceed6 100644
--- a/client/src/hooks/Artifacts/useArtifacts.ts
+++ b/client/src/hooks/Artifacts/useArtifacts.ts
@@ -59,8 +59,16 @@ const getArtifactFence = (text: string, lineStart: number): ArtifactFence | null
};
const isClosingArtifactFence = (line: string, openingFence: ArtifactFence): boolean => {
- const closePattern = new RegExp(`^\\${openingFence.marker}{${openingFence.length},}\\s*$`);
- return closePattern.test(line.trim());
+ const trimmed = line.trim();
+ if (trimmed.length < openingFence.length) {
+ return false;
+ }
+ for (const char of trimmed) {
+ if (char !== openingFence.marker) {
+ return false;
+ }
+ }
+ return true;
};
const isArtifactCloseLine = (line: string): boolean => {
@@ -104,6 +112,9 @@ const hasUnfencedArtifactClose = (text: string, start: number): boolean => {
};
const hasEnclosedArtifact = (messageText: string): boolean => {
+ if (!messageText.includes(':::artifact')) {
+ return false;
+ }
const text = messageText.trim();
const artifactPattern = /:::artifact(?:\{[^}]*\})?/g;
let artifactMatch = artifactPattern.exec(text);
diff --git a/client/src/hooks/Files/useFileHandling.ts b/client/src/hooks/Files/useFileHandling.ts
index 099504b4d8..ed76e2494a 100644
--- a/client/src/hooks/Files/useFileHandling.ts
+++ b/client/src/hooks/Files/useFileHandling.ts
@@ -253,7 +253,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
setErrors([]);
}, [errors, showToast, localize]);
- const debouncedDisplayToast = debounce(displayToast, 250);
+ const debouncedDisplayToast = useMemo(() => debounce(displayToast, 250), [displayToast]);
useEffect(() => {
if (errors.length > 0) {
diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.ts
index 2e370866fe..8c42d91634 100644
--- a/client/src/hooks/Input/useAutoSave.ts
+++ b/client/src/hooks/Input/useAutoSave.ts
@@ -111,9 +111,19 @@ export const useAutoSave = ({
// Retrieve files stored in localStorage from files in fileList and set them to `setFiles`
// If a file is found with `temp_file_id`, use `temp_file_id` as a key in `setFiles`
+ const filesById = new Map<string, TFile>();
+ const filesByTempId = new Map<string, TFile>();
+ for (const f of fileList) {
+ if (!filesById.has(f.file_id)) {
+ filesById.set(f.file_id, f);
+ }
+ if (f.temp_file_id != null && !filesByTempId.has(f.temp_file_id)) {
+ filesByTempId.set(f.temp_file_id, f);
+ }
+ }
filesDraft.fileIds.forEach((fileId) => {
- const fileData = fileList?.find((f) => f.file_id === fileId);
- const tempFileData = fileList?.find((f) => f.temp_file_id === fileId);
+ const fileData = filesById.get(fileId);
+ const tempFileData = filesByTempId.get(fileId);
const { fileToRecover, fileIdToRecover } = fileData
? { fileToRecover: fileData, fileIdToRecover: fileId }
: {
diff --git a/e2e/specs/mock/scenarios/sidebar-active-row.spec.ts b/e2e/specs/mock/scenarios/sidebar-active-row.spec.ts
new file mode 100644
index 0000000000..98a18a5fdb
--- /dev/null
+++ b/e2e/specs/mock/scenarios/sidebar-active-row.spec.ts
@@ -0,0 +1,76 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { randomUUID } from 'node:crypto';
+import { deleteConversations, deleteMessagesByConversation, seedConversations } from '../db';
+import { getE2EUser } from '../../../setup/user';
+import { NEW_CHAT_PATH } from '../helpers';
+import { openSidebar } from './sidebar';
+
+const userEmail = getE2EUser().email;
+
+/** The row's own highlight, not its `hover:` variant, which every idle row carries. */
+const ACTIVE = /(^|\s)bg-surface-active-alt(\s|$)/;
+
+const row = (page: Page, title: string) =>
+ page.getByTestId('convo-item').filter({ hasText: title }).filter({ visible: true }).first();
+
+async function openRow(page: Page, id: string, title: string) {
+ await openSidebar(page);
+ await row(page, title)
+ .getByRole('button', { name: new RegExp(`^${title} conversation`) })
+ .dispatchEvent('click');
+ await expect(page).toHaveURL(new RegExp(`/c/${id}$`));
+}
+
+async function expectHighlighted(page: Page, active: string | null, titles: string[]) {
+ await openSidebar(page);
+ for (const title of titles) {
+ const target = row(page, title);
+ await expect(target).toBeVisible();
+ if (title === active) {
+ await expect(target).toHaveClass(ACTIVE);
+ } else {
+ await expect(target).not.toHaveClass(ACTIVE);
+ }
+ }
+}
+
+test.describe('sidebar active row', () => {
+ test('the sidebar highlights only the open chat and none on a new chat @scenario:sidebar-highlights-only-the-open-chat', async ({
+ page,
+ }) => {
+ test.setTimeout(60_000);
+ const first = randomUUID();
+ const second = randomUUID();
+ const firstTitle = `Active first ${first.slice(0, 8)}`;
+ const secondTitle = `Active second ${second.slice(0, 8)}`;
+ const titles = [firstTitle, secondTitle];
+ const now = Date.now();
+ try {
+ await seedConversations(userEmail, [
+ { conversationId: first, title: firstTitle, updatedAt: new Date(now) },
+ { conversationId: second, title: secondTitle, updatedAt: new Date(now - 1_000) },
+ ]);
+ await page.goto(NEW_CHAT_PATH, { timeout: 15_000 });
+ await expectHighlighted(page, null, titles);
+
+ await openRow(page, first, firstTitle);
+ await expectHighlighted(page, firstTitle, titles);
+
+ await openRow(page, second, secondTitle);
+ await expectHighlighted(page, secondTitle, titles);
+
+ await page
+ .getByRole('link', { name: 'New chat', exact: true })
+ .or(page.getByRole('button', { name: 'New chat', exact: true }))
+ .filter({ visible: true })
+ .first()
+ .click();
+ await expect(page).toHaveURL(/\/c\/new$/);
+ await expectHighlighted(page, null, titles);
+ } finally {
+ await deleteMessagesByConversation([first, second]);
+ await deleteConversations([first, second]);
+ }
+ });
+});
diff --git a/packages/client/src/components/PixelCard.tsx b/packages/client/src/components/PixelCard.tsx
index 0661b1c2db..78b4227a02 100644
--- a/packages/client/src/components/PixelCard.tsx
+++ b/packages/client/src/components/PixelCard.tsx
@@ -2,6 +2,10 @@ import { useEffect, useRef, useCallback } from 'react';
import { JSX } from 'react/jsx-runtime';
import { cn } from '~/utils';
+/** Last fillStyle written during the current frame. Reset at the start of each frame so a
+ * pixel only touches canvas state when its color differs from the previous draw. */
+let lastFillStyle = '';
+
class Pixel {
width: number;
height: number;
@@ -60,7 +64,10 @@ class Pixel {
private draw() {
const offset = this.maxSizeInteger * 0.5 - this.size * 0.5;
- this.ctx.fillStyle = this.color;
+ if (lastFillStyle !== this.color) {
+ this.ctx.fillStyle = this.color;
+ lastFillStyle = this.color;
+ }
this.ctx.fillRect(this.x + offset, this.y + offset, this.size, this.size);
}
@@ -242,20 +249,28 @@ export default function PixelCard({
ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
+ lastFillStyle = '';
let idle = true;
- for (const p of pixelsRef.current) {
- if (method === 'appearWithProgress') {
- if (progressRef.current !== undefined) {
- p.appearWithProgress(progressRef.current);
+ const pixels = pixelsRef.current;
+ if (method === 'appearWithProgress') {
+ const currentProgress = progressRef.current;
+ for (const p of pixels) {
+ if (currentProgress !== undefined) {
+ p.appearWithProgress(currentProgress);
} else {
p.isIdle = true;
}
- } else {
+ if (!p.isIdle) {
+ idle = false;
+ }
+ }
+ } else {
+ for (const p of pixels) {
// @ts-ignore dynamic dispatch
p[method]();
- }
- if (!p.isIdle) {
- idle = false;
+ if (!p.isIdle) {
+ idle = false;
+ }
}
}
@@ -291,6 +306,7 @@ export default function PixelCard({
const cx = cw / 2;
const cy = ch / 2;
const maxDist = Math.hypot(cx, cy);
+ const effectiveSpeed = getEffectiveSpeed(s, reducedMotion);
for (let x = 0; x < cw; x += g) {
for (let y = 0; y < ch; y += g) {
@@ -301,18 +317,7 @@ export default function PixelCard({
if (!ctx) {
continue;
}
- px.push(
- new Pixel(
- canvasRef.current,
- ctx,
- x,
- y,
- color,
- getEffectiveSpeed(s, reducedMotion),
- delay,
- threshold,
- ),
- );
+ px.push(new Pixel(canvasRef.current, ctx, x, y, color, effectiveSpeed, delay, threshold));
}
}
pixelsRef.current = px;
diff --git a/packages/client/src/components/SplitText.tsx b/packages/client/src/components/SplitText.tsx
index dfbc410139..8eebaa6323 100644
--- a/packages/client/src/components/SplitText.tsx
+++ b/packages/client/src/components/SplitText.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { useSprings, animated, SpringConfig } from '@react-spring/web';
interface SegmenterOptions {
@@ -45,17 +45,26 @@ interface SplitTextProps {
onLineCountChange?: (lineCount: number) => void;
}
+let segmenter: IntlSegmenter | null | undefined;
+
+const getSegmenter = (): IntlSegmenter | null => {
+ if (segmenter === undefined) {
+ segmenter =
+ typeof Intl !== 'undefined' && 'Segmenter' in Intl
+ ? new (Intl as typeof Intl & { Segmenter: IntlSegmenterConstructor }).Segmenter('en', {
+ granularity: 'grapheme',
+ })
+ : null;
+ }
+ return segmenter;
+};
+
const splitGraphemes = (text: string): string[] => {
- if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {
- const segmenter = new (Intl as typeof Intl & { Segmenter: IntlSegmenterConstructor }).Segmenter(
- 'en',
- { granularity: 'grapheme' },
- );
- const segments = segmenter.segment(text);
- return Array.from(segments).map((s: SegmentData) => s.segment);
- } else {
- return [...text];
+ const instance = getSegmenter();
+ if (instance) {
+ return Array.from(instance.segment(text)).map((s: SegmentData) => s.segment);
}
+ return [...text];
};
const SplitText: React.FC<SplitTextProps> = ({
@@ -71,21 +80,29 @@ const SplitText: React.FC<SplitTextProps> = ({
onLetterAnimationComplete,
onLineCountChange,
}) => {
- const words = text.split(' ').map(splitGraphemes);
- const letters = words.flat();
+ const { words, letterCount, offsets } = useMemo(() => {
+ const split = text.split(' ').map(splitGraphemes);
+ const starts: number[] = [];
+ let total = 0;
+ for (const w of split) {
+ starts.push(total);
+ total += w.length;
+ }
+ return { words: split, letterCount: total, offsets: starts };
+ }, [text]);
const [inView, setInView] = useState(false);
const ref = useRef<HTMLParagraphElement>(null);
const animatedCount = useRef(0);
const [springs] = useSprings(
- letters.length,
+ letterCount,
(i) => ({
from: animationFrom,
to: inView
? async (next) => {
await next(animationTo);
animatedCount.current += 1;
- if (animatedCount.current === letters.length && onLetterAnimationComplete) {
+ if (animatedCount.current === letterCount && onLetterAnimationComplete) {
onLetterAnimationComplete();
}
}
@@ -151,8 +168,7 @@ const SplitText: React.FC<SplitTextProps> = ({
style={{ display: 'inline-block', whiteSpace: 'nowrap' }}
>
{word.map((letter, letterIndex) => {
- const index =
- words.slice(0, wordIndex).reduce((acc, w) => acc + w.length, 0) + letterIndex;
+ const index = offsets[wordIndex] + letterIndex;
return (
<animated.span