Skip to content

Self-improving AI Employees for everyone

feat(chat): hover bars to edit, try again, switch versions and rate

trohitgcdf9cb812867
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsx
index 69ebaa1e..d38bc3e6 100644
--- a/client/src/features/chat/ChatPane.tsx
+++ b/client/src/features/chat/ChatPane.tsx
@@ -15,6 +15,12 @@
* reply that made it, or after the conversation for the employee's own work
* (data/approvals.ts). Ctrl/Cmd+Enter sends the newest one; the Ask first
* chip beside the box changes the rule for everything they send.
+ *
+ * The owner can change the conversation (data/branches.ts, TurnActions):
+ * edit one of their messages in place (ArrowUp in an empty box edits the
+ * last one), try the latest answer again, move between the versions of a
+ * message or an answer, and rate an answer. Each waits while a message is
+ * on its way or the employee is answering; a refusal says why.
*/
import { useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';
@@ -33,6 +39,13 @@ import {
type DecideInput,
} from './data/approvals';
import { useConversation } from './data/conversation';
+import {
+ useEditChatMessage,
+ useRegenerateChatReply,
+ useSetChatFeedback,
+ useSwitchChatBranch,
+ type ChatBranchError,
+} from './data/branches';
import { liveApprovalIds, savedApprovalIds } from './data/parts';
import { useSendChatMessage, type ChatSendError } from './data/send';
import { useStopChatRun } from './data/stop';
@@ -42,6 +55,8 @@ import { asksWhatItSays, type ChatUiActions } from './genui/actions';
import type { ChatHost, ChatPaneHandle } from './host';
import { newClientMessageId, useComposerStore } from './state/composerStore';
import { ChatThread } from './thread/ChatThread';
+import { TurnActionsContext, type TurnActions } from './thread/turnActions';
+import { branchRefusalText, feedbackThanks } from './turns/runCopy';
export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandle> }) {
const { sessionId, scope, persona, composer, notify, onSendRefused, compact = false } = host;
@@ -58,9 +73,67 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
);
const send = useSendChatMessage(sessionId, scope, onRefused);
const stop = useStopChatRun(sessionId, () => notify('Couldn’t stop the reply. Try again.', 'error'));
- const busy = send.isPending || lane !== null;
+
+ // Changing the conversation: edit, try again, another version, a rating.
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editingIn, setEditingIn] = useState(sessionId);
+ if (editingIn !== sessionId) {
+ setEditingIn(sessionId);
+ setEditingId(null);
+ }
+ const branchRefused = useCallback(
+ (error: ChatBranchError) => {
+ if (error.code === 'not_running' && onSendRefused) {
+ onSendRefused('not_running');
+ return;
+ }
+ const quiet = error.code === 'revision_conflict' || error.code === 'run_in_progress';
+ notify(branchRefusalText(error.code, persona.name), quiet ? 'info' : 'error');
+ },
+ [notify, onSendRefused, persona.name],
+ );
+ const edit = useEditChatMessage(sessionId, scope, branchRefused);
+ const regenerate = useRegenerateChatReply(sessionId, scope, branchRefused);
+ const switchBranch = useSwitchChatBranch(sessionId, scope, branchRefused);
+ const feedback = useSetChatFeedback(sessionId, scope, () => notify('Your rating didn’t save. Try again.', 'error'));
+ const changing = edit.isPending || regenerate.isPending || switchBranch.isPending;
+
+ const busy = send.isPending || lane !== null || changing;
const stopping = lane?.state === 'stopping' || stop.isPending;
+ const editMutate = edit.mutate;
+ const regenerateMutate = regenerate.mutate;
+ const switchMutate = switchBranch.mutate;
+ const feedbackMutate = feedback.mutate;
+ const turnActions = useMemo<TurnActions>(
+ () => ({
+ sessionId,
+ editingId,
+ busy,
+ startEdit: (messageId) => setEditingId(messageId),
+ cancelEdit: () => setEditingId(null),
+ saveEdit: (messageId, text) =>
+ editMutate({ messageId, text, clientMessageId: newClientMessageId() }, { onSuccess: () => setEditingId(null) }),
+ switchTo: (messageId) => switchMutate({ messageId }),
+ regenerate: (messageId) => regenerateMutate({ messageId }),
+ rate: (messageId, value) =>
+ feedbackMutate(
+ { messageId, value },
+ { onSuccess: (reaches) => value && notify(feedbackThanks(persona.name, reaches), 'success') },
+ ),
+ }),
+ [sessionId, editingId, busy, editMutate, switchMutate, regenerateMutate, feedbackMutate, notify, persona.name],
+ );
+
+ // ArrowUp in an empty box edits the owner's last message, when it can be.
+ const editLast = () => {
+ if (busy) return false;
+ const last = [...turns].reverse().find((turn) => turn.kind === 'user');
+ if (!last || last.kind !== 'user' || !last.message.editable) return false;
+ setEditingId(last.message.id);
+ return true;
+ };
+
const submit = () => {
const store = useComposerStore.getState();
if (busy || !thread.data || !(store.drafts[sessionId]?.text ?? '').trim()) return;
@@ -208,6 +281,7 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
return (
<ApprovalsContext.Provider value={approvalsValue}>
+ <TurnActionsContext.Provider value={turnActions}>
<section aria-label={`Chat with ${persona.name}`} onKeyDown={onKeyDown} className="flex min-h-0 w-full flex-1 flex-col">
<ChatThread
persona={persona}
@@ -249,12 +323,14 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
compact={compact}
boxRef={boxRef}
chips={chips}
+ onEditLast={editLast}
/>
)}
{host.footnote && <p className="m-0 text-center text-xs text-fg-muted">{host.footnote}</p>}
</div>
</div>
</section>
+ </TurnActionsContext.Provider>
</ApprovalsContext.Provider>
);
}
diff --git a/client/src/features/chat/__tests__/branches.test.tsx b/client/src/features/chat/__tests__/branches.test.tsx
new file mode 100644
index 00000000..e85e370a
--- /dev/null
+++ b/client/src/features/chat/__tests__/branches.test.tsx
@@ -0,0 +1,255 @@
+/**
+ * Changing the conversation against a fake server: editing one of the
+ * owner's messages in place (and ArrowUp to edit the last one), moving
+ * between versions, trying the latest answer again (also from the note of a
+ * run that gave none), rating an answer, copying, saying why a change was
+ * refused, and hiding the suggested questions while the owner writes.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
+}));
+
+import { resetChatRunStore } from '@/stores/chatRunStore';
+import { ChatPane } from '../ChatPane';
+import { parseMessages } from '../data/schemas';
+import type { ChatHost } from '../host';
+import { useComposerStore } from '../state/composerStore';
+import { branchRefusalText, feedbackThanks } from '../turns/runCopy';
+import '../markdown/ReplyMarkdown';
+
+type Wire = Record<string, unknown>;
+let server: { messages: Wire[]; activeRuns: Wire[]; replies: Record<string, Wire> };
+
+function row(id: string, role: 'user' | 'assistant', text: string, patch: Wire = {}): Wire {
+ return { id, role, text, message: text, timestamp: '2026-10-04T09:00:00Z', run_key: 'g1', ...patch };
+}
+
+const versions = (index: number, ids: string[]) => ({ index, count: ids.length, ids });
+
+function conversation(): Wire[] {
+ return [
+ row('m1', 'user', 'Book Saturday', { run_id: 'r1', editable: true, siblings: versions(1, ['m0', 'm1']) }),
+ row('a1', 'assistant', 'Saturday is booked.', {
+ run_id: 'r1',
+ editable: true,
+ parts: { followups: ['And Sunday?'] },
+ run: { run_id: 'r1', state: 'finished', outcome: 'success' },
+ }),
+ ];
+}
+
+function host(patch: Partial<ChatHost> = {}): ChatHost {
+ return { kind: 'home', sessionId: 'w1', scope: 'all', persona: { name: 'Maya', colorRole: 'agent' }, composer: 'send', notify: vi.fn(), ...patch };
+}
+
+function renderPane(chat: ChatHost = host()) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <ChatPane host={chat} />
+ </QueryClientProvider>,
+ );
+ return chat;
+}
+
+function requests(kind: string): Wire[] {
+ return sendRequest.mock.calls.filter(([name]) => name === kind).map(([, data]) => data as Wire);
+}
+
+beforeEach(() => {
+ resetChatRunStore();
+ useComposerStore.setState({ drafts: {} });
+ server = { messages: conversation(), activeRuns: [], replies: {} };
+ sendRequest.mockReset().mockImplementation(async (kind: string, data: Wire) => {
+ if (server.replies[kind]) return server.replies[kind];
+ switch (kind) {
+ case 'chat_subscribe':
+ return { success: true, session_id: data.session_id, hub_epoch: 'e1', active_runs: server.activeRuns };
+ case 'get_chat_messages':
+ return { success: true, messages: server.messages, thread: { active_leaf_id: 'a1', revision: 7 }, active_runs: server.activeRuns };
+ case 'edit_chat_message':
+ return { success: true, message_id: 'm2', run_id: 'r2', delivery: 'now' };
+ case 'regenerate_chat_reply':
+ return { success: true, message_id: 'm1', run_id: 'r3', delivery: 'now' };
+ case 'set_chat_feedback':
+ server.messages = server.messages.map((message) => (message.id === data.message_id ? { ...message, feedback: data.value } : message));
+ return { success: true, message_id: data.message_id, value: data.value, reaches: ['next_turn'] };
+ default:
+ return { success: true };
+ }
+ });
+});
+
+describe('the message schema', () => {
+ it('reads versions, whether it may change, and the rating', () => {
+ const [one, alone, odd] = parseMessages([
+ row('m1', 'user', 'a', { siblings: versions(1, ['m0', 'm1']), editable: true, feedback: 'down' }),
+ row('m2', 'user', 'b', { siblings: versions(0, ['m2']), editable: 'yes', feedback: 'meh' }),
+ row('m3', 'user', 'c', { siblings: { index: 3, count: 2, ids: ['x', 'y'] } }),
+ ]);
+ expect(one).toMatchObject({ siblings: versions(1, ['m0', 'm1']), editable: true, feedback: 'down' });
+ // Alone, unreadable or missing: no versions; anything odd: unchanged and unrated.
+ expect(alone).toMatchObject({ siblings: null, editable: false, feedback: null });
+ expect(odd.siblings).toBeNull();
+ });
+});
+
+describe('editing a message', () => {
+ it('opens in place, sends the edit against the revision read, and closes', async () => {
+ renderPane();
+ await screen.findByText('Book Saturday');
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }));
+ const editor = screen.getByRole('textbox', { name: 'Edit your message' });
+ expect(editor).toHaveValue('Book Saturday');
+ expect(screen.getByText('Editing starts a new branch of the conversation')).toBeInTheDocument();
+ // Unchanged: Send waits.
+ expect(screen.getByRole('button', { name: 'Send edit' })).toBeDisabled();
+ fireEvent.change(editor, { target: { value: 'Book Sunday' } });
+ fireEvent.keyDown(editor, { key: 'Enter' });
+ await waitFor(() => expect(requests('edit_chat_message')).toHaveLength(1));
+ expect(requests('edit_chat_message')[0]).toMatchObject({ session_id: 'w1', message_id: 'm1', message: 'Book Sunday', expected_revision: 7 });
+ expect(typeof requests('edit_chat_message')[0].client_message_id).toBe('string');
+ await waitFor(() => expect(screen.queryByRole('textbox', { name: 'Edit your message' })).not.toBeInTheDocument());
+ });
+
+ it('cancels with Esc or Cancel, and Esc does not stop anything', async () => {
+ renderPane();
+ await screen.findByText('Book Saturday');
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }));
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Edit your message' }), { key: 'Escape' });
+ expect(screen.queryByRole('textbox', { name: 'Edit your message' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('textbox', { name: 'Edit your message' })).not.toBeInTheDocument();
+ expect(requests('stop_chat_run')).toHaveLength(0);
+ });
+
+ it('opens on the last message with ArrowUp in an empty box', async () => {
+ renderPane();
+ await screen.findByText('Book Saturday');
+ const box = screen.getByRole('textbox', { name: 'Message Maya' });
+ fireEvent.change(box, { target: { value: 'x' } });
+ fireEvent.keyDown(box, { key: 'ArrowUp' });
+ expect(screen.queryByRole('textbox', { name: 'Edit your message' })).not.toBeInTheDocument();
+ fireEvent.change(box, { target: { value: '' } });
+ fireEvent.keyDown(box, { key: 'ArrowUp' });
+ expect(screen.getByRole('textbox', { name: 'Edit your message' })).toHaveValue('Book Saturday');
+ });
+
+ it('offers no edit where the server allows none', async () => {
+ server.messages = [row('m1', 'user', 'Book Saturday', { run_id: 'r1', editable: false })];
+ renderPane();
+ await screen.findByText('Book Saturday');
+ expect(screen.queryByRole('button', { name: 'Edit message' })).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Copy message' })).toBeInTheDocument();
+ });
+
+ it('says why an edit was refused and keeps it open', async () => {
+ const chat = renderPane();
+ server.replies.edit_chat_message = { success: false, error: 'cannot_rewind' };
+ await screen.findByText('Book Saturday');
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }));
+ const editor = screen.getByRole('textbox', { name: 'Edit your message' });
+ fireEvent.change(editor, { target: { value: 'Book Sunday' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Send edit' }));
+ await waitFor(() => expect(chat.notify).toHaveBeenCalledWith(branchRefusalText('cannot_rewind', 'Maya'), 'error'));
+ expect(screen.getByRole('textbox', { name: 'Edit your message' })).toHaveValue('Book Sunday');
+ });
+});
+
+describe('versions and trying again', () => {
+ it('moves to another version of a message', async () => {
+ renderPane();
+ await screen.findByText('Book Saturday');
+ const steps = screen.getByRole('group', { name: 'Versions' });
+ expect(within(steps).getByText('2 / 2')).toBeInTheDocument();
+ expect(within(steps).getByRole('button', { name: 'Next version' })).toBeDisabled();
+ fireEvent.click(within(steps).getByRole('button', { name: 'Previous version' }));
+ await waitFor(() => expect(requests('switch_chat_branch')).toEqual([{ session_id: 'w1', expected_revision: 7, message_id: 'm0' }]));
+ });
+
+ it('tries the latest answer again', async () => {
+ renderPane();
+ await screen.findByText('Saturday is booked.');
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(requests('regenerate_chat_reply')).toEqual([{ session_id: 'w1', expected_revision: 7, message_id: 'a1' }]));
+ });
+
+ it('tries again from the note of a run that gave no answer', async () => {
+ server.messages = [
+ row('m1', 'user', 'Book Saturday', {
+ run_id: 'r1',
+ editable: true,
+ run: { run_id: 'r1', state: 'error', outcome: null, error: { message: 'boom', code: 'run_failed' } },
+ }),
+ ];
+ renderPane();
+ await screen.findByText('Book Saturday');
+ fireEvent.click(await screen.findByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(requests('regenerate_chat_reply')).toEqual([{ session_id: 'w1', expected_revision: 7, message_id: 'm1' }]));
+ });
+});
+
+describe('rating and copying an answer', () => {
+ it('rates, says where it goes, and takes it back', async () => {
+ const chat = renderPane();
+ await screen.findByText('Saturday is booked.');
+ const good = screen.getByRole('button', { name: 'Good reply' });
+ expect(good).toHaveAttribute('aria-pressed', 'false');
+ fireEvent.click(good);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Good reply' })).toHaveAttribute('aria-pressed', 'true'));
+ await waitFor(() => expect(chat.notify).toHaveBeenCalledWith(feedbackThanks('Maya', ['next_turn']), 'success'));
+ expect(requests('set_chat_feedback')[0]).toMatchObject({ message_id: 'a1', value: 'up' });
+ // Pressed again: the rating is taken back, without a thank-you.
+ fireEvent.click(screen.getByRole('button', { name: 'Good reply' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Good reply' })).toHaveAttribute('aria-pressed', 'false'));
+ expect(requests('set_chat_feedback')[1]).toMatchObject({ message_id: 'a1', value: null });
+ expect(chat.notify).toHaveBeenCalledTimes(1);
+ });
+
+ it('puts a rating back when it does not save', async () => {
+ const chat = renderPane();
+ server.replies.set_chat_feedback = { success: false, error: 'not_found' };
+ await screen.findByText('Saturday is booked.');
+ fireEvent.click(screen.getByRole('button', { name: 'Bad reply' }));
+ await waitFor(() => expect(chat.notify).toHaveBeenCalledWith('Your rating didn’t save. Try again.', 'error'));
+ expect(screen.getByRole('button', { name: 'Bad reply' })).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('copies a message and an answer', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ renderPane();
+ await screen.findByText('Saturday is booked.');
+ fireEvent.click(screen.getByRole('button', { name: 'Copy reply' }));
+ expect(writeText).toHaveBeenLastCalledWith('Saturday is booked.');
+ expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Copy message' }));
+ expect(writeText).toHaveBeenLastCalledWith('Book Saturday');
+ });
+
+ it('hides the suggested questions while the owner writes', async () => {
+ renderPane();
+ expect(await screen.findByRole('button', { name: /And Sunday\?/ })).toBeInTheDocument();
+ fireEvent.change(screen.getByRole('textbox', { name: 'Message Maya' }), { target: { value: 'Something else' } });
+ expect(screen.queryByRole('button', { name: /And Sunday\?/ })).not.toBeInTheDocument();
+ });
+});
+
+describe('the copy', () => {
+ it('names each refusal and where a rating goes', () => {
+ expect(branchRefusalText('revision_conflict', 'Maya')).toBe('The conversation changed meanwhile. Try again.');
+ expect(branchRefusalText('run_in_progress', 'Maya')).toContain('Maya is still answering');
+ expect(branchRefusalText('older_generation', 'Maya')).toContain('before Maya restarted');
+ expect(branchRefusalText('something', 'Maya')).toBe('That didn’t go through. Try again.');
+ expect(feedbackThanks('Maya', ['next_turn', 'memory'])).toBe('Thanks — Maya will see this next time and remember it.');
+ });
+});
diff --git a/client/src/features/chat/__tests__/model.test.ts b/client/src/features/chat/__tests__/model.test.ts
index c7cc42e5..e94b39ab 100644
--- a/client/src/features/chat/__tests__/model.test.ts
+++ b/client/src/features/chat/__tests__/model.test.ts
@@ -25,6 +25,9 @@ function message(id: string, role: 'user' | 'assistant', patch: Partial<ChatMess
parts: {},
clientMessageId: null,
run: null,
+ siblings: null,
+ editable: false,
+ feedback: null,
...patch,
};
}
diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsx
index f653703c..10833f9c 100644
--- a/client/src/features/chat/composer/Composer.tsx
+++ b/client/src/features/chat/composer/Composer.tsx
@@ -4,7 +4,7 @@
* Send, which becomes Stop while the employee is answering. Enter sends,
* Shift+Enter starts a new line, and the Enter that confirms an input
* method's composition never sends (lib/composerKeys). Esc stops an answer
- * (ChatPane).
+ * (ChatPane); ArrowUp in an empty box edits the owner's last message.
*
* What is written lives in the composer store per conversation, so it
* survives switching to another employee and back. While the employee is
@@ -37,15 +37,27 @@ export interface ComposerProps {
boxRef: RefObject<HTMLTextAreaElement | null>;
/** Chips beside the button (Ask first). */
chips?: ReactNode;
+ /** ArrowUp in an empty box: edit the owner's last message. False when
+ * there is none to edit, so the key does what it always does. */
+ onEditLast?: () => boolean;
}
-export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef, chips }: ComposerProps) {
+export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef, chips, onEditLast }: ComposerProps) {
const draft = useComposerDraft(sessionId);
const setText = useComposerStore((state) => state.setText);
useAutoGrow(boxRef, draft.text);
const canSend = ready && !busy && draft.text.trim().length > 0;
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (
+ event.key === 'ArrowUp' &&
+ !draft.text &&
+ !(event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) &&
+ onEditLast?.()
+ ) {
+ event.preventDefault();
+ return;
+ }
if (!isSendKey(event)) return;
event.preventDefault();
if (canSend) onSend();
diff --git a/client/src/features/chat/data/branches.ts b/client/src/features/chat/data/branches.ts
new file mode 100644
index 00000000..167d6492
--- /dev/null
+++ b/client/src/features/chat/data/branches.ts
@@ -0,0 +1,153 @@
+/**
+ * Changing the conversation's path (docs-internal/chat_protocol.md,
+ * "Branches"): editing one of the owner's messages (`edit_chat_message`),
+ * trying the latest answer again (`regenerate_chat_reply`), moving to
+ * another version of a message or an answer (`switch_chat_branch`), and
+ * rating an answer (`set_chat_feedback`).
+ *
+ * Each names the thread's revision it was made against, so a change made
+ * meanwhile elsewhere (another tab, the employee answering) refuses it
+ * (`revision_conflict`) instead of moving a path the owner did not see. An
+ * edit or a retry starts a run, registered in the run store at once, like a
+ * sent message's. Refusals reach `onRefused` with the server's code
+ * (`ChatBranchError`); the thread is read again either way.
+ */
+
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { queryKeys } from '@/lib/queryConfig';
+import { useChatRunStore } from '@/stores/chatRunStore';
+import type { ChatThreadData, Feedback } from './schemas';
+import { chatThreadKey, type ThreadScope } from './thread';
+
+/** A change to the conversation that did not go through: `code` is the
+ * server's (`revision_conflict`, `run_in_progress`, `cannot_rewind`,
+ * `older_generation`, `branch_unavailable`, `not_editable`, `not_running`,
+ * ...) or `transport`. */
+export class ChatBranchError extends Error {
+ readonly code: string;
+
+ constructor(code: string) {
+ super(code);
+ this.name = 'ChatBranchError';
+ this.code = code;
+ }
+}
+
+type Reply = {
+ success?: boolean;
+ error?: string;
+ run_id?: string | null;
+ message_id?: string | null;
+ delivery?: string;
+ reaches?: unknown;
+};
+
+export interface StartedRun {
+ runId: string | null;
+ /** The owner's message the run answers. */
+ messageId: string | null;
+ delivery: 'now' | 'queued' | null;
+}
+
+function useBranchRequest(sessionId: string, scope: ThreadScope) {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ const revision = () => queryClient.getQueryData<ChatThreadData>(chatThreadKey(sessionId, scope))?.thread.revision ?? 0;
+ const request = async (kind: string, data: Record<string, unknown>): Promise<Reply> => {
+ let reply: Reply | undefined;
+ try {
+ reply = await sendRequest<Reply>(kind, { session_id: sessionId, expected_revision: revision(), ...data });
+ } catch {
+ throw new ChatBranchError('transport');
+ }
+ if (!reply || reply.success === false) throw new ChatBranchError(reply?.error || 'failed');
+ return reply;
+ };
+ const refetch = () => queryClient.invalidateQueries({ queryKey: queryKeys.chatThread.bySession(sessionId).queryKey });
+ return { request, refetch, queryClient };
+}
+
+function started(sessionId: string, reply: Reply): StartedRun {
+ const result: StartedRun = {
+ runId: reply.run_id ?? null,
+ messageId: reply.message_id ?? null,
+ delivery: reply.delivery === 'queued' ? 'queued' : reply.delivery === 'now' ? 'now' : null,
+ };
+ if (result.runId && result.messageId) {
+ useChatRunStore.getState().admit(sessionId, {
+ runId: result.runId,
+ userMessageId: result.messageId,
+ state: result.delivery === 'queued' ? 'queued' : 'pending',
+ });
+ }
+ return result;
+}
+
+/** Edit one of the owner's messages: the edit goes after the same earlier
+ * message, as a new version of it, and the employee answers it. */
+export function useEditChatMessage(sessionId: string, scope: ThreadScope, onRefused?: (error: ChatBranchError) => void) {
+ const { request, refetch } = useBranchRequest(sessionId, scope);
+ return useMutation<StartedRun, ChatBranchError, { messageId: string; text: string; clientMessageId: string }>({
+ mutationFn: async ({ messageId, text, clientMessageId }) =>
+ started(sessionId, await request('edit_chat_message', { message_id: messageId, message: text, client_message_id: clientMessageId })),
+ onError: (error) => onRefused?.(error),
+ onSettled: refetch,
+ });
+}
+
+/** Try the latest answer again: a new version of it, answering the same
+ * message. */
+export function useRegenerateChatReply(sessionId: string, scope: ThreadScope, onRefused?: (error: ChatBranchError) => void) {
+ const { request, refetch } = useBranchRequest(sessionId, scope);
+ return useMutation<StartedRun, ChatBranchError, { messageId: string }>({
+ mutationFn: async ({ messageId }) => started(sessionId, await request('regenerate_chat_reply', { message_id: messageId })),
+ onError: (error) => onRefused?.(error),
+ onSettled: refetch,
+ });
+}
+
+/** Show another version of a message or an answer, and the conversation
+ * that followed it. */
+export function useSwitchChatBranch(sessionId: string, scope: ThreadScope, onRefused?: (error: ChatBranchError) => void) {
+ const { request, refetch } = useBranchRequest(sessionId, scope);
+ return useMutation<void, ChatBranchError, { messageId: string }>({
+ mutationFn: async ({ messageId }) => {
+ await request('switch_chat_branch', { message_id: messageId });
+ },
+ onError: (error) => onRefused?.(error),
+ onSettled: refetch,
+ });
+}
+
+/** Where a rating goes: `next_turn` (the employee reads it before its next
+ * answer) and `memory` (a Memory tool keeps it). */
+export type FeedbackReach = 'next_turn' | 'memory';
+
+/** Rate an answer good or bad, or take the rating back (`null`). Shown at
+ * once; put back when the server refuses. */
+export function useSetChatFeedback(sessionId: string, scope: ThreadScope, onRefused?: (error: ChatBranchError) => void) {
+ const { request, refetch, queryClient } = useBranchRequest(sessionId, scope);
+ const key = chatThreadKey(sessionId, scope);
+ const setLocal = (messageId: string, value: Feedback | null) =>
+ queryClient.setQueryData<ChatThreadData>(key, (data) =>
+ data ? { ...data, messages: data.messages.map((message) => (message.id === messageId ? { ...message, feedback: value } : message)) } : data,
+ );
+ return useMutation<FeedbackReach[], ChatBranchError, { messageId: string; value: Feedback | null }, { before: Feedback | null }>({
+ mutationFn: async ({ messageId, value }) => {
+ const reply = await request('set_chat_feedback', { message_id: messageId, value });
+ const reaches = Array.isArray(reply.reaches) ? reply.reaches : [];
+ return reaches.filter((reach): reach is FeedbackReach => reach === 'next_turn' || reach === 'memory');
+ },
+ onMutate: ({ messageId, value }) => {
+ const before = queryClient.getQueryData<ChatThreadData>(key)?.messages.find((message) => message.id === messageId)?.feedback ?? null;
+ setLocal(messageId, value);
+ return { before };
+ },
+ onError: (error, { messageId }, context) => {
+ setLocal(messageId, context?.before ?? null);
+ onRefused?.(error);
+ },
+ onSettled: refetch,
+ });
+}
diff --git a/client/src/features/chat/data/schemas.ts b/client/src/features/chat/data/schemas.ts
index 99c10cd3..0be20099 100644
--- a/client/src/features/chat/data/schemas.ts
+++ b/client/src/features/chat/data/schemas.ts
@@ -43,6 +43,29 @@ const messageRunSchema = z
}),
);
+/** The messages sharing this one's place in the conversation (its parent),
+ * oldest first: the owner's edits of a message, or the answers tried for
+ * one. `index` is this one's. */
+export interface MessageSiblings {
+ index: number;
+ count: number;
+ ids: string[];
+}
+
+export type Feedback = 'up' | 'down';
+
+const siblingsSchema = z
+ .object({
+ index: z.number().int().nonnegative(),
+ count: z.number().int().positive(),
+ ids: z.array(z.union([z.string(), z.number()]).transform(String)),
+ })
+ .transform((siblings): MessageSiblings | null =>
+ siblings.ids.length === siblings.count && siblings.index < siblings.count
+ ? { index: siblings.index, count: siblings.count, ids: siblings.ids }
+ : null,
+ );
+
const messageSchema = z
.object({
id: z.union([z.number(), z.string()]).transform(String),
@@ -60,6 +83,9 @@ const messageSchema = z
parts: z.record(z.string(), z.unknown()).catch({}),
client_message_id: z.string().nullable().catch(null),
run: messageRunSchema.nullable().catch(null),
+ siblings: siblingsSchema.nullable().catch(null),
+ editable: z.boolean().catch(false),
+ feedback: z.enum(['up', 'down']).nullable().catch(null),
})
.transform((row) => ({
id: row.id,
@@ -76,6 +102,12 @@ const messageSchema = z
parts: row.parts,
clientMessageId: row.client_message_id,
run: row.run,
+ /** Null when it is the only one. */
+ siblings: row.siblings && row.siblings.count > 1 ? row.siblings : null,
+ /** The owner may edit it (their message) or try it again (the latest
+ * answer); the server decides. */
+ editable: row.editable,
+ feedback: row.feedback as Feedback | null,
}));
export type ChatMessage = z.output<typeof messageSchema> & {
diff --git a/client/src/features/chat/data/send.ts b/client/src/features/chat/data/send.ts
index 2648a569..06c62728 100644
--- a/client/src/features/chat/data/send.ts
+++ b/client/src/features/chat/data/send.ts
@@ -130,6 +130,9 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefu
parts: {},
clientMessageId,
run: null,
+ siblings: null,
+ editable: false,
+ feedback: null,
pending: true,
};
replace((messages) => [...messages.filter((message) => message.id !== pending.id), pending]);
diff --git a/client/src/features/chat/thread/turnActions.ts b/client/src/features/chat/thread/turnActions.ts
new file mode 100644
index 00000000..e65388be
--- /dev/null
+++ b/client/src/features/chat/thread/turnActions.ts
@@ -0,0 +1,31 @@
+/**
+ * What the owner can do to a saved turn (design handoff chat, "Thread"):
+ * edit their message, move between the versions of a message or of an
+ * answer, try the latest answer again, rate an answer. ChatPane provides it;
+ * turns without it (a host that shows the chat only) offer none of this,
+ * and Copy still works.
+ */
+
+import { createContext, useContext } from 'react';
+import type { Feedback } from '../data/schemas';
+
+export interface TurnActions {
+ sessionId: string;
+ /** The owner's message being edited, if any. */
+ editingId: string | null;
+ /** A message is on its way, the employee is answering, or the
+ * conversation is changing: nothing else may change it now. */
+ busy: boolean;
+ startEdit: (messageId: string) => void;
+ cancelEdit: () => void;
+ saveEdit: (messageId: string, text: string) => void;
+ switchTo: (messageId: string) => void;
+ regenerate: (messageId: string) => void;
+ rate: (messageId: string, value: Feedback | null) => void;
+}
+
+export const TurnActionsContext = createContext<TurnActions | null>(null);
+
+export function useTurnActions(): TurnActions | null {
+ return useContext(TurnActionsContext);
+}
diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsx
index e3946363..41ea84c0 100644
--- a/client/src/features/chat/turns/AssistantTurn.tsx
+++ b/client/src/features/chat/turns/AssistantTurn.tsx
@@ -16,8 +16,9 @@
* themes paint as a bubble.
*/
-import { CircleAlert, Pause, Square } from 'lucide-react';
+import { CircleAlert, Pause, RotateCcw, Square } from 'lucide-react';
import { Suspense, lazy, useMemo, type ReactNode } from 'react';
+import { Button } from '@/components/ui/button';
import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';
import type { UiStateChange } from '@/lib/jsonRender/uiState';
import { cn } from '@/lib/utils';
@@ -43,9 +44,12 @@ import { citationOrder } from '../markdown/citations';
import { ChatAvatar } from '../thread/ChatAvatar';
import type { TurnWork } from '../thread/model';
import { timeLabel } from '../thread/timeLabel';
+import { useComposerStore } from '../state/composerStore';
+import { useTurnActions } from '../thread/turnActions';
import { ArtifactCard } from './ArtifactCard';
import { GeneratedUiBlock } from './GeneratedUiBlock';
import { FollowUps } from './FollowUps';
+import { ReplyActions } from './ReplyActions';
import { failureLines, liveLabel, liveText } from './runCopy';
import { SourceChips } from './SourceChips';
import { StatusLine } from './StatusLine';
@@ -55,6 +59,12 @@ import { useWritingRate } from './useWritingRate';
const NO_UI: UiPart[] = [];
+/** Whether the owner has written something in this chat's box. */
+function useDrafting(): boolean {
+ const sessionId = useTurnActions()?.sessionId ?? null;
+ return useComposerStore((state) => Boolean(sessionId && state.drafts[sessionId]?.text.trim()));
+}
+
// Its own chunk: the markdown stack stays out of the first load.
const ReplyMarkdown = lazy(() => import('../markdown/ReplyMarkdown'));
@@ -128,6 +138,25 @@ export function AssistantTurn({
const narration = streamed.narration;
const rate = useWritingRate(text, streaming, now);
const failure = run?.state === 'error' ? failureLines(run.error, persona.name) : null;
+ // A run that ended without saving an answer can be tried again from its
+ // note (an answer it saved has Try again in its bar).
+ const actions = useTurnActions();
+ const question = run?.userMessageId ?? null;
+ const retry =
+ !message && latest && actions && question && (run?.state === 'stopped' || run?.state === 'error') ? (
+ <div>
+ <Button
+ variant="quiet"
+ size="sm"
+ disabled={actions.busy}
+ onClick={() => actions.regenerate(question)}
+ className="-ml-2 h-7 gap-1.5 px-2 text-xs font-semibold text-fg-default"
+ >
+ <RotateCcw aria-hidden className="size-3.25" strokeWidth={2} />
+ Try again
+ </Button>
+ </div>
+ ) : null;
const saved = message ? savedUiParts(message.parts) : NO_UI;
const interfaces = saved.length > 0 ? saved : liveUi;
// The documents it wrote, at the latest version the reply or the run names.
@@ -140,8 +169,13 @@ export function AssistantTurn({
() => [...new Set([...savedApprovalIds(message?.parts), ...liveApprovalIds(run?.activities)])],
[message?.parts, run?.activities],
);
- // Only under the latest answer, once it is done.
- const followups = message && latest && !live && onFollowUp ? savedFollowups(message.parts) : [];
+ // Only under the latest answer, once it is done, not stopped, and while
+ // the owner is not writing something else.
+ const drafting = useDrafting();
+ const followups =
+ message && latest && !live && onFollowUp && !drafting && message.status !== 'stopped' && run?.state !== 'stopped'
+ ? savedFollowups(message.parts)
+ : [];
const citations = useMemo<CitationInfo>(() => {
if (!message) return NO_CITATIONS;
const known = sources ?? new Map(savedSources(message.parts).map((source) => [source.n, source] as const));
@@ -210,6 +244,7 @@ export function AssistantTurn({
{run?.state === 'stopped' && (
<Note icon="stop">
<p className="m-0">You stopped this reply.</p>
+ {retry}
</Note>
)}
{failure && (
@@ -217,11 +252,17 @@ export function AssistantTurn({
<p className="m-0 text-fg-default">{failure.headline}</p>
{failure.detail && <p className="m-0">{failure.detail}</p>}
{run?.error?.hint && <p className="m-0">{run.error.hint}</p>}
+ {retry}
</Note>
)}
{citations.order.size > 0 && <SourceChips sources={citations.sources} order={citations.order} />}
{followups.length > 0 && onFollowUp && <FollowUps items={followups} onPick={onFollowUp} />}
- {message && <TurnMeta shown={latest}>{timeLabel(message.timestamp, now)}</TurnMeta>}
+ {message &&
+ (live ? (
+ <TurnMeta shown={latest}>{timeLabel(message.timestamp, now)}</TurnMeta>
+ ) : (
+ <ReplyActions message={message} latest={latest} now={now} />
+ ))}
</div>
</div>
);
diff --git a/client/src/features/chat/turns/ReplyActions.tsx b/client/src/features/chat/turns/ReplyActions.tsx
new file mode 100644
index 00000000..c7e40859
--- /dev/null
+++ b/client/src/features/chat/turns/ReplyActions.tsx
@@ -0,0 +1,97 @@
+/**
+ * The bar under a finished answer (design handoff chat, "Assistant row"):
+ * Copy, Good and Bad (a rating the employee reads before its next answer;
+ * pressing it again takes it back), Try again on the latest answer, ‹ 1 / 2
+ * › between the answers tried for the same message, and when it was written.
+ * Faint until the turn is hovered or focused, except under the latest
+ * answer. Rating and Try again need the chat's TurnActions; Copy always
+ * works.
+ */
+
+import { Check, Copy, RotateCcw, ThumbsDown, ThumbsUp } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { cn } from '@/lib/utils';
+import type { ChatMessage, Feedback } from '../data/schemas';
+import { timeLabel } from '../thread/timeLabel';
+import { useTurnActions } from '../thread/turnActions';
+import { TurnMeta } from './TurnMeta';
+import { useCopied } from './useCopied';
+import { VersionStepper } from './VersionStepper';
+
+function RateButton({
+ value,
+ current,
+ disabled,
+ onRate,
+}: {
+ value: Feedback;
+ current: Feedback | null;
+ disabled: boolean;
+ onRate: (value: Feedback | null) => void;
+}) {
+ const on = current === value;
+ const Icon = value === 'up' ? ThumbsUp : ThumbsDown;
+ const label = value === 'up' ? 'Good reply' : 'Bad reply';
+ return (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ disabled={disabled}
+ onClick={() => onRate(on ? null : value)}
+ aria-label={label}
+ aria-pressed={on}
+ title={label}
+ className={cn(on && 'text-fg-default')}
+ >
+ <Icon aria-hidden className="size-3.5" strokeWidth={1.9} fill={on ? 'currentColor' : 'none'} />
+ </Button>
+ );
+}
+
+export function ReplyActions({ message, latest, now }: { message: ChatMessage; latest: boolean; now: Date }) {
+ const actions = useTurnActions();
+ const [copied, copy] = useCopied();
+ // An answer a run gave can be rated; a note from OpenCompany cannot.
+ const rateable = Boolean(actions && message.runId && message.kind === 'text');
+ return (
+ <TurnMeta shown={latest} className="-ml-1.5 h-7 gap-0.5 px-0">
+ {message.text.trim() && (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ onClick={() => copy(message.text)}
+ aria-label={copied ? 'Copied' : 'Copy reply'}
+ title={copied ? 'Copied' : 'Copy'}
+ >
+ {copied ? (
+ <Check aria-hidden className="size-3.5 text-action-run-ink" strokeWidth={1.9} />
+ ) : (
+ <Copy aria-hidden className="size-3.5" strokeWidth={1.9} />
+ )}
+ </Button>
+ )}
+ {rateable && actions && (
+ <>
+ <RateButton value="up" current={message.feedback} disabled={false} onRate={(value) => actions.rate(message.id, value)} />
+ <RateButton value="down" current={message.feedback} disabled={false} onRate={(value) => actions.rate(message.id, value)} />
+ </>
+ )}
+ {message.editable && actions && (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ disabled={actions.busy}
+ onClick={() => actions.regenerate(message.id)}
+ aria-label="Try again"
+ title="Try again"
+ >
+ <RotateCcw aria-hidden className="size-3.5" strokeWidth={1.9} />
+ </Button>
+ )}
+ {message.siblings && actions && (
+ <VersionStepper siblings={message.siblings} noun="reply" disabled={actions.busy} onSwitch={actions.switchTo} />
+ )}
+ <span className="px-1.5">{timeLabel(message.timestamp, now)}</span>
+ </TurnMeta>
+ );
+}
diff --git a/client/src/features/chat/turns/UserEditBox.tsx b/client/src/features/chat/turns/UserEditBox.tsx
new file mode 100644
index 00000000..99956435
--- /dev/null
+++ b/client/src/features/chat/turns/UserEditBox.tsx
@@ -0,0 +1,91 @@
+/**
+ * Editing one of the owner's messages in place (design handoff chat, "Edit
+ * & branch"): the text in a box where the bubble was, that editing starts a
+ * new branch of the conversation, Cancel and Send. Enter sends (Shift+Enter
+ * a new line), Esc cancels. Sending an unchanged or empty message does
+ * nothing.
+ */
+
+import { useLayoutEffect, useRef, useState, type KeyboardEvent } from 'react';
+import { Button } from '@/components/ui/button';
+import { Textarea } from '@/components/ui/textarea';
+import { isSendKey } from '@/lib/composerKeys';
+import { useAutoGrow } from '@/lib/useAutoGrow';
+import { cn } from '@/lib/utils';
+
+export function UserEditBox({
+ initial,
+ compact,
+ busy,
+ onCancel,
+ onSave,
+}: {
+ initial: string;
+ compact: boolean;
+ /** The conversation cannot change now: Send waits. */
+ busy: boolean;
+ onCancel: () => void;
+ onSave: (text: string) => void;
+}) {
+ const [text, setText] = useState(initial);
+ const boxRef = useRef<HTMLTextAreaElement>(null);
+ useAutoGrow(boxRef, text);
+ useLayoutEffect(() => {
+ const box = boxRef.current;
+ if (!box) return;
+ box.focus();
+ box.setSelectionRange(box.value.length, box.value.length);
+ }, []);
+ const changed = text.trim().length > 0 && text.trim() !== initial.trim();
+ const save = () => {
+ if (changed && !busy) onSave(text.trim());
+ };
+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ onCancel();
+ return;
+ }
+ if (!isSendKey(event)) return;
+ event.preventDefault();
+ save();
+ };
+ return (
+ <div
+ className={cn(
+ 'flex w-full flex-col gap-2.5 rounded-draft border border-border-strong bg-bg-panel',
+ compact ? 'px-3 py-2' : 'px-3.5 py-3',
+ )}
+ >
+ <Textarea
+ ref={boxRef}
+ variant="bare"
+ rows={2}
+ value={text}
+ onChange={(event) => setText(event.target.value)}
+ onKeyDown={onKeyDown}
+ aria-label="Edit your message"
+ className={cn(
+ 'max-h-(--h-chat-composer-max) overflow-hidden text-fg-default field-sizing-fixed',
+ compact ? 'text-sm leading-normal' : 'text-md leading-normal',
+ )}
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-xs text-fg-faint">Editing starts a new branch of the conversation</span>
+ <Button variant="quiet" size="sm" onClick={onCancel} className="ml-auto h-7.5 rounded-lg border-border-default px-3 text-xs font-semibold text-fg-default">
+ Cancel
+ </Button>
+ <Button
+ variant="invert"
+ size="sm"
+ onClick={save}
+ disabled={!changed || busy}
+ aria-label="Send edit"
+ className="h-7.5 rounded-lg px-3 text-xs font-semibold"
+ >
+ Send
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/features/chat/turns/UserTurn.tsx b/client/src/features/chat/turns/UserTurn.tsx
index f806b020..07486948 100644
--- a/client/src/features/chat/turns/UserTurn.tsx
+++ b/client/src/features/chat/turns/UserTurn.tsx
@@ -1,22 +1,45 @@
/**
* The owner's message: a bubble on the right (design handoff chat,
- * "Thread"), with when they sent it under it. A button they pressed in an
- * interface the employee showed (`kind: "action"`) reads as the press: the
- * button's label beside a pointer, in a quieter pill. `chat-msg
- * chat-msg-user` is the theme hook the stylized themes paint.
+ * "Thread"). A button they pressed in an interface the employee showed
+ * (`kind: "action"`) reads as the press: the button's label beside a
+ * pointer, in a quieter pill. `chat-msg chat-msg-user` is the theme hook the
+ * stylized themes paint.
+ *
+ * Under it, the hover bar: when they sent it, ‹ 1 / 2 › between their edits
+ * of it, Edit (it opens in place; sending the edit starts a new branch of
+ * the conversation), and Copy. Edit shows only where the server allows it
+ * (`editable`) and the chat offers it (TurnActions).
*/
-import { MousePointerClick } from 'lucide-react';
+import { Check, Copy, MousePointerClick, Pencil } from 'lucide-react';
+import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type { ChatMessage } from '../data/schemas';
import { timeLabel } from '../thread/timeLabel';
+import { useTurnActions } from '../thread/turnActions';
import { TurnMeta } from './TurnMeta';
+import { useCopied } from './useCopied';
+import { UserEditBox } from './UserEditBox';
+import { VersionStepper } from './VersionStepper';
export function UserTurn({ message, now, latest, compact }: { message: ChatMessage; now: Date; latest: boolean; compact: boolean }) {
+ const actions = useTurnActions();
+ const [copied, copy] = useCopied();
const pressed = message.kind === 'action';
+ const editing = Boolean(actions && actions.editingId === message.id);
+ const canEdit = Boolean(actions && message.editable && !pressed && !message.pending);
+
return (
<div data-turn="user" data-message={message.id} className="chat-turn-user group/turn flex flex-col items-end gap-1.5">
- {pressed ? (
+ {editing && actions ? (
+ <UserEditBox
+ initial={message.text}
+ compact={compact}
+ busy={actions.busy}
+ onCancel={actions.cancelEdit}
+ onSave={(text) => actions.saveEdit(message.id, text)}
+ />
+ ) : pressed ? (
<p
className={cn(
'm-0 flex max-w-[85%] items-center gap-2 rounded-pill border border-border-default bg-bg-panel text-fg-muted wrap-anywhere',
@@ -37,7 +60,44 @@ export function UserTurn({ message, now, latest, compact }: { message: ChatMessa
{message.text}
</p>
)}
- <TurnMeta shown={latest || message.pending}>{message.pending ? 'Sending…' : timeLabel(message.timestamp, now)}</TurnMeta>
+ {!editing &&
+ (message.pending ? (
+ <TurnMeta shown>Sending…</TurnMeta>
+ ) : (
+ <TurnMeta shown={latest} className="h-7 gap-0.5 px-0">
+ <span className="px-1.5">{timeLabel(message.timestamp, now)}</span>
+ {message.siblings && actions && (
+ <VersionStepper siblings={message.siblings} noun="version" disabled={actions.busy} onSwitch={actions.switchTo} />
+ )}
+ {canEdit && actions && (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ disabled={actions.busy}
+ onClick={() => actions.startEdit(message.id)}
+ aria-label="Edit message"
+ title="Edit"
+ >
+ <Pencil aria-hidden className="size-3.5" strokeWidth={1.9} />
+ </Button>
+ )}
+ {!pressed && (
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ onClick={() => copy(message.text)}
+ aria-label={copied ? 'Copied' : 'Copy message'}
+ title={copied ? 'Copied' : 'Copy'}
+ >
+ {copied ? (
+ <Check aria-hidden className="size-3.5 text-action-run-ink" strokeWidth={1.9} />
+ ) : (
+ <Copy aria-hidden className="size-3.5" strokeWidth={1.9} />
+ )}
+ </Button>
+ )}
+ </TurnMeta>
+ ))}
</div>
);
}
diff --git a/client/src/features/chat/turns/VersionStepper.tsx b/client/src/features/chat/turns/VersionStepper.tsx
new file mode 100644
index 00000000..46e58322
--- /dev/null
+++ b/client/src/features/chat/turns/VersionStepper.tsx
@@ -0,0 +1,54 @@
+/**
+ * ‹ 1 / 2 › between the versions of a message (the owner's edits) or of an
+ * answer (the tries), in the turn's hover bar. Moving shows that version and
+ * the conversation that followed it. Off while the conversation cannot
+ * change.
+ */
+
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import type { MessageSiblings } from '../data/schemas';
+
+export function VersionStepper({
+ siblings,
+ noun,
+ disabled,
+ onSwitch,
+}: {
+ siblings: MessageSiblings;
+ /** What steps: "version" (a message) or "reply" (an answer). */
+ noun: 'version' | 'reply';
+ disabled: boolean;
+ onSwitch: (messageId: string) => void;
+}) {
+ const { index, count, ids } = siblings;
+ const go = (to: number) => {
+ const id = ids[to];
+ if (id !== undefined) onSwitch(id);
+ };
+ return (
+ <span role="group" aria-label={noun === 'reply' ? 'Replies' : 'Versions'} className="flex items-center font-mono text-xs text-fg-muted">
+ <Button
+ variant="quiet"
+ size="icon-xs"
+ disabled={disabled || index === 0}
+ onClick={() => go(index - 1)}
+ aria-label={`Previous ${noun}`}
+ >
+ <ChevronLeft aria-hidden className="size-3.25" strokeWidth={2.2} />
+ </Button>
+ <span className="tabular-nums">
+ {index + 1} / {count}
+ </span>
+ <Button
+ variant="quiet"
+ size="icon-xs"
+ disabled={disabled || index === count - 1}
+ onClick={() => go(index + 1)}
+ aria-label={`Next ${noun}`}
+ >
+ <ChevronRight aria-hidden className="size-3.25" strokeWidth={2.2} />
+ </Button>
+ </span>
+ );
+}
diff --git a/client/src/features/chat/turns/runCopy.ts b/client/src/features/chat/turns/runCopy.ts
index 7d23d4a6..4d87414e 100644
--- a/client/src/features/chat/turns/runCopy.ts
+++ b/client/src/features/chat/turns/runCopy.ts
@@ -87,3 +87,32 @@ export function stepDetail(step: RunStep): string | null {
if (step.state === 'failed') return step.detail ? `Failed · ${step.detail}` : 'Failed';
return step.detail ?? null;
}
+
+/** Why a change to the conversation (an edit, Try again, another version)
+ * did not go through, by the server's code. */
+export function branchRefusalText(code: string, name: string): string {
+ switch (code) {
+ case 'revision_conflict':
+ return 'The conversation changed meanwhile. Try again.';
+ case 'run_in_progress':
+ return `${name} is still answering. Try again once they finish.`;
+ case 'cannot_rewind':
+ return `${name} has summed up the conversation since, so it can’t go back to that point.`;
+ case 'older_generation':
+ return `That’s from before ${name} restarted, so it can’t be changed.`;
+ case 'branch_unavailable':
+ return 'That version can’t be brought back any more.';
+ case 'not_editable':
+ case 'not_found':
+ return 'That can’t be changed.';
+ default:
+ return 'That didn’t go through. Try again.';
+ }
+}
+
+/** What the owner hears after rating an answer: where the rating goes. */
+export function feedbackThanks(name: string, reaches: readonly string[]): string {
+ return reaches.includes('memory')
+ ? `Thanks — ${name} will see this next time and remember it.`
+ : `Thanks — ${name} will see this next time.`;
+}
diff --git a/client/src/features/chat/turns/useCopied.ts b/client/src/features/chat/turns/useCopied.ts
new file mode 100644
index 00000000..ec762e32
--- /dev/null
+++ b/client/src/features/chat/turns/useCopied.ts
@@ -0,0 +1,25 @@
+/**
+ * Copy text, and say so for a moment ("Copied", a check) on the button that
+ * did it. A clipboard the page may not write to copies nothing and says
+ * nothing.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+
+export const COPIED_MS = 1600;
+
+export function useCopied(): [boolean, (text: string) => void] {
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ if (!copied) return;
+ const timer = window.setTimeout(() => setCopied(false), COPIED_MS);
+ return () => window.clearTimeout(timer);
+ }, [copied]);
+ const copy = useCallback((text: string) => {
+ void navigator.clipboard?.writeText(text).then(
+ () => setCopied(true),
+ () => undefined,
+ );
+ }, []);
+ return [copied, copy];
+}