Skip to content

Reviews and agents ​

These parts draw what an agent proposed or wrote. Asking the agent, keeping its proposals and deciding who may accept them stay with the app. A read-only diff of a whole file is a DiffView.

ChangeReview ​

tsx
import type { Editor } from '@adecore/editor';
import { ChangeReview, RowHost } from '@adecore/editor-react';
import { Button } from '@adecore/ui';
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { EditorFrame } from '../shared/editor-frame.tsx';
import { SAMPLE, useEditor } from '../shared/editor.ts';

const OPTIONS = { text: SAMPLE, language: 'typescript', theme: 'demo' } as const;

const SELECTED = '    for (const line of lines) {\n        total += line.price * line.quantity;\n    }\n';
const PROPOSAL = '    total = lines.reduce((sum, line) => sum + line.price * line.quantity, 0);\n';

/* A proposed change to lines 6 to 8, drawn in a row under them until a person decides. */
export default function ChangeReviewDemo() {
    const [rows, setRows] = useState<RowHost | null>(null);
    const [decided, setDecided] = useState<string | null>(null);

    const setup = useCallback((editor: Editor) => {
        const host = new RowHost(editor, 'review');
        host.set([{ id: 'proposal', line: 7, placement: 'below', height: 120 }]);
        setRows(host);

        return () => {
            host.clear();
            setRows(null);
        };
    }, []);
    const { host, editor } = useEditor(OPTIONS, setup);

    useSyncExternalStore(rows === null ? noSubscription : (listener) => rows.subscribe(listener), rows === null ? zero : () => rows.getVersion(), zero);
    useEffect(() => {
        if (decided !== null) {
            rows?.clear();
        }
    }, [decided, rows]);

    const container = rows?.container('proposal');

    return (
        <>
            <EditorFrame
                host={host}
                toolbar={<span className="px-1 text-xs text-text-muted">{decided ?? 'Accept or reject the proposal under line 8.'}</span>}
            />
            {editor !== null &&
                container !== undefined &&
                decided === null &&
                createPortal(
                    <ChangeReview
                        editor={editor}
                        selected={SELECTED}
                        proposal={PROPOSAL}
                        startLine={6}
                        label="Proposed change"
                        className="border-y border-border bg-surface"
                        actions={
                            <div className="flex gap-1 px-2 py-1">
                                <Button size="xs" variant="primary" onClick={() => setDecided('Accepted. The app applies the edit itself.')}>
                                    Accept
                                </Button>
                                <Button size="xs" onClick={() => setDecided('Rejected.')}>
                                    Reject
                                </Button>
                            </div>
                        }
                    />,
                    container
                )}
        </>
    );
}

function noSubscription(): () => void {
    return () => {};
}

function zero(): number {
    return 0;
}

ChangeReview (ChangeReviewProps) draws a proposed change to a stretch of the file in the editor's font and colors: removed lines faded with -, added lines with +, replaced words in a stronger tint. It belongs in an editor row under the stretch.

PropTypeMeaning
editorEditorThe editor whose renderCode draws the lines
selectedstringThe text as it stands
proposalstringThe text as proposed
startLinenumberThe one-based number of the first line; 1 by default
labelstringThe accessible name of the review
actionsReactNodeDrawn under the diff, such as Accept and Reject
classNamestringOn the outer section

The component accepts nothing itself. Guard the stretch with a tracked range and apply the proposal over it:

ts
const current = tracked.get();

if (current !== null && editor.textInRange(current) === selected) {
    editor.applyEdits([{ range: current, text: fitReplacement(selected, proposal) }]);
}

Proposals describes fitReplacement and parseAnswer.

AttributionCard ​

tsx
import { AGENT_COLORS, type Editor, type EditorAttributionHover } from '@adecore/editor';
import { AttributionCard } from '@adecore/editor-react';
import { useCallback, useRef, useState } from 'react';
import { EditorFrame } from '../shared/editor-frame.tsx';
import { SAMPLE, useEditor } from '../shared/editor.ts';

const OPTIONS = { text: SAMPLE, language: 'typescript', theme: 'demo' } as const;

const RUNS = {
    pricing: { title: 'Pricing agent', subtitle: 'lines 4 to 10', prompt: 'Add up the price of every line of the order.', color: AGENT_COLORS[0] },
    summary: { title: 'Writer', subtitle: 'lines 12 to 15', prompt: 'Describe an order in one sentence.', color: AGENT_COLORS[1] }
} as const;

/* Rest the pointer on a colored bar in the gutter; the card stays while the pointer is on it. */
export default function AttributionCardDemo() {
    const [hover, setHover] = useState<EditorAttributionHover | null>(null);
    const held = useRef(false);
    const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

    const setup = useCallback((editor: Editor) => {
        editor.setAttributionMarks([
            { id: 'pricing', startLine: 4, endLine: 10, color: RUNS.pricing.color },
            { id: 'summary', startLine: 12, endLine: 15, color: RUNS.summary.color }
        ]);
        const stop = editor.onAttributionHover((next) => {
            clearTimeout(timer.current);

            if (next !== null) {
                setHover(next);

                return;
            }

            // A moment to reach the card before it goes.
            timer.current = setTimeout(() => {
                if (!held.current) {
                    setHover(null);
                }
            }, 250);
        });

        return () => {
            clearTimeout(timer.current);
            stop();
        };
    }, []);
    const { host } = useEditor(OPTIONS, setup);

    const run = hover === null ? null : RUNS[hover.id as keyof typeof RUNS];

    return (
        <>
            <EditorFrame host={host} />
            {hover !== null && run !== null && (
                <AttributionCard
                    rect={hover.rect}
                    title={run.title}
                    subtitle={run.subtitle}
                    prompt={run.prompt}
                    color={run.color}
                    onHold={(inside) => {
                        held.current = inside;
                        if (!inside) {
                            setHover(null);
                        }
                    }}
                />
            )}
        </>
    );
}

AttributionCard (AttributionCardProps) describes a run of lines an agent wrote, placed at the rect that onAttributionHover reports.

PropMeaning
rectWhere the bar is, in page pixels
title, subtitleSuch as the agent's name and what it did
metadataA line of the app's own under the title
promptWhat the agent was asked, quoted
color, iconThe agent's color and an icon; a dot in that color by default
actionsButtons under the card
onHold(inside)The pointer entered or left the card, to keep it open meanwhile

Rows and actions in React ​

The editor recreates a widget row's element whenever the row scrolls back into view. RowHost tracks those elements so React can portal into them:

tsx
const rows = new RowHost(editor, 'review');
rows.set([{ id: 'proposal', line: 7, placement: 'below', height: 120 }]);

// In the component:
const containers = useSyncExternalStore(
    (listener) => rows.subscribe(listener),
    () => rows.getContainers()
);
const container = containers.get('proposal');

return container === undefined ? null : createPortal(<ChangeReview editor={editor} {...review} />, container);

getContainers returns a new map only when an element comes or goes. Call subscribe and getContainers on the host, since they are methods, not free functions. Outside a render, container(id) and getVersion read the live state.

set(rows) replaces the owner's rows, and clear() removes them. A HostedRow with fixed has an exact height; one with filler draws a hatched spacer without a portal. Keep state outside the element, since it comes and goes.

LineActionHost(editor, owner) does the same for line actions. set takes HostedActions, { id, line } with a zero-based line, and an element lives as long as its action, so React state in it survives.

The editor has one set of line highlights, which a review and a conflict may share. highlightLayers(editor) returns its HighlightLayers. set(owner, provider) takes a function returning that owner's current highlights, and set(owner, null) removes them.

One file in several editors ​

When two editors in a window show the same file, an answer to a review in one is an answer in both. joinReviewGroup(key) returns the ReviewGroup of a file key the host chooses, such as the path, and a leave() that releases it with its last editor. Each editor's review joins the group as a ReviewMember with hide(runIds), show(runIds) and refresh(). The group calls them on every member, so a run the person accepted in one editor leaves the other at once.

ts
const { group, leave } = joinReviewGroup(path);
const stop = group.join({ hide: (ids) => review.hide(ids), show: (ids) => review.show(ids), refresh: () => review.reload() });

// An answer in this editor:
group.hide(['run-3']);

// When the editor closes:
stop();
leave();

hide hides runs before the host answers, and show restores them when the host refuses.

Licenses and third-party notices are listed in each package.