diff --git a/ui-packages/web/src/core/conversations.ts b/ui-packages/web/src/core/conversations.ts index 83fbdfe..148fdf8 100644 --- a/ui-packages/web/src/core/conversations.ts +++ b/ui-packages/web/src/core/conversations.ts @@ -21,6 +21,8 @@ export type StoredConversation = { titledBy?: TitleSource selection?: ModelSelection draft: ConversationDraft + // Sent while a reply was running and not yet given to the model. + queued?: ConversationDraft[] createdAt: number lastActiveAt: number } @@ -40,6 +42,22 @@ export type ConversationPage = { export const emptyConversationDraft = (): ConversationDraft => ({ text: '', attachments: [] }) +// Queued messages were written before the draft, so they come first. +export const foldQueued = ( + draft: ConversationDraft, + queued: readonly ConversationDraft[], +): ConversationDraft => ({ + text: [...queued.map(item => item.text), draft.text].filter(text => text.trim()).join('\n\n'), + attachments: [...queued.flatMap(item => item.attachments), ...draft.attachments], +}) + +// A queue only means something while its reply runs; a conversation opened later gets it back as +// its draft. +export const returnQueuedToDraft = (conversation: StoredConversation): StoredConversation => + conversation.queued?.length + ? { ...conversation, draft: foldQueued(conversation.draft, conversation.queued), queued: [] } + : conversation + export const conversationTitle = (draft: ConversationDraft) => { const firstLine = draft.text.trim().split(/\r?\n/, 1)[0]?.replace(/\s+/g, ' ') const source = firstLine || draft.attachments[0]?.name || 'New conversation' diff --git a/ui-packages/web/src/data/conversation-store.test.ts b/ui-packages/web/src/data/conversation-store.test.ts index 66216f0..f4eda51 100644 --- a/ui-packages/web/src/data/conversation-store.test.ts +++ b/ui-packages/web/src/data/conversation-store.test.ts @@ -63,6 +63,22 @@ describe('conversation store', () => { expect((await listStoredFiles()).some(file => file.path === 'Shared.md')).toBe(true) }) + it('opens a conversation with its unsent queue returned to the draft', async () => { + await saveStoredConversationDraft({ + ...conversation('queued', 10), + draft: { text: 'Still typing', attachments: [] }, + queued: [ + { text: 'First queued', attachments: [] }, + { text: 'Second queued', attachments: [] }, + ], + }) + + const opened = await getStoredConversation('queued') + + expect(opened?.conversation.draft.text).toBe('First queued\n\nSecond queued\n\nStill typing') + expect(opened?.conversation.queued).toEqual([]) + }) + it('pages by activity and id without duplicates when timestamps match', async () => { await Promise.all( Array.from({ length: 65 }, (_, index) => diff --git a/ui-packages/web/src/data/conversation-store.ts b/ui-packages/web/src/data/conversation-store.ts index bfb4416..b63c7bd 100644 --- a/ui-packages/web/src/data/conversation-store.ts +++ b/ui-packages/web/src/data/conversation-store.ts @@ -1,9 +1,10 @@ import type { AgentMessage } from '@earendil-works/pi-agent-core' -import type { - ConversationCursor, - ConversationPage, - StoredConversation, - TitleSource, +import { + type ConversationCursor, + type ConversationPage, + returnQueuedToDraft, + type StoredConversation, + type TitleSource, } from '../core/conversations' import { openWorkspaceDatabase, requestPersistentStorage } from './workspace-database' @@ -55,7 +56,7 @@ export const getStoredConversation = async (id: string) => { ]) if (!conversation) return null return { - conversation, + conversation: returnQueuedToDraft(conversation), messages: records .sort((left, right) => left.position - right.position) .map(record => record.message), @@ -98,7 +99,7 @@ export const touchStoredConversation = async (id: string, lastActiveAt: number) const database = await openWorkspaceDatabase() const conversation = await database.get('conversations', id) if (!conversation) throw new Error('Conversation is unavailable.') - const updated = { ...conversation, lastActiveAt } + const updated = { ...returnQueuedToDraft(conversation), lastActiveAt } await database.put('conversations', updated) return updated } diff --git a/ui-packages/web/src/features/agent/create-reader-agent.ts b/ui-packages/web/src/features/agent/create-reader-agent.ts index cab1753..af2b114 100644 --- a/ui-packages/web/src/features/agent/create-reader-agent.ts +++ b/ui-packages/web/src/features/agent/create-reader-agent.ts @@ -99,6 +99,7 @@ export const createReaderAgent = ( const agent = new Agent({ sessionId: session.id, toolExecution: 'sequential', + steeringMode: 'all', initialState: { model: session.model, thinkingLevel: session.thinkingLevel, diff --git a/ui-packages/web/src/features/conversation/composer/index.tsx b/ui-packages/web/src/features/conversation/composer/index.tsx index abe9a08..ad98304 100644 --- a/ui-packages/web/src/features/conversation/composer/index.tsx +++ b/ui-packages/web/src/features/conversation/composer/index.tsx @@ -1,9 +1,11 @@ import { ArrowUp, Paperclip, Square } from 'lucide-react' import { type DragEvent, type RefObject, useLayoutEffect, useRef, useState } from 'react' +import type { ConversationDraft } from '../../../core/conversations' import { DraftAttachmentTray } from '../conversation-attachments' import { ConversationModelControl, type ModelControlProps } from '../model-control' import type { ConversationPhase } from '../use-conversation' import type { DraftAttachment } from '../use-draft-attachments' +import { QueuedMessages } from './queued-messages' import styles from './style.module.scss' type ComposerProps = { @@ -14,6 +16,8 @@ type ComposerProps = { inputRef: RefObject draft: string phase: ConversationPhase + queued: readonly ConversationDraft[] + onRemoveQueued: (index: number) => void attachments: DraftAttachment[] limitReached: boolean unsettled: boolean @@ -40,6 +44,8 @@ export const ConversationComposer = ({ onConfigureModels, draft, phase, + queued, + onRemoveQueued, attachments, limitReached, unsettled, @@ -57,8 +63,9 @@ export const ConversationComposer = ({ const running = phase === 'running' || phase === 'stopping' const readyAttachments = attachments.filter(item => item.status === 'ready') const hasUnavailable = readyAttachments.some(item => !availableFileIds.has(item.metadata.id)) + // While a reply runs, sending queues the message. const canSend = - phase === 'ready' && + (phase === 'ready' || running) && !unsettled && !hasUnavailable && Boolean(draft.trim() || readyAttachments.length) @@ -100,6 +107,7 @@ export const ConversationComposer = ({ }} onDrop={addDroppedFiles} > + { - if ( - event.key !== 'Enter' || - event.shiftKey || - event.nativeEvent.isComposing || - event.keyCode === 229 - ) + if (event.nativeEvent.isComposing || event.keyCode === 229) return + if (event.key === 'Escape' && running) { + event.preventDefault() + onStop() return + } + if (event.key !== 'Enter' || event.shiftKey) return event.preventDefault() if (canSend) onSend() }} @@ -168,16 +176,30 @@ export const ConversationComposer = ({ /> )} {limitReached && 10 attachments maximum} - + {running && ( + + )} + {(!running || canSend) && ( + + )} {dragging && Drop files to attach} diff --git a/ui-packages/web/src/features/conversation/composer/queued-messages.tsx b/ui-packages/web/src/features/conversation/composer/queued-messages.tsx new file mode 100644 index 0000000..cdd39d9 --- /dev/null +++ b/ui-packages/web/src/features/conversation/composer/queued-messages.tsx @@ -0,0 +1,40 @@ +import { Paperclip, X } from 'lucide-react' +import type { ConversationDraft } from '../../../core/conversations' +import styles from './style.module.scss' + +export const QueuedMessages = ({ + queued, + onRemove, +}: { + queued: readonly ConversationDraft[] + onRemove: (index: number) => void +}) => { + if (!queued.length) return null + return ( +
    + {queued.map((item, index) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: items have no identity; the list only appends and removes +
  • + + {item.text || item.attachments.map(attachment => attachment.name).join(', ')} + + {item.attachments.length > 0 && ( + + + {item.attachments.length} + + )} + +
  • + ))} +
+ ) +} diff --git a/ui-packages/web/src/features/conversation/composer/style.module.scss b/ui-packages/web/src/features/conversation/composer/style.module.scss index fb89766..88b1bb8 100644 --- a/ui-packages/web/src/features/conversation/composer/style.module.scss +++ b/ui-packages/web/src/features/conversation/composer/style.module.scss @@ -78,6 +78,45 @@ background: var(--accent); color: var(--surface); } +.bottom .sendButton + .sendButton { + margin-left: 6px; +} +.queued { + display: grid; + gap: 4px; + margin: 0 0 8px; + padding: 0; + list-style: none; +} +.queuedItem { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + padding: 3px 4px 3px 8px; + border-radius: 5px; + background: oklch(0.96 0 0); + color: var(--muted); + font-size: 12px; +} +.queuedItem > button { + flex-shrink: 0; + width: 22px; + height: 22px; +} +.queuedText { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.queuedAttachments { + display: inline-flex; + align-items: center; + gap: 2px; + flex-shrink: 0; +} @media (max-width: 599px) { .composer textarea { diff --git a/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx b/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx index 4a339d4..da95d43 100644 --- a/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx +++ b/ui-packages/web/src/features/conversation/conversation-panel.integration.test.tsx @@ -304,7 +304,7 @@ describe('conversation', () => { const requests: RequestInit[] = [] vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { if (url === '/api/agent/config') return Response.json(config) - if (init) requests.push(init) + if (init && !isTitleRequest(init)) requests.push(init) return new Response( new ReadableStream({ start(value) { @@ -340,8 +340,10 @@ describe('conversation', () => { expect(requests).toHaveLength(1) await user.click(screen.getByRole('button', { name: 'Close reading assistant' })) await user.click(screen.getByRole('button', { name: 'Open reading assistant' })) - expect(question()).toHaveValue('Next question') + const queue = screen.getByRole('list', { name: 'Queued messages' }) + expect(within(queue).getByText('Next question')).toBeVisible() expect(screen.getByText('First words')).toBeVisible() + await user.click(within(queue).getByRole('button', { name: 'Remove queued message' })) await act(async () => { controller?.enqueue( new TextEncoder().encode( @@ -350,7 +352,8 @@ describe('conversation', () => { ) controller?.close() }) - await waitFor(() => expect(send()).toBeEnabled()) + await waitFor(() => expect(screen.getByRole('combobox', { name: 'Chat model' })).toBeEnabled()) + expect(requests).toHaveLength(1) expect(screen.getByText('First words').tagName).toBe('STRONG') }) @@ -412,6 +415,101 @@ describe('conversation', () => { expect(await screen.findByText('Ready again')).toBeVisible() }) + it('queues a message during a reply and gives it to the model at the next turn', async () => { + const user = userEvent.setup({ delay: null }) + const bodies: { messages: { role: string; content: unknown }[] }[] = [] + let releaseToolCall = () => {} + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + if (url === '/api/agent/config') return Response.json(config) + if (isTitleRequest(init)) return complete('Title') + bodies.push(JSON.parse(String(init?.body))) + if (bodies.length > 1) return complete('Checked both') + return new Response( + new ReadableStream({ + start(controller) { + releaseToolCall = () => { + controller.enqueue( + new TextEncoder().encode( + `${event( + { + tool_calls: [ + { + index: 0, + id: 'state-call', + type: 'function', + function: { name: 'get_reader_state', arguments: '{}' }, + }, + ], + }, + 'tool_calls', + )}data: [DONE]\n\n`, + ), + ) + controller.close() + } + }, + }), + { headers: { 'Content-Type': 'text/event-stream' } }, + ) + }) + open() + await waitFor(() => expect(question()).toBeEnabled()) + await user.type(question(), 'What am I reading?') + await user.click(send()) + await waitFor(() => expect(bodies).toHaveLength(1)) + await user.type(question(), 'Also list the open files{Enter}') + + const queue = screen.getByRole('list', { name: 'Queued messages' }) + expect(within(queue).getByText('Also list the open files')).toBeVisible() + expect(question()).toHaveValue('') + act(() => releaseToolCall()) + + expect(await screen.findByText('Checked both')).toBeVisible() + const sent = bodies[1]?.messages ?? [] + expect(sent.at(-2)?.role).toBe('tool') + expect(sent.at(-1)?.role).toBe('user') + expect(JSON.stringify(sent.at(-1)?.content)).toContain('Also list the open files') + expect(screen.queryByRole('list', { name: 'Queued messages' })).not.toBeInTheDocument() + }) + + it('sends queued messages as soon as Escape stops the reply', async () => { + const user = userEvent.setup({ delay: null }) + const bodies: { messages: { role: string; content: unknown }[] }[] = [] + let signal: AbortSignal | null | undefined + vi.spyOn(globalThis, 'fetch').mockImplementation(async (url, init) => { + if (url === '/api/agent/config') return Response.json(config) + if (isTitleRequest(init)) return complete('Title') + bodies.push(JSON.parse(String(init?.body))) + if (bodies.length > 1) return complete('Answered the follow-up') + signal = init?.signal + return new Response( + new ReadableStream({ + start(controller) { + signal?.addEventListener( + 'abort', + () => controller.error(new DOMException('Aborted', 'AbortError')), + { once: true }, + ) + }, + }), + { headers: { 'Content-Type': 'text/event-stream' } }, + ) + }) + open() + await waitFor(() => expect(question()).toBeEnabled()) + await user.type(question(), 'Summarize everything') + await user.click(send()) + await waitFor(() => expect(bodies).toHaveLength(1)) + await user.type(question(), 'Only the first chapter{Enter}') + await user.keyboard('{Escape}') + + expect(await screen.findByText('Generation stopped.')).toBeVisible() + expect(signal?.aborted).toBe(true) + expect(await screen.findByText('Answered the follow-up')).toBeVisible() + expect(screen.queryByRole('list', { name: 'Queued messages' })).not.toBeInTheDocument() + expect(JSON.stringify(bodies[1]?.messages.at(-1)?.content)).toContain('Only the first chapter') + }) + it('switches between isolated conversations and restores the active transcript', async () => { const user = userEvent.setup({ delay: null }) const requests: Array<{ messages: Array<{ role: string; content: unknown }> }> = [] diff --git a/ui-packages/web/src/features/conversation/conversation-panel.tsx b/ui-packages/web/src/features/conversation/conversation-panel.tsx index 7986814..66e95e9 100644 --- a/ui-packages/web/src/features/conversation/conversation-panel.tsx +++ b/ui-packages/web/src/features/conversation/conversation-panel.tsx @@ -43,6 +43,8 @@ export const ConversationPanel = ({ renameConversation, send, stop, + queued, + removeQueued, draftAttachments, } = conversation const running = phase === 'running' || phase === 'stopping' @@ -134,6 +136,8 @@ export const ConversationPanel = ({ inputRef={inputRef} draft={draft} phase={phase} + queued={queued} + onRemoveQueued={removeQueued} attachments={draftAttachments.attachments} limitReached={draftAttachments.limitReached} unsettled={draftAttachments.unsettled} @@ -142,7 +146,7 @@ export const ConversationPanel = ({ onRetry={key => void draftAttachments.retry(key)} onRemove={draftAttachments.remove} onOpenFile={onOpenFile} - onSend={() => void send()} + onSend={send} onStop={stop} availableFileIds={availableFileIds} /> diff --git a/ui-packages/web/src/features/conversation/use-conversation.ts b/ui-packages/web/src/features/conversation/use-conversation.ts index 53df6a0..2950f5b 100644 --- a/ui-packages/web/src/features/conversation/use-conversation.ts +++ b/ui-packages/web/src/features/conversation/use-conversation.ts @@ -15,6 +15,7 @@ import { type ConversationId, conversationTitle, emptyConversationDraft, + foldQueued, type ModelSelection, type StoredConversation, type TitleSource, @@ -146,6 +147,15 @@ const snapshot = ( ] } +// A turn that ended this way stops the run, so the library would never read a steered message. +const runContinues = (message: AgentMessage) => + message.role === 'assistant' && message.stopReason !== 'error' && message.stopReason !== 'aborted' + +const failedRun = (agent: Agent) => { + const last = agent.state.messages.at(-1) + return last?.role === 'assistant' && last.stopReason === 'error' +} + const displayMessages = ( messages: readonly AgentMessage[], statuses: ReadonlyMap, @@ -196,6 +206,7 @@ export const useConversation = ( const readyDraftAttachments = draftAttachments.ready const settleDraftAttachments = draftAttachments.settle const replaceDraftAttachments = draftAttachments.replaceReady + const restoreDraftAttachments = draftAttachments.restore const reportStorageError = useCallback((cause: unknown) => { console.error('Unable to save conversation', cause) @@ -260,6 +271,31 @@ export const useConversation = ( [queueDraft], ) + const setQueued = useCallback((queued: ConversationDraft[]) => { + const next = { ...activeRef.current, queued } + activeRef.current = next + setActive(next) + }, []) + + // Not saved here: the next message_end writes the emptied queue and the message in one transaction. + const takeQueued = useCallback(() => { + const queued = activeRef.current.queued ?? [] + if (queued.length) setQueued([]) + return queued + }, [setQueued]) + + const restoreToDraft = useCallback( + (items: readonly ConversationDraft[]) => { + if (!items.length) return + const next = foldQueued(currentDraft(), items) + draftRef.current = next.text + setDraftState(next.text) + restoreDraftAttachments(items.flatMap(item => item.attachments)) + updateActiveDraft(next) + }, + [currentDraft, restoreDraftAttachments, updateActiveDraft], + ) + // The active conversation is written whole from memory, so its title changes there; any other // is changed in storage. A title the reader chose is never replaced by one the model suggests. const applyTitle = useCallback( @@ -346,11 +382,13 @@ export const useConversation = ( const disposeAgent = useCallback( async (saveDraft: boolean) => { const agent = agentRef.current + // Taken before stopping, so the run does not send it to an agent about to be dropped. + const queued = takeQueued() if (agent?.state.isStreaming) agent.abort() if (agent) await agent.waitForIdle() await settleDraftAttachments() if (saveDraft) { - updateActiveDraft(currentDraft()) + updateActiveDraft(foldQueued(currentDraft(), queued)) await queueDraft(activeRef.current) } await draftQueue.current.running @@ -359,7 +397,7 @@ export const useConversation = ( agentRef.current = null busy.current = false }, - [currentDraft, queueDraft, settleDraftAttachments, updateActiveDraft], + [currentDraft, queueDraft, settleDraftAttachments, takeQueued, updateActiveDraft], ) const attachAgent = useCallback( @@ -401,6 +439,10 @@ export const useConversation = ( } agentRef.current = agent unsubscribeRef.current = agent.subscribe(async (event, signal) => { + if (event.type === 'turn_end' && !signal.aborted && runContinues(event.message)) + takeQueued().forEach(item => { + agent.steer(createReaderUserMessage(item.text, item.attachments)) + }) if (event.type === 'tool_execution_start') statuses.current.set(event.toolCallId, 'Running') if (event.type === 'tool_execution_end') statuses.current.set( @@ -413,7 +455,7 @@ export const useConversation = ( setError(undefined) setPhase('ready') }, - [persistAgentMessages, refresh, tools], + [persistAgentMessages, refresh, takeQueued, tools], ) const showSession = useCallback( @@ -643,53 +685,37 @@ export const useConversation = ( .catch(cause => console.error('Unable to name the conversation', cause)) } - const send = async () => { - const agent = agentRef.current - const text = draftRef.current.trim() - if ( - !agent || - busy.current || - draftAttachments.unsettled || - (!text && !draftAttachments.attachments.length) - ) - return - const outgoingAttachments = draftAttachments.takeReady() - const message = createReaderUserMessage( - text, - outgoingAttachments.map(item => item.metadata), - ) - const current = activeRef.current - const submitted = { - ...current, - title: current.title ?? conversationTitle({ text, attachments: message.reader.attachments }), - draft: emptyConversationDraft(), - lastActiveAt: nextActivityTime(current), - } - activeRef.current = submitted - setActive(submitted) - void queueDraft(submitted) + // Queued messages join the run at its next turn; whatever is left when it stops, including after + // an abort, is sent as the next prompt. A failed run hands them back as the draft. + const run = async (agent: Agent, batch: readonly ConversationDraft[]) => { busy.current = true - setPhase('running') setError(undefined) - draftRef.current = '' - setDraftState('') try { - await agent.prompt(message) - nameConversation(agent, submitted.id, message.reader) - } catch (cause) { - const recorded = agent.state.messages.some( - item => isReaderUserMessage(item) && item.reader.id === message.reader.id, - ) - if (agentRef.current === agent) { - setError(cause instanceof Error ? cause.message : 'Could not send the message.') - if (!recorded) { - draftRef.current = text - setDraftState(text) - draftAttachments.restore(outgoingAttachments) - updateActiveDraft({ - text, - attachments: outgoingAttachments.map(item => item.metadata), - }) + for (let items = batch; items.length; items = takeQueued()) { + setPhase('running') + const sending = items.map(item => ({ + item, + message: createReaderUserMessage(item.text, item.attachments), + })) + try { + await agent.prompt(sending.map(entry => entry.message)) + } catch (cause) { + if (agentRef.current !== agent) return + setError(cause instanceof Error ? cause.message : 'Could not send the message.') + const recorded = new Set( + agent.state.messages.flatMap(item => + isReaderUserMessage(item) ? [item.reader.id] : [], + ), + ) + const unsent = sending.filter(entry => !recorded.has(entry.message.reader.id)) + restoreToDraft([...unsent.map(entry => entry.item), ...takeQueued()]) + return + } + if (agentRef.current !== agent) return + nameConversation(agent, activeRef.current.id, foldQueued(emptyConversationDraft(), items)) + if (failedRun(agent)) { + restoreToDraft(takeQueued()) + return } } } finally { @@ -704,6 +730,34 @@ export const useConversation = ( } } + const send = () => { + const agent = agentRef.current + const text = draftRef.current.trim() + if (!agent || draftAttachments.unsettled || (!text && !draftAttachments.attachments.length)) + return + const item = { text, attachments: draftAttachments.takeReady().map(entry => entry.metadata) } + const current = activeRef.current + const queuing = busy.current + const submitted = { + ...current, + title: current.title ?? conversationTitle(item), + draft: emptyConversationDraft(), + queued: queuing ? [...(current.queued ?? []), item] : current.queued, + lastActiveAt: nextActivityTime(current), + } + activeRef.current = submitted + setActive(submitted) + void queueDraft(submitted, queuing) + draftRef.current = '' + setDraftState('') + if (!queuing) void run(agent, [item]) + } + + const removeQueued = (index: number) => { + setQueued((activeRef.current.queued ?? []).filter((_, position) => position !== index)) + void queueDraft(activeRef.current, true) + } + const configureModel = (selection: ModelSelection) => { const config = configRef.current const agent = agentRef.current @@ -772,6 +826,8 @@ export const useConversation = ( renameConversation: (id: ConversationId, title: string) => applyTitle(id, title, 'reader'), send, stop, + queued: active.queued ?? [], + removeQueued, draftAttachments, modelConfiguration: runtime && selection ? { providers: runtime.providers, selection } : null, selectModel: (model: ModelReference) => { diff --git a/ui-packages/web/src/features/conversation/use-draft-attachments.ts b/ui-packages/web/src/features/conversation/use-draft-attachments.ts index f6f26a1..8df9b93 100644 --- a/ui-packages/web/src/features/conversation/use-draft-attachments.ts +++ b/ui-packages/web/src/features/conversation/use-draft-attachments.ts @@ -166,9 +166,13 @@ export const useDraftAttachments = (importFiles: AddWorkspaceAttachments) => { return ready }, [update]) + // Restored files may pass the limit; adding is refused until some are removed, none are dropped. const restore = useCallback( - (items: readonly Extract[]) => - update(current => [...items, ...current].slice(0, maximumDraftAttachments)), + (items: readonly ConversationAttachment[]) => + update(current => [ + ...items.map(metadata => ({ key: nanoid(), metadata, status: 'ready' as const })), + ...current, + ]), [update], )